@urun-sh/core 0.5.3 → 0.5.5
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.
- package/dist/{chunk-2IZQGJA3.mjs → chunk-JFRHVRUS.mjs} +2 -2
- package/dist/{chunk-PJ3QK656.mjs → chunk-STXAJ5OB.mjs} +4 -4
- package/dist/index.browser.d.mts +2 -2
- package/dist/index.browser.d.ts +2 -2
- package/dist/index.browser.js +2 -2
- package/dist/index.browser.mjs +1 -1
- package/dist/index.d.mts +2 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +5 -5
- package/dist/index.mjs +1 -1
- package/dist/internal.browser.d.mts +1 -1
- package/dist/internal.browser.d.ts +1 -1
- package/dist/internal.browser.js +2 -2
- package/dist/internal.browser.mjs +1 -1
- package/dist/internal.d.mts +1 -1
- package/dist/internal.d.ts +1 -1
- package/dist/internal.js +4 -4
- package/dist/internal.mjs +1 -1
- package/dist/{stream-data-DoU_1K17.d.mts → stream-data-77pUfFQK.d.mts} +2 -0
- package/dist/{stream-data-DoU_1K17.d.ts → stream-data-77pUfFQK.d.ts} +2 -0
- package/package.json +2 -2
package/dist/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
|
-
"use strict";var gu=Object.create;var rn=Object.defineProperty;var _u=Object.getOwnPropertyDescriptor;var vu=Object.getOwnPropertyNames;var wu=Object.getPrototypeOf,yu=Object.prototype.hasOwnProperty;var bu=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var D=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},yo=(r,e)=>{for(var t in e)rn(r,t,{get:e[t],enumerable:!0})},bo=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of vu(e))!yu.call(r,s)&&s!==t&&rn(r,s,{get:()=>e[s],enumerable:!(n=_u(e,s))||n.enumerable});return r};var Ke=(r,e,t)=>(t=r!=null?gu(wu(r)):{},bo(e||!r||!r.__esModule?rn(t,"default",{value:r,enumerable:!0}):t,r)),So=r=>bo(rn({},"__esModule",{value:!0}),r);var ta=D((ug,ea)=>{"use strict";var It=1e3,At=It*60,Lt=At*60,at=Lt*24,cl=at*7,dl=at*365.25;ea.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return ul(r);if(t==="number"&&isFinite(r))return e.long?pl(r):ll(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function ul(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*dl;case"weeks":case"week":case"w":return t*cl;case"days":case"day":case"d":return t*at;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Lt;case"minutes":case"minute":case"mins":case"min":case"m":return t*At;case"seconds":case"second":case"secs":case"sec":case"s":return t*It;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function ll(r){var e=Math.abs(r);return e>=at?Math.round(r/at)+"d":e>=Lt?Math.round(r/Lt)+"h":e>=At?Math.round(r/At)+"m":e>=It?Math.round(r/It)+"s":r+"ms"}function pl(r){var e=Math.abs(r);return e>=at?fn(r,e,at,"day"):e>=Lt?fn(r,e,Lt,"hour"):e>=At?fn(r,e,At,"minute"):e>=It?fn(r,e,It,"second"):r+" ms"}function fn(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var Ws=D((lg,ra)=>{"use strict";function hl(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=ta(),t.destroy=u,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let l=0;for(let p=0;p<d.length;p++)l=(l<<5)-l+d.charCodeAt(p),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(d){let l,p=null,f,h;function m(...g){if(!m.enabled)return;let _=m,v=Number(new Date),y=v-(l||v);_.diff=y,_.prev=l,_.curr=v,l=v,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let S=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(b,O)=>{if(b==="%%")return"%";S++;let j=t.formatters[O];if(typeof j=="function"){let F=g[S];b=j.call(_,F),g.splice(S,1),S--}return b}),t.formatArgs.call(_,g),(_.log||t.log).apply(_,g)}return m.namespace=d,m.useColors=t.useColors(),m.color=t.selectColor(d),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(f!==t.namespaces&&(f=t.namespaces,h=t.enabled(d)),h),set:g=>{p=g}}),typeof t.init=="function"&&t.init(m),m}function n(d,l){let p=t(this.namespace+(typeof l>"u"?":":l)+d);return p.log=this.log,p}function s(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let l=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let p of l)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function i(d,l){let p=0,f=0,h=-1,m=0;for(;p<d.length;)if(f<l.length&&(l[f]===d[p]||l[f]==="*"))l[f]==="*"?(h=f,m=p,f++):(p++,f++);else if(h!==-1)f=h+1,m++,p=m;else return!1;for(;f<l.length&&l[f]==="*";)f++;return f===l.length}function o(){let d=[...t.names,...t.skips.map(l=>"-"+l)].join(",");return t.enable(""),d}function a(d){for(let l of t.skips)if(i(d,l))return!1;for(let l of t.names)if(i(d,l))return!0;return!1}function c(d){return d instanceof Error?d.stack||d.message:d}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}ra.exports=hl});var na=D((le,mn)=>{"use strict";le.formatArgs=ml;le.save=gl;le.load=_l;le.useColors=fl;le.storage=vl();le.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();le.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function fl(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function ml(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+mn.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}le.log=console.debug||console.log||(()=>{});function gl(r){try{r?le.storage.setItem("debug",r):le.storage.removeItem("debug")}catch{}}function _l(){let r;try{r=le.storage.getItem("debug")||le.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function vl(){try{return localStorage}catch{}}mn.exports=Ws()(le);var{formatters:wl}=mn.exports;wl.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var ia={};yo(ia,{createSupportsColor:()=>qs,default:()=>Tl});function ve(r,e=globalThis.Deno?globalThis.Deno.args:_n.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}function yl(){if(!("FORCE_COLOR"in B))return;if(B.FORCE_COLOR==="true")return 1;if(B.FORCE_COLOR==="false")return 0;if(B.FORCE_COLOR.length===0)return 1;let r=Math.min(Number.parseInt(B.FORCE_COLOR,10),3);if([0,1,2,3].includes(r))return r}function bl(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function Sl(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let n=yl();n!==void 0&&(gn=n);let s=t?gn:n;if(s===0)return 0;if(t){if(ve("color=16m")||ve("color=full")||ve("color=truecolor"))return 3;if(ve("color=256"))return 2}if("TF_BUILD"in B&&"AGENT_NAME"in B)return 1;if(r&&!e&&s===void 0)return 0;let i=s||0;if(B.TERM==="dumb")return i;if(_n.default.platform==="win32"){let o=sa.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in B)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in B)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in B)||B.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in B)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(B.TEAMCITY_VERSION)?1:0;if(B.COLORTERM==="truecolor"||B.TERM==="xterm-kitty"||B.TERM==="xterm-ghostty"||B.TERM==="wezterm")return 3;if("TERM_PROGRAM"in B){let o=Number.parseInt((B.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(B.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(B.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(B.TERM)||"COLORTERM"in B?1:i}function qs(r,e={}){let t=Sl(r,{streamIsTTY:r&&r.isTTY,...e});return bl(t)}var _n,sa,js,B,gn,kl,Tl,oa=bu(()=>{"use strict";_n=Ke(require("process"),1),sa=Ke(require("os"),1),js=Ke(require("tty"),1);({env:B}=_n.default);ve("no-color")||ve("no-colors")||ve("color=false")||ve("color=never")?gn=0:(ve("color")||ve("colors")||ve("color=true")||ve("color=always"))&&(gn=1);kl={stdout:qs({isTTY:js.default.isatty(1)}),stderr:qs({isTTY:js.default.isatty(2)})},Tl=kl});var ca=D((J,wn)=>{"use strict";var Rl=require("tty"),vn=require("util");J.init=Al;J.log=Dl;J.formatArgs=El;J.save=xl;J.load=Il;J.useColors=Cl;J.destroy=vn.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");J.colors=[6,2,3,4,5,1];try{let r=(oa(),So(ia));r&&(r.stderr||r).level>=2&&(J.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}J.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function Cl(){return"colors"in J.inspectOpts?!!J.inspectOpts.colors:Rl.isatty(process.stderr.fd)}function El(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${e} \x1B[0m`;r[0]=i+r[0].split(`
|
|
1
|
+
"use strict";var _u=Object.create;var nn=Object.defineProperty;var vu=Object.getOwnPropertyDescriptor;var wu=Object.getOwnPropertyNames;var yu=Object.getPrototypeOf,bu=Object.prototype.hasOwnProperty;var Su=(r,e,t)=>()=>{if(t)throw t[0];try{return r&&(e=r(r=0)),e}catch(n){throw t=[n],n}};var D=(r,e)=>()=>{try{return e||r((e={exports:{}}).exports,e),e.exports}catch(t){throw e=0,t}},ko=(r,e)=>{for(var t in e)nn(r,t,{get:e[t],enumerable:!0})},To=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of wu(e))!bu.call(r,s)&&s!==t&&nn(r,s,{get:()=>e[s],enumerable:!(n=vu(e,s))||n.enumerable});return r};var Ye=(r,e,t)=>(t=r!=null?_u(yu(r)):{},To(e||!r||!r.__esModule?nn(t,"default",{value:r,enumerable:!0}):t,r)),Ro=r=>To(nn({},"__esModule",{value:!0}),r);var na=D((lg,ra)=>{"use strict";var At=1e3,Lt=At*60,Mt=Lt*60,ct=Mt*24,dl=ct*7,ul=ct*365.25;ra.exports=function(r,e){e=e||{};var t=typeof r;if(t==="string"&&r.length>0)return ll(r);if(t==="number"&&isFinite(r))return e.long?hl(r):pl(r);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(r))};function ll(r){if(r=String(r),!(r.length>100)){var e=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(r);if(e){var t=parseFloat(e[1]),n=(e[2]||"ms").toLowerCase();switch(n){case"years":case"year":case"yrs":case"yr":case"y":return t*ul;case"weeks":case"week":case"w":return t*dl;case"days":case"day":case"d":return t*ct;case"hours":case"hour":case"hrs":case"hr":case"h":return t*Mt;case"minutes":case"minute":case"mins":case"min":case"m":return t*Lt;case"seconds":case"second":case"secs":case"sec":case"s":return t*At;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return t;default:return}}}}function pl(r){var e=Math.abs(r);return e>=ct?Math.round(r/ct)+"d":e>=Mt?Math.round(r/Mt)+"h":e>=Lt?Math.round(r/Lt)+"m":e>=At?Math.round(r/At)+"s":r+"ms"}function hl(r){var e=Math.abs(r);return e>=ct?mn(r,e,ct,"day"):e>=Mt?mn(r,e,Mt,"hour"):e>=Lt?mn(r,e,Lt,"minute"):e>=At?mn(r,e,At,"second"):r+" ms"}function mn(r,e,t,n){var s=e>=t*1.5;return Math.round(r/t)+" "+n+(s?"s":"")}});var qs=D((pg,sa)=>{"use strict";function fl(r){t.debug=t,t.default=t,t.coerce=c,t.disable=o,t.enable=s,t.enabled=a,t.humanize=na(),t.destroy=u,Object.keys(r).forEach(d=>{t[d]=r[d]}),t.names=[],t.skips=[],t.formatters={};function e(d){let l=0;for(let p=0;p<d.length;p++)l=(l<<5)-l+d.charCodeAt(p),l|=0;return t.colors[Math.abs(l)%t.colors.length]}t.selectColor=e;function t(d){let l,p=null,f,h;function m(...g){if(!m.enabled)return;let _=m,v=Number(new Date),y=v-(l||v);_.diff=y,_.prev=l,_.curr=v,l=v,g[0]=t.coerce(g[0]),typeof g[0]!="string"&&g.unshift("%O");let S=0;g[0]=g[0].replace(/%([a-zA-Z%])/g,(b,L)=>{if(b==="%%")return"%";S++;let q=t.formatters[L];if(typeof q=="function"){let W=g[S];b=q.call(_,W),g.splice(S,1),S--}return b}),t.formatArgs.call(_,g),(_.log||t.log).apply(_,g)}return m.namespace=d,m.useColors=t.useColors(),m.color=t.selectColor(d),m.extend=n,m.destroy=t.destroy,Object.defineProperty(m,"enabled",{enumerable:!0,configurable:!1,get:()=>p!==null?p:(f!==t.namespaces&&(f=t.namespaces,h=t.enabled(d)),h),set:g=>{p=g}}),typeof t.init=="function"&&t.init(m),m}function n(d,l){let p=t(this.namespace+(typeof l>"u"?":":l)+d);return p.log=this.log,p}function s(d){t.save(d),t.namespaces=d,t.names=[],t.skips=[];let l=(typeof d=="string"?d:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(let p of l)p[0]==="-"?t.skips.push(p.slice(1)):t.names.push(p)}function i(d,l){let p=0,f=0,h=-1,m=0;for(;p<d.length;)if(f<l.length&&(l[f]===d[p]||l[f]==="*"))l[f]==="*"?(h=f,m=p,f++):(p++,f++);else if(h!==-1)f=h+1,m++,p=m;else return!1;for(;f<l.length&&l[f]==="*";)f++;return f===l.length}function o(){let d=[...t.names,...t.skips.map(l=>"-"+l)].join(",");return t.enable(""),d}function a(d){for(let l of t.skips)if(i(d,l))return!1;for(let l of t.names)if(i(d,l))return!0;return!1}function c(d){return d instanceof Error?d.stack||d.message:d}function u(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")}return t.enable(t.load()),t}sa.exports=fl});var ia=D((pe,gn)=>{"use strict";pe.formatArgs=gl;pe.save=_l;pe.load=vl;pe.useColors=ml;pe.storage=wl();pe.destroy=(()=>{let r=!1;return()=>{r||(r=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})();pe.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"];function ml(){if(typeof window<"u"&&window.process&&(window.process.type==="renderer"||window.process.__nwjs))return!0;if(typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let r;return typeof document<"u"&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||typeof window<"u"&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||typeof navigator<"u"&&navigator.userAgent&&(r=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(r[1],10)>=31||typeof navigator<"u"&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)}function gl(r){if(r[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+r[0]+(this.useColors?"%c ":" ")+"+"+gn.exports.humanize(this.diff),!this.useColors)return;let e="color: "+this.color;r.splice(1,0,e,"color: inherit");let t=0,n=0;r[0].replace(/%[a-zA-Z%]/g,s=>{s!=="%%"&&(t++,s==="%c"&&(n=t))}),r.splice(n,0,e)}pe.log=console.debug||console.log||(()=>{});function _l(r){try{r?pe.storage.setItem("debug",r):pe.storage.removeItem("debug")}catch{}}function vl(){let r;try{r=pe.storage.getItem("debug")||pe.storage.getItem("DEBUG")}catch{}return!r&&typeof process<"u"&&"env"in process&&(r=process.env.DEBUG),r}function wl(){try{return localStorage}catch{}}gn.exports=qs()(pe);var{formatters:yl}=gn.exports;yl.j=function(r){try{return JSON.stringify(r)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}});var aa={};ko(aa,{createSupportsColor:()=>Bs,default:()=>Rl});function we(r,e=globalThis.Deno?globalThis.Deno.args:vn.default.argv){let t=r.startsWith("-")?"":r.length===1?"-":"--",n=e.indexOf(t+r),s=e.indexOf("--");return n!==-1&&(s===-1||n<s)}function bl(){if(!("FORCE_COLOR"in V))return;if(V.FORCE_COLOR==="true")return 1;if(V.FORCE_COLOR==="false")return 0;if(V.FORCE_COLOR.length===0)return 1;let r=Math.min(Number.parseInt(V.FORCE_COLOR,10),3);if([0,1,2,3].includes(r))return r}function Sl(r){return r===0?!1:{level:r,hasBasic:!0,has256:r>=2,has16m:r>=3}}function kl(r,{streamIsTTY:e,sniffFlags:t=!0}={}){let n=bl();n!==void 0&&(_n=n);let s=t?_n:n;if(s===0)return 0;if(t){if(we("color=16m")||we("color=full")||we("color=truecolor"))return 3;if(we("color=256"))return 2}if("TF_BUILD"in V&&"AGENT_NAME"in V)return 1;if(r&&!e&&s===void 0)return 0;let i=s||0;if(V.TERM==="dumb")return i;if(vn.default.platform==="win32"){let o=oa.default.release().split(".");return Number(o[0])>=10&&Number(o[2])>=10586?Number(o[2])>=14931?3:2:1}if("CI"in V)return["GITHUB_ACTIONS","GITEA_ACTIONS","CIRCLECI"].some(o=>o in V)?3:["TRAVIS","APPVEYOR","GITLAB_CI","BUILDKITE","DRONE"].some(o=>o in V)||V.CI_NAME==="codeship"?1:i;if("TEAMCITY_VERSION"in V)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(V.TEAMCITY_VERSION)?1:0;if(V.COLORTERM==="truecolor"||V.TERM==="xterm-kitty"||V.TERM==="xterm-ghostty"||V.TERM==="wezterm")return 3;if("TERM_PROGRAM"in V){let o=Number.parseInt((V.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(V.TERM_PROGRAM){case"iTerm.app":return o>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(V.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(V.TERM)||"COLORTERM"in V?1:i}function Bs(r,e={}){let t=kl(r,{streamIsTTY:r&&r.isTTY,...e});return Sl(t)}var vn,oa,$s,V,_n,Tl,Rl,ca=Su(()=>{"use strict";vn=Ye(require("process"),1),oa=Ye(require("os"),1),$s=Ye(require("tty"),1);({env:V}=vn.default);we("no-color")||we("no-colors")||we("color=false")||we("color=never")?_n=0:(we("color")||we("colors")||we("color=true")||we("color=always"))&&(_n=1);Tl={stdout:Bs({isTTY:$s.default.isatty(1)}),stderr:Bs({isTTY:$s.default.isatty(2)})},Rl=Tl});var ua=D((J,yn)=>{"use strict";var Cl=require("tty"),wn=require("util");J.init=Ll;J.log=Il;J.formatArgs=Pl;J.save=xl;J.load=Al;J.useColors=El;J.destroy=wn.deprecate(()=>{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.");J.colors=[6,2,3,4,5,1];try{let r=(ca(),Ro(aa));r&&(r.stderr||r).level>=2&&(J.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch{}J.inspectOpts=Object.keys(process.env).filter(r=>/^debug_/i.test(r)).reduce((r,e)=>{let t=e.substring(6).toLowerCase().replace(/_([a-z])/g,(s,i)=>i.toUpperCase()),n=process.env[e];return/^(yes|on|true|enabled)$/i.test(n)?n=!0:/^(no|off|false|disabled)$/i.test(n)?n=!1:n==="null"?n=null:n=Number(n),r[t]=n,r},{});function El(){return"colors"in J.inspectOpts?!!J.inspectOpts.colors:Cl.isatty(process.stderr.fd)}function Pl(r){let{namespace:e,useColors:t}=this;if(t){let n=this.color,s="\x1B[3"+(n<8?n:"8;5;"+n),i=` ${s};1m${e} \x1B[0m`;r[0]=i+r[0].split(`
|
|
2
2
|
`).join(`
|
|
3
|
-
`+i),r.push(s+"m+"+
|
|
4
|
-
`)}function xl(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function
|
|
5
|
-
`).map(e=>e.trim()).join(" ")};aa.O=function(r){return this.inspectOpts.colors=this.useColors,vn.inspect(r,this.inspectOpts)}});var xr=D((pg,$s)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?$s.exports=na():$s.exports=ca()});var ua=D(da=>{"use strict";Object.defineProperty(da,"__esModule",{value:!0})});var se=D(yn=>{"use strict";Object.defineProperty(yn,"__esModule",{value:!0});yn.Logger=void 0;var Mt=xr(),Ot="media-client",Bs=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Mt.default)(`${Ot}:${e}`),this._warn=(0,Mt.default)(`${Ot}:WARN:${e}`),this._error=(0,Mt.default)(`${Ot}:ERROR:${e}`)):(this._debug=(0,Mt.default)(Ot),this._warn=(0,Mt.default)(`${Ot}:WARN`),this._error=(0,Mt.default)(`${Ot}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};yn.Logger=Bs});var ba=D((mg,Hs)=>{"use strict";var Ut=typeof Reflect=="object"?Reflect:null,la=Ut&&typeof Ut.apply=="function"?Ut.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},bn;Ut&&typeof Ut.ownKeys=="function"?bn=Ut.ownKeys:Object.getOwnPropertySymbols?bn=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:bn=function(e){return Object.getOwnPropertyNames(e)};function Ll(r){console&&console.warn&&console.warn(r)}var ha=Number.isNaN||function(e){return e!==e};function W(){W.init.call(this)}Hs.exports=W;Hs.exports.once=Nl;W.EventEmitter=W;W.prototype._events=void 0;W.prototype._eventsCount=0;W.prototype._maxListeners=void 0;var pa=10;function Sn(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(W,"defaultMaxListeners",{enumerable:!0,get:function(){return pa},set:function(r){if(typeof r!="number"||r<0||ha(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");pa=r}});W.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};W.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||ha(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function fa(r){return r._maxListeners===void 0?W.defaultMaxListeners:r._maxListeners}W.prototype.getMaxListeners=function(){return fa(this)};W.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s=e==="error",i=this._events;if(i!==void 0)s=s&&i.error===void 0;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=i[e];if(c===void 0)return!1;if(typeof c=="function")la(c,this,t);else for(var u=c.length,d=wa(c,u),n=0;n<u;++n)la(d[n],this,t);return!0};function ma(r,e,t,n){var s,i,o;if(Sn(t),i=r._events,i===void 0?(i=r._events=Object.create(null),r._eventsCount=0):(i.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),i=r._events),o=i[e]),o===void 0)o=i[e]=t,++r._eventsCount;else if(typeof o=="function"?o=i[e]=n?[t,o]:[o,t]:n?o.unshift(t):o.push(t),s=fa(r),s>0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=o.length,Ll(a)}return r}W.prototype.addListener=function(e,t){return ma(this,e,t,!1)};W.prototype.on=W.prototype.addListener;W.prototype.prependListener=function(e,t){return ma(this,e,t,!0)};function Ml(){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 ga(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},s=Ml.bind(n);return s.listener=t,n.wrapFn=s,s}W.prototype.once=function(e,t){return Sn(t),this.on(e,ga(this,e,t)),this};W.prototype.prependOnceListener=function(e,t){return Sn(t),this.prependListener(e,ga(this,e,t)),this};W.prototype.removeListener=function(e,t){var n,s,i,o,a;if(Sn(t),s=this._events,s===void 0)return this;if(n=s[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,i=o;break}if(i<0)return this;i===0?n.shift():Ol(n,i),n.length===1&&(s[e]=n[0]),s.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};W.prototype.off=W.prototype.removeListener;W.prototype.removeAllListeners=function(e){var t,n,s;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),o;for(s=0;s<i.length;++s)o=i[s],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this};function _a(r,e,t){var n=r._events;if(n===void 0)return[];var s=n[e];return s===void 0?[]:typeof s=="function"?t?[s.listener||s]:[s]:t?Ul(s):wa(s,s.length)}W.prototype.listeners=function(e){return _a(this,e,!0)};W.prototype.rawListeners=function(e){return _a(this,e,!1)};W.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):va.call(r,e)};W.prototype.listenerCount=va;function va(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}W.prototype.eventNames=function(){return this._eventsCount>0?bn(this._events):[]};function wa(r,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=r[n];return t}function Ol(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function Ul(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function Nl(r,e){return new Promise(function(t,n){function s(o){r.removeListener(e,i),n(o)}function i(){typeof r.removeListener=="function"&&r.removeListener("error",s),t([].slice.call(arguments))}ya(r,e,i,{once:!0}),e!=="error"&&Fl(r,s,{once:!0})})}function Fl(r,e,t){typeof r.on=="function"&&ya(r,"error",e,t)}function ya(r,e,t,n){if(typeof r.on=="function")n.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function s(i){n.once&&r.removeEventListener(e,s),t(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var pe=D(kn=>{"use strict";Object.defineProperty(kn,"__esModule",{value:!0});kn.EnhancedEventEmitter=void 0;var Wl=ba(),jl=se(),ql=new jl.Logger("EnhancedEventEmitter"),Vs=class extends Wl.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}close(){super.removeAllListeners()}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(n){ql.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,n);try{super.emit("listenererror",e,n)}catch{}return!!super.listenerCount(e)}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}};kn.EnhancedEventEmitter=Vs});var we=D(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.InvalidStateError=Nt.UnsupportedError=void 0;var zs=class r extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,r):this.stack=new Error(e).stack}};Nt.UnsupportedError=zs;var Gs=class r extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,r):this.stack=new Error(e).stack}};Nt.InvalidStateError=Gs});var ct=D(Ir=>{"use strict";Object.defineProperty(Ir,"__esModule",{value:!0});Ir.clone=$l;Ir.generateRandomNumber=Bl;Ir.deepFreeze=Sa;function $l(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}function Bl(){return Math.round(Math.random()*1e7)}function Sa(r){let e=Reflect.ownKeys(r);for(let t of e){let n=r[t];(n&&typeof n=="object"||typeof n=="function")&&Sa(n)}return Object.freeze(r)}});var ka=D(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.Logger=void 0;var Ft=xr(),Wt="h264-profile-level-id",Ks=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Ft.default)(`${Wt}:${e}`),this._warn=(0,Ft.default)(`${Wt}:WARN:${e}`),this._error=(0,Ft.default)(`${Wt}:ERROR:${e}`)):(this._debug=(0,Ft.default)(Wt),this._warn=(0,Ft.default)(`${Wt}:WARN`),this._error=(0,Ft.default)(`${Wt}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};Tn.Logger=Ks});var Da=D(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.ProfileLevelId=X.Level=X.Profile=void 0;X.parseProfileLevelId=Ea;X.profileLevelIdToString=Pa;X.profileToString=Gl;X.levelToString=Kl;X.parseSdpProfileLevelId=dt;X.isSameProfile=Yl;X.isSameProfileAndLevel=Ql;X.generateProfileLevelIdStringForAnswer=Jl;X.supportedLevel=Xl;var Hl=ka(),Pe=new Hl.Logger,q;(function(r){r[r.ConstrainedBaseline=1]="ConstrainedBaseline",r[r.Baseline=2]="Baseline",r[r.Main=3]="Main",r[r.ConstrainedHigh=4]="ConstrainedHigh",r[r.High=5]="High",r[r.PredictiveHigh444=6]="PredictiveHigh444"})(q||(X.Profile=q={}));var k;(function(r){r[r.L1_b=0]="L1_b",r[r.L1=10]="L1",r[r.L1_1=11]="L1_1",r[r.L1_2=12]="L1_2",r[r.L1_3=13]="L1_3",r[r.L2=20]="L2",r[r.L2_1=21]="L2_1",r[r.L2_2=22]="L2_2",r[r.L3=30]="L3",r[r.L3_1=31]="L3_1",r[r.L3_2=32]="L3_2",r[r.L4=40]="L4",r[r.L4_1=41]="L4_1",r[r.L4_2=42]="L4_2",r[r.L5=50]="L5",r[r.L5_1=51]="L5_1",r[r.L5_2=52]="L5_2"})(k||(X.Level=k={}));var jt=class{profile;level;constructor(e,t){this.profile=e,this.level=t}};X.ProfileLevelId=jt;var Vl=new jt(q.ConstrainedBaseline,k.L3_1),Ce=class{mask;masked_value;constructor(e){this.mask=~Ra("x",e),this.masked_value=Ra("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}},Ee=class{profile_idc;profile_iop;profile;constructor(e,t,n){this.profile_idc=e,this.profile_iop=t,this.profile=n}},zl=[new Ee(66,new Ce("x1xx0000"),q.ConstrainedBaseline),new Ee(77,new Ce("1xxx0000"),q.ConstrainedBaseline),new Ee(88,new Ce("11xx0000"),q.ConstrainedBaseline),new Ee(66,new Ce("x0xx0000"),q.Baseline),new Ee(88,new Ce("10xx0000"),q.Baseline),new Ee(77,new Ce("0x0x0000"),q.Main),new Ee(100,new Ce("00000000"),q.High),new Ee(100,new Ce("00001100"),q.ConstrainedHigh),new Ee(244,new Ce("00000000"),q.PredictiveHigh444)],Ta=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:k.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:k.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:k.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:k.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:k.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:k.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:k.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:k.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:k.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:k.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:k.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:k.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:k.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:k.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:k.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:k.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:k.L5_2}];function Ea(r){if(typeof r!="string"||r.length!==6)return;let t=parseInt(r,16);if(t===0)return;let n=t&255,s=t>>8&255,i=t>>16&255,o;switch(n){case k.L1_1:{o=(s&16)!==0?k.L1_b:k.L1_1;break}case k.L1:case k.L1_2:case k.L1_3:case k.L2:case k.L2_1:case k.L2_2:case k.L3:case k.L3_1:case k.L3_2:case k.L4:case k.L4_1:case k.L4_2:case k.L5:case k.L5_1:case k.L5_2:{o=n;break}default:{Pe.warn(`parseProfileLevelId() | unrecognized level_idc [str:${r}, level_idc:${n}]`);return}}for(let a of zl)if(i===a.profile_idc&&a.profile_iop.isMatch(s))return Pe.debug(`parseProfileLevelId() | result [str:${r}, profile:${a.profile}, level:${o}]`),new jt(a.profile,o);Pe.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${r}, profile_idc:${i}, profile_iop:${s}]`)}function Pa(r){if(r.level==k.L1_b)switch(r.profile){case q.ConstrainedBaseline:return"42f00b";case q.Baseline:return"42100b";case q.Main:return"4d100b";default:{Pe.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${r.profile}`);return}}let e;switch(r.profile){case q.ConstrainedBaseline:{e="42e0";break}case q.Baseline:{e="4200";break}case q.Main:{e="4d00";break}case q.ConstrainedHigh:{e="640c";break}case q.High:{e="6400";break}case q.PredictiveHigh444:{e="f400";break}default:{Pe.warn(`profileLevelIdToString() | unrecognized profile ${r.profile}`);return}}let t=r.level.toString(16);return t.length===1&&(t=`0${t}`),`${e}${t}`}function Gl(r){switch(r){case q.ConstrainedBaseline:return"ConstrainedBaseline";case q.Baseline:return"Baseline";case q.Main:return"Main";case q.ConstrainedHigh:return"ConstrainedHigh";case q.High:return"High";case q.PredictiveHigh444:return"PredictiveHigh444";default:{Pe.warn(`profileToString() | unrecognized profile ${r}`);return}}}function Kl(r){switch(r){case k.L1_b:return"1b";case k.L1:return"1";case k.L1_1:return"1.1";case k.L1_2:return"1.2";case k.L1_3:return"1.3";case k.L2:return"2";case k.L2_1:return"2.1";case k.L2_2:return"2.2";case k.L3:return"3";case k.L3_1:return"3.1";case k.L3_2:return"3.2";case k.L4:return"4";case k.L4_1:return"4.1";case k.L4_2:return"4.2";case k.L5:return"5";case k.L5_1:return"5.1";case k.L5_2:return"5.2";default:{Pe.warn(`levelToString() | unrecognized level ${r}`);return}}}function dt(r={}){let e=r["profile-level-id"];return e?Ea(e):Vl}function Yl(r={},e={}){let t=dt(r),n=dt(e);return!!(t&&n&&t.profile===n.profile)}function Ql(r={},e={}){let t=dt(r),n=dt(e);return!!(t&&n&&t.profile===n.profile&&t.level==n.level)}function Jl(r={},e={}){if(!r["profile-level-id"]&&!e["profile-level-id"]){Pe.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");return}let t=dt(r),n=dt(e);if(!t)throw new TypeError("invalid local_profile_level_id");if(!n)throw new TypeError("invalid remote_profile_level_id");if(t.profile!==n.profile)throw new TypeError("H264 Profile mismatch");let s=Ca(r)&&Ca(e),i=t.level,o=n.level,a=ep(i,o),c=s?i:a;return Pe.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${t.profile}, level:${c}]`),Pa(new jt(t.profile,c))}function Xl(r,e){for(let n=Ta.length-1;n>=0;--n){let s=Ta[n];if(s.max_macroblock_frame_size*256<=r&&s.max_macroblocks_per_second<=e*s.max_macroblock_frame_size)return Pe.debug(`supportedLevel() | result [max_frame_pixel_count:${r}, max_fps:${e}, level:${s.level}]`),s.level}Pe.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${r}, max_fps:${e}]`)}function Ra(r,e){return+(e[0]===r)<<7|+(e[1]===r)<<6|+(e[2]===r)<<5|+(e[3]===r)<<4|+(e[4]===r)<<3|+(e[5]===r)<<2|+(e[6]===r)<<1|+(e[7]===r)<<0}function Zl(r,e){return r===k.L1_b?e!==k.L1&&e!==k.L1_b:e===k.L1_b?r!==k.L1:r<e}function ep(r,e){return Zl(r,e)?r:e}function Ca(r={}){let e=r["level-asymmetry-allowed"];return e===!0||e===1||e==="1"}});var Oe=D(ie=>{"use strict";Object.defineProperty(ie,"__esModule",{value:!0});ie.validateAndNormalizeRtpCapabilities=ip;ie.validateAndNormalizeRtpParameters=Qs;ie.validateAndNormalizeSctpStreamParameters=op;ie.validateSctpCapabilities=ap;ie.getExtendedRtpCapabilities=cp;ie.getRecvRtpCapabilities=dp;ie.getSendRtpCapabilities=up;ie.getSendingRtpParameters=lp;ie.getSendingRemoteRtpParameters=pp;ie.reduceCodecs=hp;ie.generateProbatorRtpParameters=fp;ie.canSend=mp;ie.canReceive=gp;var xa=Da(),tp=ct(),rp="probator",np=1234,sp=127;function ip(r){if(typeof r!="object")throw new TypeError("caps is not an object");if(r.codecs&&!Array.isArray(r.codecs))throw new TypeError("caps.codecs is not an array");r.codecs||(r.codecs=[]);for(let e of r.codecs)_p(e);if(r.headerExtensions&&!Array.isArray(r.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");r.headerExtensions||(r.headerExtensions=[]);for(let e of r.headerExtensions)vp(e)}function Qs(r){if(typeof r!="object")throw new TypeError("params is not an object");if(r.mid&&typeof r.mid!="string")throw new TypeError("params.mid is not a string");if(!Array.isArray(r.codecs))throw new TypeError("missing params.codecs");for(let e of r.codecs)wp(e);if(r.headerExtensions&&!Array.isArray(r.headerExtensions))throw new TypeError("params.headerExtensions is not an array");r.headerExtensions||(r.headerExtensions=[]);for(let e of r.headerExtensions)yp(e);if(r.encodings&&!Array.isArray(r.encodings))throw new TypeError("params.encodings is not an array");r.encodings||(r.encodings=[]);for(let e of r.encodings)bp(e);if(r.rtcp&&typeof r.rtcp!="object")throw new TypeError("params.rtcp is not an object");r.rtcp||(r.rtcp={}),Sp(r.rtcp)}function op(r){if(typeof r!="object")throw new TypeError("params is not an object");if(typeof r.streamId!="number")throw new TypeError("missing params.streamId");let e=!1;if(typeof r.ordered=="boolean"?e=!0:r.ordered=!0,r.maxPacketLifeTime&&typeof r.maxPacketLifeTime!="number")throw new TypeError("invalid params.maxPacketLifeTime");if(r.maxRetransmits&&typeof r.maxRetransmits!="number")throw new TypeError("invalid params.maxRetransmits");if(r.maxPacketLifeTime&&r.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(e&&r.ordered&&(r.maxPacketLifeTime||r.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");if(!e&&(r.maxPacketLifeTime||r.maxRetransmits)&&(r.ordered=!1),r.label&&typeof r.label!="string")throw new TypeError("invalid params.label");if(r.protocol&&typeof r.protocol!="string")throw new TypeError("invalid params.protocol")}function ap(r){if(typeof r!="object")throw new TypeError("caps is not an object");if(!r.numStreams||typeof r.numStreams!="object")throw new TypeError("missing caps.numStreams");kp(r.numStreams)}function cp(r,e,t){let n={codecs:[],headerExtensions:[]};if(t)for(let s of r.codecs??[]){if(qt(s))continue;let i=(e.codecs??[]).find(a=>Ys(a,s,{strict:!0,modify:!0}));if(!i)continue;let o={kind:s.kind,mimeType:s.mimeType,clockRate:s.clockRate,channels:s.channels,localPayloadType:s.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:i.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:s.parameters??{},remoteParameters:i.parameters??{},rtcpFeedback:Ia(s,i)};n.codecs.push(o)}else for(let s of e.codecs??[]){if(qt(s))continue;let i=(r.codecs??[]).find(a=>Ys(a,s,{strict:!0,modify:!0}));if(!i)continue;let o={kind:i.kind,mimeType:i.mimeType,clockRate:i.clockRate,channels:i.channels,localPayloadType:i.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:s.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:i.parameters??{},remoteParameters:s.parameters??{},rtcpFeedback:Ia(i,s)};n.codecs.push(o)}for(let s of n.codecs){let i=r.codecs.find(a=>qt(a)&&a.parameters?.apt===s.localPayloadType),o=e.codecs.find(a=>qt(a)&&a.parameters?.apt===s.remotePayloadType);i&&o&&(s.localRtxPayloadType=i.preferredPayloadType,s.remoteRtxPayloadType=o.preferredPayloadType)}for(let s of e.headerExtensions){let i=r.headerExtensions.find(a=>Tp(a,s));if(!i)continue;let o={kind:s.kind,uri:s.uri,sendId:i.preferredId,recvId:s.preferredId,encrypt:i.preferredEncrypt??!1,direction:"sendrecv"};switch(s.direction){case"sendrecv":{o.direction="sendrecv";break}case"recvonly":{o.direction="sendonly";break}case"sendonly":{o.direction="recvonly";break}case"inactive":{o.direction="inactive";break}}n.headerExtensions.push(o)}return n}function dp(r){return La({direction:"recvonly",extendedRtpCapabilities:r})}function up(r){return La({direction:"sendonly",extendedRtpCapabilities:r})}function lp(r,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let n of e.codecs){if(n.kind!==r)continue;let s={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(t.codecs.push(s),n.localRtxPayloadType){let i={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let n of e.headerExtensions){if(n.kind&&n.kind!==r||n.direction!=="sendrecv"&&n.direction!=="sendonly")continue;let s={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};t.headerExtensions.push(s)}return t}function pp(r,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let n of e.codecs){if(n.kind!==r)continue;let s={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.remoteParameters,rtcpFeedback:n.rtcpFeedback};if(t.codecs.push(s),n.localRtxPayloadType){let i={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let n of e.headerExtensions){if(n.kind&&n.kind!==r||n.direction!=="sendrecv"&&n.direction!=="sendonly")continue;let s={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};t.headerExtensions.push(s)}if(t.headerExtensions.some(n=>n.uri==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"))for(let n of t.codecs)n.rtcpFeedback=(n.rtcpFeedback??[]).filter(s=>s.type!=="goog-remb");else if(t.headerExtensions.some(n=>n.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"))for(let n of t.codecs)n.rtcpFeedback=(n.rtcpFeedback??[]).filter(s=>s.type!=="transport-cc");else for(let n of t.codecs)n.rtcpFeedback=(n.rtcpFeedback??[]).filter(s=>s.type!=="transport-cc"&&s.type!=="goog-remb");return t}function hp(r,e){let t=[];if(!e)t.push(r[0]),qt(r[1])&&t.push(r[1]);else{for(let n=0;n<r.length;++n)if(Ys(r[n],e,{strict:!0})){t.push(r[n]),qt(r[n+1])&&t.push(r[n+1]);break}if(t.length===0)throw new TypeError("no matching codec found")}return t}function fp(r){r=tp.clone(r),Qs(r);let e={mid:rp,codecs:[],headerExtensions:[],encodings:[{ssrc:np}],rtcp:{cname:"probator"}};return e.codecs.push(r.codecs[0]),e.codecs[0].payloadType=sp,e.headerExtensions=r.headerExtensions,e}function mp(r,e){return(e.codecs??[]).some(t=>t.kind===r)}function gp(r,e){if(Qs(r),r.codecs.length===0)return!1;let t=r.codecs[0];return(e.codecs??[]).some(n=>n.preferredPayloadType===t.payloadType)}function _p(r){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof r!="object")throw new TypeError("codec is not an object");if(!r.mimeType||typeof r.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(r.kind=t[1].toLowerCase(),typeof r.preferredPayloadType!="number")throw new TypeError("missing codec.preferredPayloadType");if(typeof r.clockRate!="number")throw new TypeError("missing codec.clockRate");r.kind==="audio"?typeof r.channels!="number"&&(r.channels=1):delete r.channels,(!r.parameters||typeof r.parameters!="object")&&(r.parameters={});for(let n of Object.keys(r.parameters)){let s=r.parameters[n];if(s===void 0&&(r.parameters[n]="",s=""),typeof s!="string"&&typeof s!="number")throw new TypeError(`invalid codec parameter [key:${n}s, value:${s}]`);if(n==="apt"&&typeof s!="number")throw new TypeError("invalid codec apt parameter")}(!r.rtcpFeedback||!Array.isArray(r.rtcpFeedback))&&(r.rtcpFeedback=[]);for(let n of r.rtcpFeedback)Aa(n)}function Aa(r){if(typeof r!="object")throw new TypeError("fb is not an object");if(!r.type||typeof r.type!="string")throw new TypeError("missing fb.type");(!r.parameter||typeof r.parameter!="string")&&(r.parameter="")}function vp(r){if(typeof r!="object")throw new TypeError("ext is not an object");if(r.kind!=="audio"&&r.kind!=="video")throw new TypeError("invalid ext.kind");if(!r.uri||typeof r.uri!="string")throw new TypeError("missing ext.uri");if(typeof r.preferredId!="number")throw new TypeError("missing ext.preferredId");if(r.preferredEncrypt&&typeof r.preferredEncrypt!="boolean")throw new TypeError("invalid ext.preferredEncrypt");if(r.preferredEncrypt||(r.preferredEncrypt=!1),r.direction&&typeof r.direction!="string")throw new TypeError("invalid ext.direction");r.direction||(r.direction="sendrecv")}function wp(r){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof r!="object")throw new TypeError("codec is not an object");if(!r.mimeType||typeof r.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(typeof r.payloadType!="number")throw new TypeError("missing codec.payloadType");if(typeof r.clockRate!="number")throw new TypeError("missing codec.clockRate");t[1].toLowerCase()==="audio"?typeof r.channels!="number"&&(r.channels=1):delete r.channels,(!r.parameters||typeof r.parameters!="object")&&(r.parameters={});for(let s of Object.keys(r.parameters)){let i=r.parameters[s];if(i===void 0&&(r.parameters[s]="",i=""),typeof i!="string"&&typeof i!="number")throw new TypeError(`invalid codec parameter [key:${s}s, value:${i}]`);if(s==="apt"&&typeof i!="number")throw new TypeError("invalid codec apt parameter")}(!r.rtcpFeedback||!Array.isArray(r.rtcpFeedback))&&(r.rtcpFeedback=[]);for(let s of r.rtcpFeedback)Aa(s)}function yp(r){if(typeof r!="object")throw new TypeError("ext is not an object");if(!r.uri||typeof r.uri!="string")throw new TypeError("missing ext.uri");if(typeof r.id!="number")throw new TypeError("missing ext.id");if(r.encrypt&&typeof r.encrypt!="boolean")throw new TypeError("invalid ext.encrypt");r.encrypt||(r.encrypt=!1),(!r.parameters||typeof r.parameters!="object")&&(r.parameters={});for(let e of Object.keys(r.parameters)){let t=r.parameters[e];if(t===void 0&&(r.parameters[e]="",t=""),typeof t!="string"&&typeof t!="number")throw new TypeError("invalid header extension parameter")}}function bp(r){if(typeof r!="object")throw new TypeError("encoding is not an object");if(r.ssrc&&typeof r.ssrc!="number")throw new TypeError("invalid encoding.ssrc");if(r.rid&&typeof r.rid!="string")throw new TypeError("invalid encoding.rid");if(r.rtx&&typeof r.rtx!="object")throw new TypeError("invalid encoding.rtx");if(r.rtx&&typeof r.rtx.ssrc!="number")throw new TypeError("missing encoding.rtx.ssrc");if((!r.dtx||typeof r.dtx!="boolean")&&(r.dtx=!1),r.scalabilityMode&&typeof r.scalabilityMode!="string")throw new TypeError("invalid encoding.scalabilityMode")}function Sp(r){if(typeof r!="object")throw new TypeError("rtcp is not an object");if(r.cname&&typeof r.cname!="string")throw new TypeError("invalid rtcp.cname");(!r.reducedSize||typeof r.reducedSize!="boolean")&&(r.reducedSize=!0)}function kp(r){if(typeof r!="object")throw new TypeError("numStreams is not an object");if(typeof r.OS!="number")throw new TypeError("missing numStreams.OS");if(typeof r.MIS!="number")throw new TypeError("missing numStreams.MIS")}function La({direction:r,extendedRtpCapabilities:e}){let t={codecs:[],headerExtensions:[]};for(let n of e.codecs){let s={kind:n.kind,mimeType:n.mimeType,preferredPayloadType:n.remotePayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(t.codecs.push(s),!n.remoteRtxPayloadType)continue;let i={kind:n.kind,mimeType:`${n.kind}/rtx`,preferredPayloadType:n.remoteRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.remotePayloadType},rtcpFeedback:[]};t.codecs.push(i)}for(let n of e.headerExtensions){if(n.direction!=="sendrecv"&&n.direction!==r)continue;let s={kind:n.kind,uri:n.uri,preferredId:n.recvId,preferredEncrypt:n.encrypt??!1,direction:n.direction};t.headerExtensions.push(s)}return t}function qt(r){return r?/.+\/rtx$/i.test(r.mimeType):!1}function Ys(r,e,{strict:t=!1,modify:n=!1}={}){let s=r.mimeType.toLowerCase(),i=e.mimeType.toLowerCase();if(s!==i||r.clockRate!==e.clockRate||r.channels!==e.channels)return!1;switch(s){case"video/h264":{if(t){let o=r.parameters["packetization-mode"]??0,a=e.parameters["packetization-mode"]??0;if(o!==a||!xa.isSameProfile(r.parameters,e.parameters))return!1;let c;try{c=xa.generateProfileLevelIdStringForAnswer(r.parameters,e.parameters)}catch{return!1}n&&(c?(r.parameters["profile-level-id"]=c,e.parameters["profile-level-id"]=c):(delete r.parameters["profile-level-id"],delete e.parameters["profile-level-id"]))}break}case"video/vp9":{if(t){let o=r.parameters["profile-id"]??0,a=e.parameters["profile-id"]??0;if(o!==a)return!1}break}}return!0}function Tp(r,e){return!(r.kind&&e.kind&&r.kind!==e.kind||r.uri!==e.uri)}function Ia(r,e){let t=[];for(let n of r.rtcpFeedback??[]){let s=(e.rtcpFeedback??[]).find(i=>i.type===n.type&&(i.parameter===n.parameter||!i.parameter&&!n.parameter));s&&t.push(s)}return t}});var Ma=D(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.Logger=void 0;var $t=xr(),Bt="awaitqueue",Js=class{_debug;_warn;_error;constructor(e){e?(this._debug=$t(`${Bt}:${e}`),this._warn=$t(`${Bt}:WARN:${e}`),this._error=$t(`${Bt}:ERROR:${e}`)):(this._debug=$t(Bt),this._warn=$t(`${Bt}:WARN`),this._error=$t(`${Bt}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};Rn.Logger=Js});var ei=D(Ht=>{"use strict";Object.defineProperty(Ht,"__esModule",{value:!0});Ht.AwaitQueueRemovedTaskError=Ht.AwaitQueueStoppedError=void 0;var Xs=class r extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};Ht.AwaitQueueStoppedError=Xs;var Zs=class r extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};Ht.AwaitQueueRemovedTaskError=Zs});var Oa=D(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.AwaitQueue=void 0;var Rp=Ma(),ti=ei(),$e=new Rp.Logger("AwaitQueue"),ri=class{pendingTasks=new Map;nextTaskId=0;constructor(){$e.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,n){if(t=t??e.name,$e.debug(`push() [name:${t}, options:%o]`,n),typeof e!="function")throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch{}return new Promise((s,i)=>{if(t&&n?.removeOngoingTasksWithSameName)for(let a of this.pendingTasks.values())a.name===t&&a.reject(new ti.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});let o={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),$e.debug(`resolving task [name:${o.name}]`),s(a);let[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:(a,{canExecuteNextTask:c})=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),$e.debug(`rejecting task [name:${o.name}]: %s`,String(a)),i(a),c)){let[u]=this.pendingTasks.values();u&&!u.executedAt&&this.execute(u)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){$e.debug("stop()");for(let e of this.pendingTasks.values())$e.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new ti.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){$e.debug(`remove() [taskIdx:${e}]`);let t=Array.from(this.pendingTasks.values())[e];if(!t){$e.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}t.reject(new ti.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0})}dump(){let e=Date.now(),t=0;return Array.from(this.pendingTasks.values()).map(n=>({idx:t++,task:n.task,name:n.name,enqueuedTime:n.executedAt?n.executedAt-n.enqueuedAt:e-n.enqueuedAt,executionTime:n.executedAt?e-n.executedAt:0}))}async execute(e){if($e.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{let t=await e.task();e.resolve(t)}catch(t){e.reject(t,{canExecuteNextTask:!0})}}};Cn.AwaitQueue=ri});var Na=D(Je=>{"use strict";Object.defineProperty(Je,"__esModule",{value:!0});Je.AwaitQueueRemovedTaskError=Je.AwaitQueueStoppedError=Je.AwaitQueue=void 0;var Cp=Oa();Object.defineProperty(Je,"AwaitQueue",{enumerable:!0,get:function(){return Cp.AwaitQueue}});var Ua=ei();Object.defineProperty(Je,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return Ua.AwaitQueueStoppedError}});Object.defineProperty(Je,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return Ua.AwaitQueueRemovedTaskError}})});var Wa=D(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.Producer=void 0;var Ep=se(),Fa=pe(),Vt=we(),Ue=new Ep.Logger("Producer"),ni=class extends Fa.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new Fa.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:n,track:s,rtpParameters:i,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:u}){super(),Ue.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=n,this._track=s,this._kind=s.kind,this._rtpParameters=i,this._paused=a?!s.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=o,this._disableTrackOnPause=a,this._zeroRtpOnPause=c,this._appData=u??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Ue.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Ue.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Vt.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(Ue.debug("pause()"),this._closed){Ue.error("pause() | Producer closed");return}this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@pause",e,t)}).catch(()=>{}),this._observer.safeEmit("pause")}resume(){if(Ue.debug("resume()"),this._closed){Ue.error("resume() | Producer closed");return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@resume",e,t)}).catch(()=>{}),this._observer.safeEmit("resume")}async replaceTrack({track:e}){if(Ue.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch{}throw new Vt.InvalidStateError("closed")}else if(e?.readyState==="ended")throw new Vt.InvalidStateError("track ended");if(e===this._track){Ue.debug("replaceTrack() | same track, ignored");return}await new Promise((t,n)=>{this.safeEmit("@replacetrack",e,t,n)}),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()}async setMaxSpatialLayer(e){if(this._closed)throw new Vt.InvalidStateError("closed");if(this._kind!=="video")throw new Vt.UnsupportedError("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise((t,n)=>{this.safeEmit("@setmaxspatiallayer",e,t,n)}).catch(()=>{}),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new Vt.InvalidStateError("closed");if(typeof e!="object")throw new TypeError("invalid params");await new Promise((t,n)=>{this.safeEmit("@setrtpencodingparameters",e,t,n)})}onTrackEnded(){Ue.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch{}}};En.Producer=ni});var qa=D(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.Consumer=void 0;var Pp=se(),ja=pe(),Dp=we(),Ne=new Pp.Logger("Consumer"),si=class extends ja.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new ja.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:n,rtpReceiver:s,track:i,rtpParameters:o,appData:a}){super(),Ne.debug("constructor()"),this._id=e,this._localId=t,this._producerId=n,this._rtpReceiver=s,this._track=i,this._rtpParameters=o,this._paused=!i.enabled,this._appData=a??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Ne.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Ne.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Dp.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(Ne.debug("pause()"),this._closed){Ne.error("pause() | Consumer closed");return}if(this._paused){Ne.debug("pause() | Consumer is already paused");return}this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause")}resume(){if(Ne.debug("resume()"),this._closed){Ne.error("resume() | Consumer closed");return}if(!this._paused){Ne.debug("resume() | Consumer is already resumed");return}this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")}onTrackEnded(){Ne.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch{}}};Pn.Consumer=si});var Ba=D(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.DataProducer=void 0;var xp=se(),$a=pe(),Ip=we(),Be=new xp.Logger("DataProducer"),ii=class extends $a.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new $a.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:n,appData:s}){super(),Be.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=n,this._appData=s??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Be.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Be.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(Be.debug("send()"),this._closed)throw new Ip.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(Be.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?Be.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):Be.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(Be.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||Be.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}};Dn.DataProducer=ii});var Va=D(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.DataConsumer=void 0;var Ap=se(),Ha=pe(),ut=new Ap.Logger("DataConsumer"),oi=class extends Ha.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Ha.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:n,sctpStreamParameters:s,appData:i}){super(),ut.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=n,this._sctpStreamParameters=s,this._appData=i??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(ut.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(ut.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(ut.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?ut.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):ut.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(ut.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",e=>{this._closed||this.safeEmit("message",e.data)})}};xn.DataConsumer=oi});var Ga=D(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.Transport=void 0;var Lp=Na(),Mp=se(),za=pe(),Y=we(),ai=ct(),Ar=Oe(),Op=Wa(),Up=qa(),Np=Ba(),Fp=Va(),G=new Mp.Logger("Transport"),ci=class{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise((t,n)=>{this.resolve=t,this.reject=n})}},di=class extends za.EnhancedEventEmitter{_id;_closed=!1;_direction;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind;_maxSctpMessageSize;_handler;_iceGatheringState="new";_connectionState="new";_appData;_producers=new Map;_consumers=new Map;_dataProducers=new Map;_dataConsumers=new Map;_probatorConsumerCreated=!1;_awaitQueue=new Lp.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new za.EnhancedEventEmitter;constructor({direction:e,id:t,iceParameters:n,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:u,appData:d,handlerFactory:l,getSendExtendedRtpCapabilities:p,recvRtpCapabilities:f,canProduceByKind:h}){super(),G.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=p,this._recvRtpCapabilities=f,this._canProduceByKind=h,this._maxSctpMessageSize=o?.maxMessageSize;let m=ai.clone(u)??{};delete m.iceServers,delete m.iceTransportPolicy,delete m.bundlePolicy,delete m.rtcpMuxPolicy,this._handler=l.factory({direction:e,iceParameters:n,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:m,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities}),this._appData=d??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){G.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(let e of this._producers.values())e.transportClosed();this._producers.clear();for(let e of this._consumers.values())e.transportClosed();this._consumers.clear();for(let e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(let e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close"),super.close(),this._observer.close()}}async getStats(){if(this._closed)throw new Y.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(G.debug("restartIce()"),this._closed)throw new Y.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push(async()=>await this._handler.restartIce(e),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(G.debug("updateIceServers()"),this._closed)throw new Y.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push(async()=>this._handler.updateIceServers(e),"transport.updateIceServers()")}async produce({track:e,streamId:t,encodings:n,codecOptions:s,headerExtensionOptions:i,codec:o,stopTracks:a=!0,disableTrackOnPause:c=!0,zeroRtpOnPause:u=!1,onRtpSender:d,appData:l={}}={}){if(G.debug("produce() [track:%o]",e),this._closed)throw new Y.InvalidStateError("closed");if(e){if(this._direction!=="send")throw new Y.UnsupportedError("not a sending Transport");if(this._canProduceByKind[e.kind]){if(e.readyState==="ended")throw new Y.InvalidStateError("track ended");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(l&&typeof l!="object")throw new TypeError("if given, appData must be an object")}else throw new Y.UnsupportedError(`cannot produce ${e.kind}`)}else throw new TypeError("missing track");return this._awaitQueue.push(async()=>{let p;if(n&&!Array.isArray(n))throw TypeError("encodings must be an array");n?.length===0?p=void 0:n&&(p=n.map(g=>{let _={active:!0};return g.active===!1&&(_.active=!1),typeof g.dtx=="boolean"&&(_.dtx=g.dtx),typeof g.scalabilityMode=="string"&&(_.scalabilityMode=g.scalabilityMode),typeof g.scaleResolutionDownBy=="number"&&(_.scaleResolutionDownBy=g.scaleResolutionDownBy),typeof g.maxBitrate=="number"&&(_.maxBitrate=g.maxBitrate),typeof g.maxFramerate=="number"&&(_.maxFramerate=g.maxFramerate),typeof g.adaptivePtime=="boolean"&&(_.adaptivePtime=g.adaptivePtime),typeof g.priority=="string"&&(_.priority=g.priority),typeof g.networkPriority=="string"&&(_.networkPriority=g.networkPriority),_}));let{localId:f,rtpParameters:h,rtpSender:m}=await this._handler.send({track:e,streamId:t,encodings:p,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:d});try{Ar.validateAndNormalizeRtpParameters(h);let{id:g}=await new Promise((v,y)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:h,appData:l},v,y)}),_=new Op.Producer({id:g,localId:f,rtpSender:m,track:e,rtpParameters:h,stopTracks:a,disableTrackOnPause:c,zeroRtpOnPause:u,appData:l});return this._producers.set(_.id,_),this.handleProducer(_),this._observer.safeEmit("newproducer",_),_}catch(g){throw this._handler.stopSending(f).catch(()=>{}),g}},"transport.produce()").catch(p=>{if(a)try{e.stop()}catch{}throw p})}async consume({id:e,producerId:t,kind:n,rtpParameters:s,streamId:i,onRtpReceiver:o,appData:a={}}){if(G.debug("consume()"),this._closed)throw new Y.InvalidStateError("closed");if(this._direction!=="recv")throw new Y.UnsupportedError("not a receiving Transport");if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing producerId");if(n!=="audio"&&n!=="video")throw new TypeError(`invalid kind '${n}'`);if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object");let c=ai.clone(s);if(!Ar.canReceive(c,this._recvRtpCapabilities))throw new Y.UnsupportedError("cannot consume this Producer");let d=new ci({id:e,producerId:t,kind:n,rtpParameters:c,streamId:i,onRtpReceiver:o,appData:a});return this._pendingConsumerTasks.push(d),queueMicrotask(()=>{this._closed||this._consumerCreationInProgress===!1&&this.createPendingConsumers()}),d.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:n,label:s="",protocol:i="",appData:o={}}={}){if(G.debug("produceData()"),this._closed)throw new Y.InvalidStateError("closed");if(this._direction!=="send")throw new Y.UnsupportedError("not a sending Transport");if(this._maxSctpMessageSize){if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("producedata")===0)throw new TypeError('no "producedata" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new Y.UnsupportedError("SCTP not enabled by remote Transport");return(t||n)&&(e=!1),this._awaitQueue.push(async()=>{let{dataChannel:a,sctpStreamParameters:c}=await this._handler.sendDataChannel({sctpStreamParameters:{ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:s,protocol:i}});Ar.validateAndNormalizeSctpStreamParameters(c);let{id:u}=await new Promise((l,p)=>{this.safeEmit("producedata",{sctpStreamParameters:c,label:s,protocol:i,appData:o},l,p)}),d=new Np.DataProducer({id:u,dataChannel:a,sctpStreamParameters:c,appData:o});return this._dataProducers.set(d.id,d),this.handleDataProducer(d),this._observer.safeEmit("newdataproducer",d),d},"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:n,label:s="",protocol:i="",appData:o={}}){if(G.debug("consumeData()"),this._closed)throw new Y.InvalidStateError("closed");if(this._direction!=="recv")throw new Y.UnsupportedError("not a receiving Transport");if(this._maxSctpMessageSize){if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing dataProducerId");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new Y.UnsupportedError("SCTP not enabled by remote Transport");let a=ai.clone(n);return Ar.validateAndNormalizeSctpStreamParameters(a),this._awaitQueue.push(async()=>{let{dataChannel:c}=await this._handler.receiveDataChannel({maxMessageSize:this._maxSctpMessageSize,sctpStreamParameters:a,label:s,protocol:i}),u=new Fp.DataConsumer({id:e,dataProducerId:t,dataChannel:c,sctpStreamParameters:a,appData:o});return this._dataConsumers.set(u.id,u),this.handleDataConsumer(u),this._observer.safeEmit("newdataconsumer",u),u},"transport.consumeData()")}getDataChannelMaxMessageSize(){return this._handler.getDataChannelMaxMessageSize()}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingConsumerTasks.length===0){G.debug("createPendingConsumers() | there is no Consumer to be created");return}let e=[...this._pendingConsumerTasks];this._pendingConsumerTasks=[];let t,n=[];for(let s of e){let{id:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:u}=s.consumerOptions;n.push({trackId:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:u})}try{let s=await this._handler.receive(n);for(let i=0;i<s.length;++i){let o=e[i],a=s[i],{id:c,producerId:u,kind:d,rtpParameters:l,appData:p}=o.consumerOptions,{localId:f,rtpReceiver:h,track:m}=a,g=new Up.Consumer({id:c,localId:f,producerId:u,rtpReceiver:h,track:m,rtpParameters:l,appData:p});this._consumers.set(g.id,g),this.handleConsumer(g),!this._probatorConsumerCreated&&!t&&d==="video"&&(t=g),this._observer.safeEmit("newconsumer",g),o.resolve(g)}}catch(s){for(let i of e)i.reject(s)}if(t)try{let s=Ar.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:s}]),G.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(s){G.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",s)}},"transport.createPendingConsumers()").then(()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()}).catch(()=>{})}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingPauseConsumers.size===0){G.debug("pausePendingConsumers() | there is no Consumer to be paused");return}let e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{let t=e.map(n=>n.localId);await this._handler.pauseReceiving(t)}catch(t){G.error("pausePendingConsumers() | failed to pause Consumers:",t)}},"transport.pausePendingConsumers()").then(()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()}).catch(()=>{})}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingResumeConsumers.size===0){G.debug("resumePendingConsumers() | there is no Consumer to be resumed");return}let e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{let t=e.map(n=>n.localId);await this._handler.resumeReceiving(t)}catch(t){G.error("resumePendingConsumers() | failed to resume Consumers:",t)}},"transport.resumePendingConsumers()").then(()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()}).catch(()=>{})}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingCloseConsumers.size===0){G.debug("closePendingConsumers() | there is no Consumer to be closed");return}let e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map(t=>t.localId))}catch(t){G.error("closePendingConsumers() | failed to close Consumers:",t)}},"transport.closePendingConsumers()").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){let e=this._handler;e.on("@connect",({dtlsParameters:t},n,s)=>{if(this._closed){s(new Y.InvalidStateError("closed"));return}this.safeEmit("connect",{dtlsParameters:t},n,s)}),e.on("@icegatheringstatechange",t=>{t!==this._iceGatheringState&&(G.debug("ICE gathering state changed to %s",t),this._iceGatheringState=t,this._closed||this.safeEmit("icegatheringstatechange",t))}),e.on("@icecandidateerror",t=>{G.warn(`ICE candidate error [url:${t.url}, localAddress:${t.address}, localPort:${t.port}]: ${t.errorCode} "${t.errorText}"`),this.safeEmit("icecandidateerror",t)}),e.on("@connectionstatechange",t=>{t!==this._connectionState&&(G.debug("connection state changed to %s",t),this._connectionState=t,this._closed||this.safeEmit("connectionstatechange",t))})}handleProducer(e){e.on("@close",()=>{this._producers.delete(e.id),!this._closed&&this._awaitQueue.push(async()=>await this._handler.stopSending(e.localId),"producer @close event").catch(t=>G.warn("producer.close() failed:%o",t))}),e.on("@pause",(t,n)=>{this._awaitQueue.push(async()=>await this._handler.pauseSending(e.localId),"producer @pause event").then(t).catch(n)}),e.on("@resume",(t,n)=>{this._awaitQueue.push(async()=>await this._handler.resumeSending(e.localId),"producer @resume event").then(t).catch(n)}),e.on("@replacetrack",(t,n,s)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(e.localId,t),"producer @replacetrack event").then(n).catch(s)}),e.on("@setmaxspatiallayer",(t,n,s)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(e.localId,t),"producer @setmaxspatiallayer event").then(n).catch(s)}),e.on("@setrtpencodingparameters",(t,n,s)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(e.localId,t),"producer @setrtpencodingparameters event").then(n).catch(s)}),e.on("@getstats",(t,n)=>{if(this._closed)return n(new Y.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(n)})}handleConsumer(e){e.on("@close",()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),!this._closed&&(this._pendingCloseConsumers.set(e.id,e),this._consumerCloseInProgress===!1&&this.closePendingConsumers())}),e.on("@pause",()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerPauseInProgress===!1&&this.pausePendingConsumers()})}),e.on("@resume",()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerResumeInProgress===!1&&this.resumePendingConsumers()})}),e.on("@getstats",(t,n)=>{if(this._closed)return n(new Y.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(n)})}handleDataProducer(e){e.on("@close",()=>{this._dataProducers.delete(e.id)})}handleDataConsumer(e){e.on("@close",()=>{this._dataConsumers.delete(e.id)})}};In.Transport=di});var An=D((Ig,Ya)=>{"use strict";var Ka=Ya.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(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.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(r){return r.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(r){return r.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(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.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"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %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(r){var e="candidate:%s %d %s %d %s %d typ %s";return e+=r.raddr!=null?" raddr %s rport %d":"%v%v",e+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(e+=" generation %d"),e+=r["network-id"]!=null?" network-id %d":"%v",e+=r["network-cost"]!=null?" network-cost %d":"%v",e}},{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(r){var e="ssrc:%d";return r.attribute!=null&&(e+=" %s",r.value!=null&&(e+=":%s")),e}},{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(r){return r.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(r){return r.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(r){return"imageattr:%s %s %s"+(r.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(r){return"simulcast:%s %s"+(r.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(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var e="mediaclk:";return e+=r.id!=null?"id=%s %s":"%v%s",e+=r.mediaClockValue!=null?"=%s":"",e+=r.rateNumerator!=null?" rate=%s":"",e+=r.rateDenominator!=null?"/%s":"",e}},{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"]}]};Object.keys(Ka).forEach(function(r){var e=Ka[r];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})})});var Xa=D(He=>{"use strict";var zt=function(r){return String(Number(r))===r?Number(r):r},Wp=function(r,e,t,n){if(n&&!t)e[n]=zt(r[1]);else for(var s=0;s<t.length;s+=1)r[s+1]!=null&&(e[t[s]]=zt(r[s+1]))},jp=function(r,e,t){var n=r.name&&r.names;r.push&&!e[r.push]?e[r.push]=[]:n&&!e[r.name]&&(e[r.name]={});var s=r.push?{}:n?e[r.name]:e;Wp(t.match(r.reg),s,r.names,r.name),r.push&&e[r.push].push(s)},Qa=An(),qp=RegExp.prototype.test.bind(/^([a-z])=(.*)/);He.parse=function(r){var e={},t=[],n=e;return r.split(/(\r\n|\r|\n)/).filter(qp).forEach(function(s){var i=s[0],o=s.slice(2);i==="m"&&(t.push({rtp:[],fmtp:[]}),n=t[t.length-1]);for(var a=0;a<(Qa[i]||[]).length;a+=1){var c=Qa[i][a];if(c.reg.test(o))return jp(c,n,o)}}),e.media=t,e};var Ja=function(r,e){var t=e.split(/=(.+)/,2);return t.length===2?r[t[0]]=zt(t[1]):t.length===1&&e.length>1&&(r[t[0]]=void 0),r};He.parseParams=function(r){return r.split(/;\s?/).reduce(Ja,{})};He.parseFmtpConfig=He.parseParams;He.parsePayloads=function(r){return r.toString().split(" ").map(Number)};He.parseRemoteCandidates=function(r){for(var e=[],t=r.split(" ").map(zt),n=0;n<t.length;n+=3)e.push({component:t[n],ip:t[n+1],port:t[n+2]});return e};He.parseImageAttributes=function(r){return r.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(Ja,{})})};He.parseSimulcastStreamList=function(r){return r.split(";").map(function(e){return e.split(",").map(function(t){var n,s=!1;return t[0]!=="~"?n=zt(t):(n=zt(t.substring(1,t.length)),s=!0),{scid:n,paused:s}})})}});var ec=D((Lg,Za)=>{"use strict";var ui=An(),$p=/%[sdv%]/g,Bp=function(r){var e=1,t=arguments,n=t.length;return r.replace($p,function(s){if(e>=n)return s;var i=t[e];switch(e+=1,s){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},Lr=function(r,e,t){var n=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,s=[r+"="+n];if(e.names)for(var i=0;i<e.names.length;i+=1){var o=e.names[i];e.name?s.push(t[e.name][o]):s.push(t[e.names[i]])}else s.push(t[e.name]);return Bp.apply(null,s)},Hp=["v","o","s","i","u","e","p","c","b","t","r","z","a"],Vp=["i","c","b","a"];Za.exports=function(r,e){e=e||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(i){i.payloads==null&&(i.payloads="")});var t=e.outerOrder||Hp,n=e.innerOrder||Vp,s=[];return t.forEach(function(i){ui[i].forEach(function(o){o.name in r&&r[o.name]!=null?s.push(Lr(i,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(a){s.push(Lr(i,o,a))})})}),r.media.forEach(function(i){s.push(Lr("m",ui.m[0],i)),n.forEach(function(o){ui[o].forEach(function(a){a.name in i&&i[a.name]!=null?s.push(Lr(o,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(c){s.push(Lr(o,a,c))})})})}),s.join(`\r
|
|
3
|
+
`+i),r.push(s+"m+"+yn.exports.humanize(this.diff)+"\x1B[0m")}else r[0]=Dl()+e+" "+r[0]}function Dl(){return J.inspectOpts.hideDate?"":new Date().toISOString()+" "}function Il(...r){return process.stderr.write(wn.formatWithOptions(J.inspectOpts,...r)+`
|
|
4
|
+
`)}function xl(r){r?process.env.DEBUG=r:delete process.env.DEBUG}function Al(){return process.env.DEBUG}function Ll(r){r.inspectOpts={};let e=Object.keys(J.inspectOpts);for(let t=0;t<e.length;t++)r.inspectOpts[e[t]]=J.inspectOpts[e[t]]}yn.exports=qs()(J);var{formatters:da}=yn.exports;da.o=function(r){return this.inspectOpts.colors=this.useColors,wn.inspect(r,this.inspectOpts).split(`
|
|
5
|
+
`).map(e=>e.trim()).join(" ")};da.O=function(r){return this.inspectOpts.colors=this.useColors,wn.inspect(r,this.inspectOpts)}});var xr=D((hg,Hs)=>{"use strict";typeof process>"u"||process.type==="renderer"||process.browser===!0||process.__nwjs?Hs.exports=ia():Hs.exports=ua()});var pa=D(la=>{"use strict";Object.defineProperty(la,"__esModule",{value:!0})});var ie=D(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.Logger=void 0;var Ot=xr(),Ut="media-client",Vs=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Ot.default)(`${Ut}:${e}`),this._warn=(0,Ot.default)(`${Ut}:WARN:${e}`),this._error=(0,Ot.default)(`${Ut}:ERROR:${e}`)):(this._debug=(0,Ot.default)(Ut),this._warn=(0,Ot.default)(`${Ut}:WARN`),this._error=(0,Ot.default)(`${Ut}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};bn.Logger=Vs});var ka=D((gg,zs)=>{"use strict";var Nt=typeof Reflect=="object"?Reflect:null,ha=Nt&&typeof Nt.apply=="function"?Nt.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},Sn;Nt&&typeof Nt.ownKeys=="function"?Sn=Nt.ownKeys:Object.getOwnPropertySymbols?Sn=function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:Sn=function(e){return Object.getOwnPropertyNames(e)};function Ml(r){console&&console.warn&&console.warn(r)}var ma=Number.isNaN||function(e){return e!==e};function j(){j.init.call(this)}zs.exports=j;zs.exports.once=Fl;j.EventEmitter=j;j.prototype._events=void 0;j.prototype._eventsCount=0;j.prototype._maxListeners=void 0;var fa=10;function kn(r){if(typeof r!="function")throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof r)}Object.defineProperty(j,"defaultMaxListeners",{enumerable:!0,get:function(){return fa},set:function(r){if(typeof r!="number"||r<0||ma(r))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+r+".");fa=r}});j.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};j.prototype.setMaxListeners=function(e){if(typeof e!="number"||e<0||ma(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this};function ga(r){return r._maxListeners===void 0?j.defaultMaxListeners:r._maxListeners}j.prototype.getMaxListeners=function(){return ga(this)};j.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var s=e==="error",i=this._events;if(i!==void 0)s=s&&i.error===void 0;else if(!s)return!1;if(s){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=i[e];if(c===void 0)return!1;if(typeof c=="function")ha(c,this,t);else for(var u=c.length,d=ba(c,u),n=0;n<u;++n)ha(d[n],this,t);return!0};function _a(r,e,t,n){var s,i,o;if(kn(t),i=r._events,i===void 0?(i=r._events=Object.create(null),r._eventsCount=0):(i.newListener!==void 0&&(r.emit("newListener",e,t.listener?t.listener:t),i=r._events),o=i[e]),o===void 0)o=i[e]=t,++r._eventsCount;else if(typeof o=="function"?o=i[e]=n?[t,o]:[o,t]:n?o.unshift(t):o.push(t),s=ga(r),s>0&&o.length>s&&!o.warned){o.warned=!0;var a=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(e)+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=r,a.type=e,a.count=o.length,Ml(a)}return r}j.prototype.addListener=function(e,t){return _a(this,e,t,!1)};j.prototype.on=j.prototype.addListener;j.prototype.prependListener=function(e,t){return _a(this,e,t,!0)};function Ol(){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 va(r,e,t){var n={fired:!1,wrapFn:void 0,target:r,type:e,listener:t},s=Ol.bind(n);return s.listener=t,n.wrapFn=s,s}j.prototype.once=function(e,t){return kn(t),this.on(e,va(this,e,t)),this};j.prototype.prependOnceListener=function(e,t){return kn(t),this.prependListener(e,va(this,e,t)),this};j.prototype.removeListener=function(e,t){var n,s,i,o,a;if(kn(t),s=this._events,s===void 0)return this;if(n=s[e],n===void 0)return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if(typeof n!="function"){for(i=-1,o=n.length-1;o>=0;o--)if(n[o]===t||n[o].listener===t){a=n[o].listener,i=o;break}if(i<0)return this;i===0?n.shift():Ul(n,i),n.length===1&&(s[e]=n[0]),s.removeListener!==void 0&&this.emit("removeListener",e,a||t)}return this};j.prototype.off=j.prototype.removeListener;j.prototype.removeAllListeners=function(e){var t,n,s;if(n=this._events,n===void 0)return this;if(n.removeListener===void 0)return arguments.length===0?(this._events=Object.create(null),this._eventsCount=0):n[e]!==void 0&&(--this._eventsCount===0?this._events=Object.create(null):delete n[e]),this;if(arguments.length===0){var i=Object.keys(n),o;for(s=0;s<i.length;++s)o=i[s],o!=="removeListener"&&this.removeAllListeners(o);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if(t=n[e],typeof t=="function")this.removeListener(e,t);else if(t!==void 0)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this};function wa(r,e,t){var n=r._events;if(n===void 0)return[];var s=n[e];return s===void 0?[]:typeof s=="function"?t?[s.listener||s]:[s]:t?Nl(s):ba(s,s.length)}j.prototype.listeners=function(e){return wa(this,e,!0)};j.prototype.rawListeners=function(e){return wa(this,e,!1)};j.listenerCount=function(r,e){return typeof r.listenerCount=="function"?r.listenerCount(e):ya.call(r,e)};j.prototype.listenerCount=ya;function ya(r){var e=this._events;if(e!==void 0){var t=e[r];if(typeof t=="function")return 1;if(t!==void 0)return t.length}return 0}j.prototype.eventNames=function(){return this._eventsCount>0?Sn(this._events):[]};function ba(r,e){for(var t=new Array(e),n=0;n<e;++n)t[n]=r[n];return t}function Ul(r,e){for(;e+1<r.length;e++)r[e]=r[e+1];r.pop()}function Nl(r){for(var e=new Array(r.length),t=0;t<e.length;++t)e[t]=r[t].listener||r[t];return e}function Fl(r,e){return new Promise(function(t,n){function s(o){r.removeListener(e,i),n(o)}function i(){typeof r.removeListener=="function"&&r.removeListener("error",s),t([].slice.call(arguments))}Sa(r,e,i,{once:!0}),e!=="error"&&Wl(r,s,{once:!0})})}function Wl(r,e,t){typeof r.on=="function"&&Sa(r,"error",e,t)}function Sa(r,e,t,n){if(typeof r.on=="function")n.once?r.once(e,t):r.on(e,t);else if(typeof r.addEventListener=="function")r.addEventListener(e,function s(i){n.once&&r.removeEventListener(e,s),t(i)});else throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof r)}});var he=D(Tn=>{"use strict";Object.defineProperty(Tn,"__esModule",{value:!0});Tn.EnhancedEventEmitter=void 0;var jl=ka(),ql=ie(),$l=new ql.Logger("EnhancedEventEmitter"),Gs=class extends jl.EventEmitter{constructor(){super(),this.setMaxListeners(1/0)}close(){super.removeAllListeners()}emit(e,...t){return super.emit(e,...t)}safeEmit(e,...t){try{return super.emit(e,...t)}catch(n){$l.error("safeEmit() | event listener threw an error [eventName:%s]:%o",e,n);try{super.emit("listenererror",e,n)}catch{}return!!super.listenerCount(e)}}on(e,t){return super.on(e,t),this}off(e,t){return super.off(e,t),this}addListener(e,t){return super.on(e,t),this}prependListener(e,t){return super.prependListener(e,t),this}once(e,t){return super.once(e,t),this}prependOnceListener(e,t){return super.prependOnceListener(e,t),this}removeListener(e,t){return super.off(e,t),this}removeAllListeners(e){return super.removeAllListeners(e),this}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}rawListeners(e){return super.rawListeners(e)}};Tn.EnhancedEventEmitter=Gs});var ye=D(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.InvalidStateError=Ft.UnsupportedError=void 0;var Ks=class r extends Error{constructor(e){super(e),this.name="UnsupportedError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,r):this.stack=new Error(e).stack}};Ft.UnsupportedError=Ks;var Ys=class r extends Error{constructor(e){super(e),this.name="InvalidStateError",Error.hasOwnProperty("captureStackTrace")?Error.captureStackTrace(this,r):this.stack=new Error(e).stack}};Ft.InvalidStateError=Ys});var dt=D(Ar=>{"use strict";Object.defineProperty(Ar,"__esModule",{value:!0});Ar.clone=Bl;Ar.generateRandomNumber=Hl;Ar.deepFreeze=Ta;function Bl(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}function Hl(){return Math.round(Math.random()*1e7)}function Ta(r){let e=Reflect.ownKeys(r);for(let t of e){let n=r[t];(n&&typeof n=="object"||typeof n=="function")&&Ta(n)}return Object.freeze(r)}});var Ra=D(Rn=>{"use strict";Object.defineProperty(Rn,"__esModule",{value:!0});Rn.Logger=void 0;var Wt=xr(),jt="h264-profile-level-id",Qs=class{_debug;_warn;_error;constructor(e){e?(this._debug=(0,Wt.default)(`${jt}:${e}`),this._warn=(0,Wt.default)(`${jt}:WARN:${e}`),this._error=(0,Wt.default)(`${jt}:ERROR:${e}`)):(this._debug=(0,Wt.default)(jt),this._warn=(0,Wt.default)(`${jt}:WARN`),this._error=(0,Wt.default)(`${jt}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};Rn.Logger=Qs});var xa=D(X=>{"use strict";Object.defineProperty(X,"__esModule",{value:!0});X.ProfileLevelId=X.Level=X.Profile=void 0;X.parseProfileLevelId=Da;X.profileLevelIdToString=Ia;X.profileToString=Kl;X.levelToString=Yl;X.parseSdpProfileLevelId=ut;X.isSameProfile=Ql;X.isSameProfileAndLevel=Jl;X.generateProfileLevelIdStringForAnswer=Xl;X.supportedLevel=Zl;var Vl=Ra(),De=new Vl.Logger,$;(function(r){r[r.ConstrainedBaseline=1]="ConstrainedBaseline",r[r.Baseline=2]="Baseline",r[r.Main=3]="Main",r[r.ConstrainedHigh=4]="ConstrainedHigh",r[r.High=5]="High",r[r.PredictiveHigh444=6]="PredictiveHigh444"})($||(X.Profile=$={}));var k;(function(r){r[r.L1_b=0]="L1_b",r[r.L1=10]="L1",r[r.L1_1=11]="L1_1",r[r.L1_2=12]="L1_2",r[r.L1_3=13]="L1_3",r[r.L2=20]="L2",r[r.L2_1=21]="L2_1",r[r.L2_2=22]="L2_2",r[r.L3=30]="L3",r[r.L3_1=31]="L3_1",r[r.L3_2=32]="L3_2",r[r.L4=40]="L4",r[r.L4_1=41]="L4_1",r[r.L4_2=42]="L4_2",r[r.L5=50]="L5",r[r.L5_1=51]="L5_1",r[r.L5_2=52]="L5_2"})(k||(X.Level=k={}));var qt=class{profile;level;constructor(e,t){this.profile=e,this.level=t}};X.ProfileLevelId=qt;var zl=new qt($.ConstrainedBaseline,k.L3_1),Ee=class{mask;masked_value;constructor(e){this.mask=~Ea("x",e),this.masked_value=Ea("1",e)}isMatch(e){return this.masked_value===(e&this.mask)}},Pe=class{profile_idc;profile_iop;profile;constructor(e,t,n){this.profile_idc=e,this.profile_iop=t,this.profile=n}},Gl=[new Pe(66,new Ee("x1xx0000"),$.ConstrainedBaseline),new Pe(77,new Ee("1xxx0000"),$.ConstrainedBaseline),new Pe(88,new Ee("11xx0000"),$.ConstrainedBaseline),new Pe(66,new Ee("x0xx0000"),$.Baseline),new Pe(88,new Ee("10xx0000"),$.Baseline),new Pe(77,new Ee("0x0x0000"),$.Main),new Pe(100,new Ee("00000000"),$.High),new Pe(100,new Ee("00001100"),$.ConstrainedHigh),new Pe(244,new Ee("00000000"),$.PredictiveHigh444)],Ca=[{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:k.L1},{max_macroblocks_per_second:1485,max_macroblock_frame_size:99,level:k.L1_b},{max_macroblocks_per_second:3e3,max_macroblock_frame_size:396,level:k.L1_1},{max_macroblocks_per_second:6e3,max_macroblock_frame_size:396,level:k.L1_2},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:k.L1_3},{max_macroblocks_per_second:11880,max_macroblock_frame_size:396,level:k.L2},{max_macroblocks_per_second:19800,max_macroblock_frame_size:792,level:k.L2_1},{max_macroblocks_per_second:20250,max_macroblock_frame_size:1620,level:k.L2_2},{max_macroblocks_per_second:40500,max_macroblock_frame_size:1620,level:k.L3},{max_macroblocks_per_second:108e3,max_macroblock_frame_size:3600,level:k.L3_1},{max_macroblocks_per_second:216e3,max_macroblock_frame_size:5120,level:k.L3_2},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:k.L4},{max_macroblocks_per_second:245760,max_macroblock_frame_size:8192,level:k.L4_1},{max_macroblocks_per_second:522240,max_macroblock_frame_size:8704,level:k.L4_2},{max_macroblocks_per_second:589824,max_macroblock_frame_size:22080,level:k.L5},{max_macroblocks_per_second:983040,max_macroblock_frame_size:36864,level:k.L5_1},{max_macroblocks_per_second:2073600,max_macroblock_frame_size:36864,level:k.L5_2}];function Da(r){if(typeof r!="string"||r.length!==6)return;let t=parseInt(r,16);if(t===0)return;let n=t&255,s=t>>8&255,i=t>>16&255,o;switch(n){case k.L1_1:{o=(s&16)!==0?k.L1_b:k.L1_1;break}case k.L1:case k.L1_2:case k.L1_3:case k.L2:case k.L2_1:case k.L2_2:case k.L3:case k.L3_1:case k.L3_2:case k.L4:case k.L4_1:case k.L4_2:case k.L5:case k.L5_1:case k.L5_2:{o=n;break}default:{De.warn(`parseProfileLevelId() | unrecognized level_idc [str:${r}, level_idc:${n}]`);return}}for(let a of Gl)if(i===a.profile_idc&&a.profile_iop.isMatch(s))return De.debug(`parseProfileLevelId() | result [str:${r}, profile:${a.profile}, level:${o}]`),new qt(a.profile,o);De.warn(`parseProfileLevelId() | unrecognized profile_idc/profile_iop combination [str:${r}, profile_idc:${i}, profile_iop:${s}]`)}function Ia(r){if(r.level==k.L1_b)switch(r.profile){case $.ConstrainedBaseline:return"42f00b";case $.Baseline:return"42100b";case $.Main:return"4d100b";default:{De.warn(`profileLevelIdToString() | Level 1_b not is allowed for profile ${r.profile}`);return}}let e;switch(r.profile){case $.ConstrainedBaseline:{e="42e0";break}case $.Baseline:{e="4200";break}case $.Main:{e="4d00";break}case $.ConstrainedHigh:{e="640c";break}case $.High:{e="6400";break}case $.PredictiveHigh444:{e="f400";break}default:{De.warn(`profileLevelIdToString() | unrecognized profile ${r.profile}`);return}}let t=r.level.toString(16);return t.length===1&&(t=`0${t}`),`${e}${t}`}function Kl(r){switch(r){case $.ConstrainedBaseline:return"ConstrainedBaseline";case $.Baseline:return"Baseline";case $.Main:return"Main";case $.ConstrainedHigh:return"ConstrainedHigh";case $.High:return"High";case $.PredictiveHigh444:return"PredictiveHigh444";default:{De.warn(`profileToString() | unrecognized profile ${r}`);return}}}function Yl(r){switch(r){case k.L1_b:return"1b";case k.L1:return"1";case k.L1_1:return"1.1";case k.L1_2:return"1.2";case k.L1_3:return"1.3";case k.L2:return"2";case k.L2_1:return"2.1";case k.L2_2:return"2.2";case k.L3:return"3";case k.L3_1:return"3.1";case k.L3_2:return"3.2";case k.L4:return"4";case k.L4_1:return"4.1";case k.L4_2:return"4.2";case k.L5:return"5";case k.L5_1:return"5.1";case k.L5_2:return"5.2";default:{De.warn(`levelToString() | unrecognized level ${r}`);return}}}function ut(r={}){let e=r["profile-level-id"];return e?Da(e):zl}function Ql(r={},e={}){let t=ut(r),n=ut(e);return!!(t&&n&&t.profile===n.profile)}function Jl(r={},e={}){let t=ut(r),n=ut(e);return!!(t&&n&&t.profile===n.profile&&t.level==n.level)}function Xl(r={},e={}){if(!r["profile-level-id"]&&!e["profile-level-id"]){De.warn("generateProfileLevelIdStringForAnswer() | profile-level-id missing in local and remote params");return}let t=ut(r),n=ut(e);if(!t)throw new TypeError("invalid local_profile_level_id");if(!n)throw new TypeError("invalid remote_profile_level_id");if(t.profile!==n.profile)throw new TypeError("H264 Profile mismatch");let s=Pa(r)&&Pa(e),i=t.level,o=n.level,a=tp(i,o),c=s?i:a;return De.debug(`generateProfileLevelIdStringForAnswer() | result [profile:${t.profile}, level:${c}]`),Ia(new qt(t.profile,c))}function Zl(r,e){for(let n=Ca.length-1;n>=0;--n){let s=Ca[n];if(s.max_macroblock_frame_size*256<=r&&s.max_macroblocks_per_second<=e*s.max_macroblock_frame_size)return De.debug(`supportedLevel() | result [max_frame_pixel_count:${r}, max_fps:${e}, level:${s.level}]`),s.level}De.warn(`supportedLevel() | no level supported [max_frame_pixel_count:${r}, max_fps:${e}]`)}function Ea(r,e){return+(e[0]===r)<<7|+(e[1]===r)<<6|+(e[2]===r)<<5|+(e[3]===r)<<4|+(e[4]===r)<<3|+(e[5]===r)<<2|+(e[6]===r)<<1|+(e[7]===r)<<0}function ep(r,e){return r===k.L1_b?e!==k.L1&&e!==k.L1_b:e===k.L1_b?r!==k.L1:r<e}function tp(r,e){return ep(r,e)?r:e}function Pa(r={}){let e=r["level-asymmetry-allowed"];return e===!0||e===1||e==="1"}});var Oe=D(oe=>{"use strict";Object.defineProperty(oe,"__esModule",{value:!0});oe.validateAndNormalizeRtpCapabilities=op;oe.validateAndNormalizeRtpParameters=Xs;oe.validateAndNormalizeSctpStreamParameters=ap;oe.validateSctpCapabilities=cp;oe.getExtendedRtpCapabilities=dp;oe.getRecvRtpCapabilities=up;oe.getSendRtpCapabilities=lp;oe.getSendingRtpParameters=pp;oe.getSendingRemoteRtpParameters=hp;oe.reduceCodecs=fp;oe.generateProbatorRtpParameters=mp;oe.canSend=gp;oe.canReceive=_p;var Aa=xa(),rp=dt(),np="probator",sp=1234,ip=127;function op(r){if(typeof r!="object")throw new TypeError("caps is not an object");if(r.codecs&&!Array.isArray(r.codecs))throw new TypeError("caps.codecs is not an array");r.codecs||(r.codecs=[]);for(let e of r.codecs)vp(e);if(r.headerExtensions&&!Array.isArray(r.headerExtensions))throw new TypeError("caps.headerExtensions is not an array");r.headerExtensions||(r.headerExtensions=[]);for(let e of r.headerExtensions)wp(e)}function Xs(r){if(typeof r!="object")throw new TypeError("params is not an object");if(r.mid&&typeof r.mid!="string")throw new TypeError("params.mid is not a string");if(!Array.isArray(r.codecs))throw new TypeError("missing params.codecs");for(let e of r.codecs)yp(e);if(r.headerExtensions&&!Array.isArray(r.headerExtensions))throw new TypeError("params.headerExtensions is not an array");r.headerExtensions||(r.headerExtensions=[]);for(let e of r.headerExtensions)bp(e);if(r.encodings&&!Array.isArray(r.encodings))throw new TypeError("params.encodings is not an array");r.encodings||(r.encodings=[]);for(let e of r.encodings)Sp(e);if(r.rtcp&&typeof r.rtcp!="object")throw new TypeError("params.rtcp is not an object");r.rtcp||(r.rtcp={}),kp(r.rtcp)}function ap(r){if(typeof r!="object")throw new TypeError("params is not an object");if(typeof r.streamId!="number")throw new TypeError("missing params.streamId");let e=!1;if(typeof r.ordered=="boolean"?e=!0:r.ordered=!0,r.maxPacketLifeTime&&typeof r.maxPacketLifeTime!="number")throw new TypeError("invalid params.maxPacketLifeTime");if(r.maxRetransmits&&typeof r.maxRetransmits!="number")throw new TypeError("invalid params.maxRetransmits");if(r.maxPacketLifeTime&&r.maxRetransmits)throw new TypeError("cannot provide both maxPacketLifeTime and maxRetransmits");if(e&&r.ordered&&(r.maxPacketLifeTime||r.maxRetransmits))throw new TypeError("cannot be ordered with maxPacketLifeTime or maxRetransmits");if(!e&&(r.maxPacketLifeTime||r.maxRetransmits)&&(r.ordered=!1),r.label&&typeof r.label!="string")throw new TypeError("invalid params.label");if(r.protocol&&typeof r.protocol!="string")throw new TypeError("invalid params.protocol")}function cp(r){if(typeof r!="object")throw new TypeError("caps is not an object");if(!r.numStreams||typeof r.numStreams!="object")throw new TypeError("missing caps.numStreams");Tp(r.numStreams)}function dp(r,e,t){let n={codecs:[],headerExtensions:[]};if(t)for(let s of r.codecs??[]){if($t(s))continue;let i=(e.codecs??[]).find(a=>Js(a,s,{strict:!0,modify:!0}));if(!i)continue;let o={kind:s.kind,mimeType:s.mimeType,clockRate:s.clockRate,channels:s.channels,localPayloadType:s.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:i.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:s.parameters??{},remoteParameters:i.parameters??{},rtcpFeedback:La(s,i)};n.codecs.push(o)}else for(let s of e.codecs??[]){if($t(s))continue;let i=(r.codecs??[]).find(a=>Js(a,s,{strict:!0,modify:!0}));if(!i)continue;let o={kind:i.kind,mimeType:i.mimeType,clockRate:i.clockRate,channels:i.channels,localPayloadType:i.preferredPayloadType,localRtxPayloadType:void 0,remotePayloadType:s.preferredPayloadType,remoteRtxPayloadType:void 0,localParameters:i.parameters??{},remoteParameters:s.parameters??{},rtcpFeedback:La(i,s)};n.codecs.push(o)}for(let s of n.codecs){let i=r.codecs.find(a=>$t(a)&&a.parameters?.apt===s.localPayloadType),o=e.codecs.find(a=>$t(a)&&a.parameters?.apt===s.remotePayloadType);i&&o&&(s.localRtxPayloadType=i.preferredPayloadType,s.remoteRtxPayloadType=o.preferredPayloadType)}for(let s of e.headerExtensions){let i=r.headerExtensions.find(a=>Rp(a,s));if(!i)continue;let o={kind:s.kind,uri:s.uri,sendId:i.preferredId,recvId:s.preferredId,encrypt:i.preferredEncrypt??!1,direction:"sendrecv"};switch(s.direction){case"sendrecv":{o.direction="sendrecv";break}case"recvonly":{o.direction="sendonly";break}case"sendonly":{o.direction="recvonly";break}case"inactive":{o.direction="inactive";break}}n.headerExtensions.push(o)}return n}function up(r){return Oa({direction:"recvonly",extendedRtpCapabilities:r})}function lp(r){return Oa({direction:"sendonly",extendedRtpCapabilities:r})}function pp(r,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let n of e.codecs){if(n.kind!==r)continue;let s={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(t.codecs.push(s),n.localRtxPayloadType){let i={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let n of e.headerExtensions){if(n.kind&&n.kind!==r||n.direction!=="sendrecv"&&n.direction!=="sendonly")continue;let s={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};t.headerExtensions.push(s)}return t}function hp(r,e){let t={mid:void 0,codecs:[],headerExtensions:[],encodings:[],rtcp:{}};for(let n of e.codecs){if(n.kind!==r)continue;let s={mimeType:n.mimeType,payloadType:n.localPayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.remoteParameters,rtcpFeedback:n.rtcpFeedback};if(t.codecs.push(s),n.localRtxPayloadType){let i={mimeType:`${n.kind}/rtx`,payloadType:n.localRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.localPayloadType},rtcpFeedback:[]};t.codecs.push(i)}}for(let n of e.headerExtensions){if(n.kind&&n.kind!==r||n.direction!=="sendrecv"&&n.direction!=="sendonly")continue;let s={uri:n.uri,id:n.sendId,encrypt:n.encrypt,parameters:{}};t.headerExtensions.push(s)}if(t.headerExtensions.some(n=>n.uri==="http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01"))for(let n of t.codecs)n.rtcpFeedback=(n.rtcpFeedback??[]).filter(s=>s.type!=="goog-remb");else if(t.headerExtensions.some(n=>n.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time"))for(let n of t.codecs)n.rtcpFeedback=(n.rtcpFeedback??[]).filter(s=>s.type!=="transport-cc");else for(let n of t.codecs)n.rtcpFeedback=(n.rtcpFeedback??[]).filter(s=>s.type!=="transport-cc"&&s.type!=="goog-remb");return t}function fp(r,e){let t=[];if(!e)t.push(r[0]),$t(r[1])&&t.push(r[1]);else{for(let n=0;n<r.length;++n)if(Js(r[n],e,{strict:!0})){t.push(r[n]),$t(r[n+1])&&t.push(r[n+1]);break}if(t.length===0)throw new TypeError("no matching codec found")}return t}function mp(r){r=rp.clone(r),Xs(r);let e={mid:np,codecs:[],headerExtensions:[],encodings:[{ssrc:sp}],rtcp:{cname:"probator"}};return e.codecs.push(r.codecs[0]),e.codecs[0].payloadType=ip,e.headerExtensions=r.headerExtensions,e}function gp(r,e){return(e.codecs??[]).some(t=>t.kind===r)}function _p(r,e){if(Xs(r),r.codecs.length===0)return!1;let t=r.codecs[0];return(e.codecs??[]).some(n=>n.preferredPayloadType===t.payloadType)}function vp(r){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof r!="object")throw new TypeError("codec is not an object");if(!r.mimeType||typeof r.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(r.kind=t[1].toLowerCase(),typeof r.preferredPayloadType!="number")throw new TypeError("missing codec.preferredPayloadType");if(typeof r.clockRate!="number")throw new TypeError("missing codec.clockRate");r.kind==="audio"?typeof r.channels!="number"&&(r.channels=1):delete r.channels,(!r.parameters||typeof r.parameters!="object")&&(r.parameters={});for(let n of Object.keys(r.parameters)){let s=r.parameters[n];if(s===void 0&&(r.parameters[n]="",s=""),typeof s!="string"&&typeof s!="number")throw new TypeError(`invalid codec parameter [key:${n}s, value:${s}]`);if(n==="apt"&&typeof s!="number")throw new TypeError("invalid codec apt parameter")}(!r.rtcpFeedback||!Array.isArray(r.rtcpFeedback))&&(r.rtcpFeedback=[]);for(let n of r.rtcpFeedback)Ma(n)}function Ma(r){if(typeof r!="object")throw new TypeError("fb is not an object");if(!r.type||typeof r.type!="string")throw new TypeError("missing fb.type");(!r.parameter||typeof r.parameter!="string")&&(r.parameter="")}function wp(r){if(typeof r!="object")throw new TypeError("ext is not an object");if(r.kind!=="audio"&&r.kind!=="video")throw new TypeError("invalid ext.kind");if(!r.uri||typeof r.uri!="string")throw new TypeError("missing ext.uri");if(typeof r.preferredId!="number")throw new TypeError("missing ext.preferredId");if(r.preferredEncrypt&&typeof r.preferredEncrypt!="boolean")throw new TypeError("invalid ext.preferredEncrypt");if(r.preferredEncrypt||(r.preferredEncrypt=!1),r.direction&&typeof r.direction!="string")throw new TypeError("invalid ext.direction");r.direction||(r.direction="sendrecv")}function yp(r){let e=new RegExp("^(audio|video)/(.+)","i");if(typeof r!="object")throw new TypeError("codec is not an object");if(!r.mimeType||typeof r.mimeType!="string")throw new TypeError("missing codec.mimeType");let t=e.exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");if(typeof r.payloadType!="number")throw new TypeError("missing codec.payloadType");if(typeof r.clockRate!="number")throw new TypeError("missing codec.clockRate");t[1].toLowerCase()==="audio"?typeof r.channels!="number"&&(r.channels=1):delete r.channels,(!r.parameters||typeof r.parameters!="object")&&(r.parameters={});for(let s of Object.keys(r.parameters)){let i=r.parameters[s];if(i===void 0&&(r.parameters[s]="",i=""),typeof i!="string"&&typeof i!="number")throw new TypeError(`invalid codec parameter [key:${s}s, value:${i}]`);if(s==="apt"&&typeof i!="number")throw new TypeError("invalid codec apt parameter")}(!r.rtcpFeedback||!Array.isArray(r.rtcpFeedback))&&(r.rtcpFeedback=[]);for(let s of r.rtcpFeedback)Ma(s)}function bp(r){if(typeof r!="object")throw new TypeError("ext is not an object");if(!r.uri||typeof r.uri!="string")throw new TypeError("missing ext.uri");if(typeof r.id!="number")throw new TypeError("missing ext.id");if(r.encrypt&&typeof r.encrypt!="boolean")throw new TypeError("invalid ext.encrypt");r.encrypt||(r.encrypt=!1),(!r.parameters||typeof r.parameters!="object")&&(r.parameters={});for(let e of Object.keys(r.parameters)){let t=r.parameters[e];if(t===void 0&&(r.parameters[e]="",t=""),typeof t!="string"&&typeof t!="number")throw new TypeError("invalid header extension parameter")}}function Sp(r){if(typeof r!="object")throw new TypeError("encoding is not an object");if(r.ssrc&&typeof r.ssrc!="number")throw new TypeError("invalid encoding.ssrc");if(r.rid&&typeof r.rid!="string")throw new TypeError("invalid encoding.rid");if(r.rtx&&typeof r.rtx!="object")throw new TypeError("invalid encoding.rtx");if(r.rtx&&typeof r.rtx.ssrc!="number")throw new TypeError("missing encoding.rtx.ssrc");if((!r.dtx||typeof r.dtx!="boolean")&&(r.dtx=!1),r.scalabilityMode&&typeof r.scalabilityMode!="string")throw new TypeError("invalid encoding.scalabilityMode")}function kp(r){if(typeof r!="object")throw new TypeError("rtcp is not an object");if(r.cname&&typeof r.cname!="string")throw new TypeError("invalid rtcp.cname");(!r.reducedSize||typeof r.reducedSize!="boolean")&&(r.reducedSize=!0)}function Tp(r){if(typeof r!="object")throw new TypeError("numStreams is not an object");if(typeof r.OS!="number")throw new TypeError("missing numStreams.OS");if(typeof r.MIS!="number")throw new TypeError("missing numStreams.MIS")}function Oa({direction:r,extendedRtpCapabilities:e}){let t={codecs:[],headerExtensions:[]};for(let n of e.codecs){let s={kind:n.kind,mimeType:n.mimeType,preferredPayloadType:n.remotePayloadType,clockRate:n.clockRate,channels:n.channels,parameters:n.localParameters,rtcpFeedback:n.rtcpFeedback};if(t.codecs.push(s),!n.remoteRtxPayloadType)continue;let i={kind:n.kind,mimeType:`${n.kind}/rtx`,preferredPayloadType:n.remoteRtxPayloadType,clockRate:n.clockRate,parameters:{apt:n.remotePayloadType},rtcpFeedback:[]};t.codecs.push(i)}for(let n of e.headerExtensions){if(n.direction!=="sendrecv"&&n.direction!==r)continue;let s={kind:n.kind,uri:n.uri,preferredId:n.recvId,preferredEncrypt:n.encrypt??!1,direction:n.direction};t.headerExtensions.push(s)}return t}function $t(r){return r?/.+\/rtx$/i.test(r.mimeType):!1}function Js(r,e,{strict:t=!1,modify:n=!1}={}){let s=r.mimeType.toLowerCase(),i=e.mimeType.toLowerCase();if(s!==i||r.clockRate!==e.clockRate||r.channels!==e.channels)return!1;switch(s){case"video/h264":{if(t){let o=r.parameters["packetization-mode"]??0,a=e.parameters["packetization-mode"]??0;if(o!==a||!Aa.isSameProfile(r.parameters,e.parameters))return!1;let c;try{c=Aa.generateProfileLevelIdStringForAnswer(r.parameters,e.parameters)}catch{return!1}n&&(c?(r.parameters["profile-level-id"]=c,e.parameters["profile-level-id"]=c):(delete r.parameters["profile-level-id"],delete e.parameters["profile-level-id"]))}break}case"video/vp9":{if(t){let o=r.parameters["profile-id"]??0,a=e.parameters["profile-id"]??0;if(o!==a)return!1}break}}return!0}function Rp(r,e){return!(r.kind&&e.kind&&r.kind!==e.kind||r.uri!==e.uri)}function La(r,e){let t=[];for(let n of r.rtcpFeedback??[]){let s=(e.rtcpFeedback??[]).find(i=>i.type===n.type&&(i.parameter===n.parameter||!i.parameter&&!n.parameter));s&&t.push(s)}return t}});var Ua=D(Cn=>{"use strict";Object.defineProperty(Cn,"__esModule",{value:!0});Cn.Logger=void 0;var Bt=xr(),Ht="awaitqueue",Zs=class{_debug;_warn;_error;constructor(e){e?(this._debug=Bt(`${Ht}:${e}`),this._warn=Bt(`${Ht}:WARN:${e}`),this._error=Bt(`${Ht}:ERROR:${e}`)):(this._debug=Bt(Ht),this._warn=Bt(`${Ht}:WARN`),this._error=Bt(`${Ht}:ERROR`)),this._debug.log=console.info.bind(console),this._warn.log=console.warn.bind(console),this._error.log=console.error.bind(console)}get debug(){return this._debug}get warn(){return this._warn}get error(){return this._error}};Cn.Logger=Zs});var ri=D(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.AwaitQueueRemovedTaskError=Vt.AwaitQueueStoppedError=void 0;var ei=class r extends Error{constructor(e){super(e??"queue stopped"),this.name="AwaitQueueStoppedError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};Vt.AwaitQueueStoppedError=ei;var ti=class r extends Error{constructor(e){super(e??"queue task removed"),this.name="AwaitQueueRemovedTaskError",typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(this,r)}};Vt.AwaitQueueRemovedTaskError=ti});var Na=D(En=>{"use strict";Object.defineProperty(En,"__esModule",{value:!0});En.AwaitQueue=void 0;var Cp=Ua(),ni=ri(),$e=new Cp.Logger("AwaitQueue"),si=class{pendingTasks=new Map;nextTaskId=0;constructor(){$e.debug("constructor()")}get size(){return this.pendingTasks.size}async push(e,t,n){if(t=t??e.name,$e.debug(`push() [name:${t}, options:%o]`,n),typeof e!="function")throw new TypeError("given task is not a function");if(t)try{Object.defineProperty(e,"name",{value:t})}catch{}return new Promise((s,i)=>{if(t&&n?.removeOngoingTasksWithSameName)for(let a of this.pendingTasks.values())a.name===t&&a.reject(new ni.AwaitQueueRemovedTaskError,{canExecuteNextTask:!1});let o={id:this.nextTaskId++,task:e,name:t,enqueuedAt:Date.now(),executedAt:void 0,completed:!1,resolve:a=>{if(o.completed)return;o.completed=!0,this.pendingTasks.delete(o.id),$e.debug(`resolving task [name:${o.name}]`),s(a);let[c]=this.pendingTasks.values();c&&!c.executedAt&&this.execute(c)},reject:(a,{canExecuteNextTask:c})=>{if(!o.completed&&(o.completed=!0,this.pendingTasks.delete(o.id),$e.debug(`rejecting task [name:${o.name}]: %s`,String(a)),i(a),c)){let[u]=this.pendingTasks.values();u&&!u.executedAt&&this.execute(u)}}};this.pendingTasks.set(o.id,o),this.pendingTasks.size===1&&this.execute(o)})}stop(){$e.debug("stop()");for(let e of this.pendingTasks.values())$e.debug(`stop() | stopping task [name:${e.name}]`),e.reject(new ni.AwaitQueueStoppedError,{canExecuteNextTask:!1})}remove(e){$e.debug(`remove() [taskIdx:${e}]`);let t=Array.from(this.pendingTasks.values())[e];if(!t){$e.debug(`stop() | no task with given idx [taskIdx:${e}]`);return}t.reject(new ni.AwaitQueueRemovedTaskError,{canExecuteNextTask:!0})}dump(){let e=Date.now(),t=0;return Array.from(this.pendingTasks.values()).map(n=>({idx:t++,task:n.task,name:n.name,enqueuedTime:n.executedAt?n.executedAt-n.enqueuedAt:e-n.enqueuedAt,executionTime:n.executedAt?e-n.executedAt:0}))}async execute(e){if($e.debug(`execute() [name:${e.name}]`),e.executedAt)throw new Error("task already being executed");e.executedAt=Date.now();try{let t=await e.task();e.resolve(t)}catch(t){e.reject(t,{canExecuteNextTask:!0})}}};En.AwaitQueue=si});var Wa=D(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.AwaitQueueRemovedTaskError=Xe.AwaitQueueStoppedError=Xe.AwaitQueue=void 0;var Ep=Na();Object.defineProperty(Xe,"AwaitQueue",{enumerable:!0,get:function(){return Ep.AwaitQueue}});var Fa=ri();Object.defineProperty(Xe,"AwaitQueueStoppedError",{enumerable:!0,get:function(){return Fa.AwaitQueueStoppedError}});Object.defineProperty(Xe,"AwaitQueueRemovedTaskError",{enumerable:!0,get:function(){return Fa.AwaitQueueRemovedTaskError}})});var qa=D(Pn=>{"use strict";Object.defineProperty(Pn,"__esModule",{value:!0});Pn.Producer=void 0;var Pp=ie(),ja=he(),zt=ye(),Ue=new Pp.Logger("Producer"),ii=class extends ja.EnhancedEventEmitter{_id;_localId;_closed=!1;_rtpSender;_track;_kind;_rtpParameters;_paused;_maxSpatialLayer;_stopTracks;_disableTrackOnPause;_zeroRtpOnPause;_appData;_observer=new ja.EnhancedEventEmitter;constructor({id:e,localId:t,rtpSender:n,track:s,rtpParameters:i,stopTracks:o,disableTrackOnPause:a,zeroRtpOnPause:c,appData:u}){super(),Ue.debug("constructor()"),this._id=e,this._localId=t,this._rtpSender=n,this._track=s,this._kind=s.kind,this._rtpParameters=i,this._paused=a?!s.enabled:!1,this._maxSpatialLayer=void 0,this._stopTracks=o,this._disableTrackOnPause=a,this._zeroRtpOnPause=c,this._appData=u??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get closed(){return this._closed}get kind(){return this._kind}get rtpSender(){return this._rtpSender}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get maxSpatialLayer(){return this._maxSpatialLayer}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Ue.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Ue.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new zt.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(Ue.debug("pause()"),this._closed){Ue.error("pause() | Producer closed");return}this._paused=!0,this._track&&this._disableTrackOnPause&&(this._track.enabled=!1),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@pause",e,t)}).catch(()=>{}),this._observer.safeEmit("pause")}resume(){if(Ue.debug("resume()"),this._closed){Ue.error("resume() | Producer closed");return}this._paused=!1,this._track&&this._disableTrackOnPause&&(this._track.enabled=!0),this._zeroRtpOnPause&&new Promise((e,t)=>{this.safeEmit("@resume",e,t)}).catch(()=>{}),this._observer.safeEmit("resume")}async replaceTrack({track:e}){if(Ue.debug("replaceTrack() [track:%o]",e),this._closed){if(e&&this._stopTracks)try{e.stop()}catch{}throw new zt.InvalidStateError("closed")}else if(e?.readyState==="ended")throw new zt.InvalidStateError("track ended");if(e===this._track){Ue.debug("replaceTrack() | same track, ignored");return}await new Promise((t,n)=>{this.safeEmit("@replacetrack",e,t,n)}),this.destroyTrack(),this._track=e,this._track&&this._disableTrackOnPause&&(this._paused?this._paused&&(this._track.enabled=!1):this._track.enabled=!0),this.handleTrack()}async setMaxSpatialLayer(e){if(this._closed)throw new zt.InvalidStateError("closed");if(this._kind!=="video")throw new zt.UnsupportedError("not a video Producer");if(typeof e!="number")throw new TypeError("invalid spatialLayer");e!==this._maxSpatialLayer&&(await new Promise((t,n)=>{this.safeEmit("@setmaxspatiallayer",e,t,n)}).catch(()=>{}),this._maxSpatialLayer=e)}async setRtpEncodingParameters(e){if(this._closed)throw new zt.InvalidStateError("closed");if(typeof e!="object")throw new TypeError("invalid params");await new Promise((t,n)=>{this.safeEmit("@setrtpencodingparameters",e,t,n)})}onTrackEnded(){Ue.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track&&this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){if(this._track)try{this._track.removeEventListener("ended",this.onTrackEnded),this._stopTracks&&this._track.stop()}catch{}}};Pn.Producer=ii});var Ba=D(Dn=>{"use strict";Object.defineProperty(Dn,"__esModule",{value:!0});Dn.Consumer=void 0;var Dp=ie(),$a=he(),Ip=ye(),Ne=new Dp.Logger("Consumer"),oi=class extends $a.EnhancedEventEmitter{_id;_localId;_producerId;_closed=!1;_rtpReceiver;_track;_rtpParameters;_paused;_appData;_observer=new $a.EnhancedEventEmitter;constructor({id:e,localId:t,producerId:n,rtpReceiver:s,track:i,rtpParameters:o,appData:a}){super(),Ne.debug("constructor()"),this._id=e,this._localId=t,this._producerId=n,this._rtpReceiver=s,this._track=i,this._rtpParameters=o,this._paused=!i.enabled,this._appData=a??{},this.onTrackEnded=this.onTrackEnded.bind(this),this.handleTrack()}get id(){return this._id}get localId(){return this._localId}get producerId(){return this._producerId}get closed(){return this._closed}get kind(){return this._track.kind}get rtpReceiver(){return this._rtpReceiver}get track(){return this._track}get rtpParameters(){return this._rtpParameters}get paused(){return this._paused}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Ne.debug("close()"),this._closed=!0,this.destroyTrack(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Ne.debug("transportClosed()"),this._closed=!0,this.destroyTrack(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}async getStats(){if(this._closed)throw new Ip.InvalidStateError("closed");return new Promise((e,t)=>{this.safeEmit("@getstats",e,t)})}pause(){if(Ne.debug("pause()"),this._closed){Ne.error("pause() | Consumer closed");return}if(this._paused){Ne.debug("pause() | Consumer is already paused");return}this._paused=!0,this._track.enabled=!1,this.emit("@pause"),this._observer.safeEmit("pause")}resume(){if(Ne.debug("resume()"),this._closed){Ne.error("resume() | Consumer closed");return}if(!this._paused){Ne.debug("resume() | Consumer is already resumed");return}this._paused=!1,this._track.enabled=!0,this.emit("@resume"),this._observer.safeEmit("resume")}onTrackEnded(){Ne.debug('track "ended" event'),this.safeEmit("trackended"),this._observer.safeEmit("trackended")}handleTrack(){this._track.addEventListener("ended",this.onTrackEnded)}destroyTrack(){try{this._track.removeEventListener("ended",this.onTrackEnded),this._track.stop()}catch{}}};Dn.Consumer=oi});var Va=D(In=>{"use strict";Object.defineProperty(In,"__esModule",{value:!0});In.DataProducer=void 0;var xp=ie(),Ha=he(),Ap=ye(),Be=new xp.Logger("DataProducer"),ai=class extends Ha.EnhancedEventEmitter{_id;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new Ha.EnhancedEventEmitter;constructor({id:e,dataChannel:t,sctpStreamParameters:n,appData:s}){super(),Be.debug("constructor()"),this._id=e,this._dataChannel=t,this._sctpStreamParameters=n,this._appData=s??{},this.handleDataChannel()}get id(){return this._id}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get bufferedAmount(){return this._dataChannel.bufferedAmount}get bufferedAmountLowThreshold(){return this._dataChannel.bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._dataChannel.bufferedAmountLowThreshold=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(Be.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(Be.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}send(e){if(Be.debug("send()"),this._closed)throw new Ap.InvalidStateError("closed");this._dataChannel.send(e)}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(Be.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?Be.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):Be.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(Be.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",()=>{this._closed||Be.warn('DataChannel "message" event in a DataProducer, message discarded')}),this._dataChannel.addEventListener("bufferedamountlow",()=>{this._closed||this.safeEmit("bufferedamountlow")})}};In.DataProducer=ai});var Ga=D(xn=>{"use strict";Object.defineProperty(xn,"__esModule",{value:!0});xn.DataConsumer=void 0;var Lp=ie(),za=he(),lt=new Lp.Logger("DataConsumer"),ci=class extends za.EnhancedEventEmitter{_id;_dataProducerId;_dataChannel;_closed=!1;_sctpStreamParameters;_appData;_observer=new za.EnhancedEventEmitter;constructor({id:e,dataProducerId:t,dataChannel:n,sctpStreamParameters:s,appData:i}){super(),lt.debug("constructor()"),this._id=e,this._dataProducerId=t,this._dataChannel=n,this._sctpStreamParameters=s,this._appData=i??{},this.handleDataChannel()}get id(){return this._id}get dataProducerId(){return this._dataProducerId}get closed(){return this._closed}get sctpStreamParameters(){return this._sctpStreamParameters}get readyState(){return this._dataChannel.readyState}get label(){return this._dataChannel.label}get protocol(){return this._dataChannel.protocol}get binaryType(){return this._dataChannel.binaryType}set binaryType(e){this._dataChannel.binaryType=e}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){this._closed||(lt.debug("close()"),this._closed=!0,this._dataChannel.close(),this.emit("@close"),this._observer.safeEmit("close"),super.close(),this._observer.close())}transportClosed(){this._closed||(lt.debug("transportClosed()"),this._closed=!0,this._dataChannel.close(),this.safeEmit("transportclose"),this._observer.safeEmit("close"))}handleDataChannel(){this._dataChannel.addEventListener("open",()=>{this._closed||(lt.debug('DataChannel "open" event'),this.safeEmit("open"))}),this._dataChannel.addEventListener("error",e=>{if(this._closed)return;let t=e.error??new Error("unknown DataChannel error");e.error?.errorDetail==="sctp-failure"?lt.error("DataChannel SCTP error [sctpCauseCode:%s]: %s",e.error?.sctpCauseCode,e.error.message):lt.error('DataChannel "error" event: %o',t),this.safeEmit("error",t)}),this._dataChannel.addEventListener("close",()=>{this._closed||(lt.warn('DataChannel "close" event'),this._closed=!0,this.emit("@close"),this.safeEmit("close"),this._observer.safeEmit("close"))}),this._dataChannel.addEventListener("message",e=>{this._closed||this.safeEmit("message",e.data)})}};xn.DataConsumer=ci});var Ya=D(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.Transport=void 0;var Mp=Wa(),Op=ie(),Ka=he(),Q=ye(),di=dt(),Lr=Oe(),Up=qa(),Np=Ba(),Fp=Va(),Wp=Ga(),G=new Op.Logger("Transport"),ui=class{consumerOptions;promise;resolve;reject;constructor(e){this.consumerOptions=e,this.promise=new Promise((t,n)=>{this.resolve=t,this.reject=n})}},li=class extends Ka.EnhancedEventEmitter{_id;_closed=!1;_direction;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_canProduceByKind;_maxSctpMessageSize;_handler;_iceGatheringState="new";_connectionState="new";_appData;_producers=new Map;_consumers=new Map;_dataProducers=new Map;_dataConsumers=new Map;_probatorConsumerCreated=!1;_awaitQueue=new Mp.AwaitQueue;_pendingConsumerTasks=[];_consumerCreationInProgress=!1;_pendingPauseConsumers=new Map;_consumerPauseInProgress=!1;_pendingResumeConsumers=new Map;_consumerResumeInProgress=!1;_pendingCloseConsumers=new Map;_consumerCloseInProgress=!1;_observer=new Ka.EnhancedEventEmitter;constructor({direction:e,id:t,iceParameters:n,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:u,appData:d,handlerFactory:l,getSendExtendedRtpCapabilities:p,recvRtpCapabilities:f,canProduceByKind:h}){super(),G.debug("constructor() [id:%s, direction:%s]",t,e),this._id=t,this._direction=e,this._getSendExtendedRtpCapabilities=p,this._recvRtpCapabilities=f,this._canProduceByKind=h,this._maxSctpMessageSize=o?.maxMessageSize;let m=di.clone(u)??{};delete m.iceServers,delete m.iceTransportPolicy,delete m.bundlePolicy,delete m.rtcpMuxPolicy,this._handler=l.factory({direction:e,iceParameters:n,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:m,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities}),this._appData=d??{},this.handleHandler()}get id(){return this._id}get closed(){return this._closed}get direction(){return this._direction}get handler(){return this._handler}get iceGatheringState(){return this._iceGatheringState}get connectionState(){return this._connectionState}get appData(){return this._appData}set appData(e){this._appData=e}get observer(){return this._observer}close(){if(!this._closed){G.debug("close()"),this._closed=!0,this._awaitQueue.stop(),this._handler.close(),this._connectionState="closed";for(let e of this._producers.values())e.transportClosed();this._producers.clear();for(let e of this._consumers.values())e.transportClosed();this._consumers.clear();for(let e of this._dataProducers.values())e.transportClosed();this._dataProducers.clear();for(let e of this._dataConsumers.values())e.transportClosed();this._dataConsumers.clear(),this._observer.safeEmit("close"),super.close(),this._observer.close()}}async getStats(){if(this._closed)throw new Q.InvalidStateError("closed");return this._handler.getTransportStats()}async restartIce({iceParameters:e}){if(G.debug("restartIce()"),this._closed)throw new Q.InvalidStateError("closed");if(!e)throw new TypeError("missing iceParameters");return this._awaitQueue.push(async()=>await this._handler.restartIce(e),"transport.restartIce()")}async updateIceServers({iceServers:e}={}){if(G.debug("updateIceServers()"),this._closed)throw new Q.InvalidStateError("closed");if(!Array.isArray(e))throw new TypeError("missing iceServers");return this._awaitQueue.push(async()=>this._handler.updateIceServers(e),"transport.updateIceServers()")}async produce({track:e,streamId:t,encodings:n,codecOptions:s,headerExtensionOptions:i,codec:o,stopTracks:a=!0,disableTrackOnPause:c=!0,zeroRtpOnPause:u=!1,onRtpSender:d,appData:l={}}={}){if(G.debug("produce() [track:%o]",e),this._closed)throw new Q.InvalidStateError("closed");if(e){if(this._direction!=="send")throw new Q.UnsupportedError("not a sending Transport");if(this._canProduceByKind[e.kind]){if(e.readyState==="ended")throw new Q.InvalidStateError("track ended");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("produce")===0)throw new TypeError('no "produce" listener set into this transport');if(l&&typeof l!="object")throw new TypeError("if given, appData must be an object")}else throw new Q.UnsupportedError(`cannot produce ${e.kind}`)}else throw new TypeError("missing track");return this._awaitQueue.push(async()=>{let p;if(n&&!Array.isArray(n))throw TypeError("encodings must be an array");n?.length===0?p=void 0:n&&(p=n.map(g=>{let _={active:!0};return g.active===!1&&(_.active=!1),typeof g.dtx=="boolean"&&(_.dtx=g.dtx),typeof g.scalabilityMode=="string"&&(_.scalabilityMode=g.scalabilityMode),typeof g.scaleResolutionDownBy=="number"&&(_.scaleResolutionDownBy=g.scaleResolutionDownBy),typeof g.maxBitrate=="number"&&(_.maxBitrate=g.maxBitrate),typeof g.maxFramerate=="number"&&(_.maxFramerate=g.maxFramerate),typeof g.adaptivePtime=="boolean"&&(_.adaptivePtime=g.adaptivePtime),typeof g.priority=="string"&&(_.priority=g.priority),typeof g.networkPriority=="string"&&(_.networkPriority=g.networkPriority),_}));let{localId:f,rtpParameters:h,rtpSender:m}=await this._handler.send({track:e,streamId:t,encodings:p,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:d});try{Lr.validateAndNormalizeRtpParameters(h);let{id:g}=await new Promise((v,y)=>{this.safeEmit("produce",{kind:e.kind,rtpParameters:h,appData:l},v,y)}),_=new Up.Producer({id:g,localId:f,rtpSender:m,track:e,rtpParameters:h,stopTracks:a,disableTrackOnPause:c,zeroRtpOnPause:u,appData:l});return this._producers.set(_.id,_),this.handleProducer(_),this._observer.safeEmit("newproducer",_),_}catch(g){throw this._handler.stopSending(f).catch(()=>{}),g}},"transport.produce()").catch(p=>{if(a)try{e.stop()}catch{}throw p})}async consume({id:e,producerId:t,kind:n,rtpParameters:s,streamId:i,onRtpReceiver:o,appData:a={}}){if(G.debug("consume()"),this._closed)throw new Q.InvalidStateError("closed");if(this._direction!=="recv")throw new Q.UnsupportedError("not a receiving Transport");if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing producerId");if(n!=="audio"&&n!=="video")throw new TypeError(`invalid kind '${n}'`);if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(a&&typeof a!="object")throw new TypeError("if given, appData must be an object");let c=di.clone(s);if(!Lr.canReceive(c,this._recvRtpCapabilities))throw new Q.UnsupportedError("cannot consume this Producer");let d=new ui({id:e,producerId:t,kind:n,rtpParameters:c,streamId:i,onRtpReceiver:o,appData:a});return this._pendingConsumerTasks.push(d),queueMicrotask(()=>{this._closed||this._consumerCreationInProgress===!1&&this.createPendingConsumers()}),d.promise}async produceData({ordered:e=!0,maxPacketLifeTime:t,maxRetransmits:n,label:s="",protocol:i="",appData:o={}}={}){if(G.debug("produceData()"),this._closed)throw new Q.InvalidStateError("closed");if(this._direction!=="send")throw new Q.UnsupportedError("not a sending Transport");if(this._maxSctpMessageSize){if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(this.listenerCount("producedata")===0)throw new TypeError('no "producedata" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new Q.UnsupportedError("SCTP not enabled by remote Transport");return(t||n)&&(e=!1),this._awaitQueue.push(async()=>{let{dataChannel:a,sctpStreamParameters:c}=await this._handler.sendDataChannel({sctpStreamParameters:{ordered:e,maxPacketLifeTime:t,maxRetransmits:n,label:s,protocol:i}});Lr.validateAndNormalizeSctpStreamParameters(c);let{id:u}=await new Promise((l,p)=>{this.safeEmit("producedata",{sctpStreamParameters:c,label:s,protocol:i,appData:o},l,p)}),d=new Fp.DataProducer({id:u,dataChannel:a,sctpStreamParameters:c,appData:o});return this._dataProducers.set(d.id,d),this.handleDataProducer(d),this._observer.safeEmit("newdataproducer",d),d},"transport.produceData()")}async consumeData({id:e,dataProducerId:t,sctpStreamParameters:n,label:s="",protocol:i="",appData:o={}}){if(G.debug("consumeData()"),this._closed)throw new Q.InvalidStateError("closed");if(this._direction!=="recv")throw new Q.UnsupportedError("not a receiving Transport");if(this._maxSctpMessageSize){if(typeof e!="string")throw new TypeError("missing id");if(typeof t!="string")throw new TypeError("missing dataProducerId");if(this.listenerCount("connect")===0&&this._connectionState==="new")throw new TypeError('no "connect" listener set into this transport');if(o&&typeof o!="object")throw new TypeError("if given, appData must be an object")}else throw new Q.UnsupportedError("SCTP not enabled by remote Transport");let a=di.clone(n);return Lr.validateAndNormalizeSctpStreamParameters(a),this._awaitQueue.push(async()=>{let{dataChannel:c}=await this._handler.receiveDataChannel({maxMessageSize:this._maxSctpMessageSize,sctpStreamParameters:a,label:s,protocol:i}),u=new Wp.DataConsumer({id:e,dataProducerId:t,dataChannel:c,sctpStreamParameters:a,appData:o});return this._dataConsumers.set(u.id,u),this.handleDataConsumer(u),this._observer.safeEmit("newdataconsumer",u),u},"transport.consumeData()")}getDataChannelMaxMessageSize(){return this._handler.getDataChannelMaxMessageSize()}createPendingConsumers(){this._consumerCreationInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingConsumerTasks.length===0){G.debug("createPendingConsumers() | there is no Consumer to be created");return}let e=[...this._pendingConsumerTasks];this._pendingConsumerTasks=[];let t,n=[];for(let s of e){let{id:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:u}=s.consumerOptions;n.push({trackId:i,kind:o,rtpParameters:a,streamId:c,onRtpReceiver:u})}try{let s=await this._handler.receive(n);for(let i=0;i<s.length;++i){let o=e[i],a=s[i],{id:c,producerId:u,kind:d,rtpParameters:l,appData:p}=o.consumerOptions,{localId:f,rtpReceiver:h,track:m}=a,g=new Np.Consumer({id:c,localId:f,producerId:u,rtpReceiver:h,track:m,rtpParameters:l,appData:p});this._consumers.set(g.id,g),this.handleConsumer(g),!this._probatorConsumerCreated&&!t&&d==="video"&&(t=g),this._observer.safeEmit("newconsumer",g),o.resolve(g)}}catch(s){for(let i of e)i.reject(s)}if(t)try{let s=Lr.generateProbatorRtpParameters(t.rtpParameters);await this._handler.receive([{trackId:"probator",kind:"video",rtpParameters:s}]),G.debug("createPendingConsumers() | Consumer for RTP probation created"),this._probatorConsumerCreated=!0}catch(s){G.error("createPendingConsumers() | failed to create Consumer for RTP probation:%o",s)}},"transport.createPendingConsumers()").then(()=>{this._consumerCreationInProgress=!1,this._pendingConsumerTasks.length>0&&this.createPendingConsumers()}).catch(()=>{})}pausePendingConsumers(){this._consumerPauseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingPauseConsumers.size===0){G.debug("pausePendingConsumers() | there is no Consumer to be paused");return}let e=Array.from(this._pendingPauseConsumers.values());this._pendingPauseConsumers.clear();try{let t=e.map(n=>n.localId);await this._handler.pauseReceiving(t)}catch(t){G.error("pausePendingConsumers() | failed to pause Consumers:",t)}},"transport.pausePendingConsumers()").then(()=>{this._consumerPauseInProgress=!1,this._pendingPauseConsumers.size>0&&this.pausePendingConsumers()}).catch(()=>{})}resumePendingConsumers(){this._consumerResumeInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingResumeConsumers.size===0){G.debug("resumePendingConsumers() | there is no Consumer to be resumed");return}let e=Array.from(this._pendingResumeConsumers.values());this._pendingResumeConsumers.clear();try{let t=e.map(n=>n.localId);await this._handler.resumeReceiving(t)}catch(t){G.error("resumePendingConsumers() | failed to resume Consumers:",t)}},"transport.resumePendingConsumers()").then(()=>{this._consumerResumeInProgress=!1,this._pendingResumeConsumers.size>0&&this.resumePendingConsumers()}).catch(()=>{})}closePendingConsumers(){this._consumerCloseInProgress=!0,this._awaitQueue.push(async()=>{if(this._pendingCloseConsumers.size===0){G.debug("closePendingConsumers() | there is no Consumer to be closed");return}let e=Array.from(this._pendingCloseConsumers.values());this._pendingCloseConsumers.clear();try{await this._handler.stopReceiving(e.map(t=>t.localId))}catch(t){G.error("closePendingConsumers() | failed to close Consumers:",t)}},"transport.closePendingConsumers()").then(()=>{this._consumerCloseInProgress=!1,this._pendingCloseConsumers.size>0&&this.closePendingConsumers()}).catch(()=>{})}handleHandler(){let e=this._handler;e.on("@connect",({dtlsParameters:t},n,s)=>{if(this._closed){s(new Q.InvalidStateError("closed"));return}this.safeEmit("connect",{dtlsParameters:t},n,s)}),e.on("@icegatheringstatechange",t=>{t!==this._iceGatheringState&&(G.debug("ICE gathering state changed to %s",t),this._iceGatheringState=t,this._closed||this.safeEmit("icegatheringstatechange",t))}),e.on("@icecandidateerror",t=>{G.warn(`ICE candidate error [url:${t.url}, localAddress:${t.address}, localPort:${t.port}]: ${t.errorCode} "${t.errorText}"`),this.safeEmit("icecandidateerror",t)}),e.on("@connectionstatechange",t=>{t!==this._connectionState&&(G.debug("connection state changed to %s",t),this._connectionState=t,this._closed||this.safeEmit("connectionstatechange",t))})}handleProducer(e){e.on("@close",()=>{this._producers.delete(e.id),!this._closed&&this._awaitQueue.push(async()=>await this._handler.stopSending(e.localId),"producer @close event").catch(t=>G.warn("producer.close() failed:%o",t))}),e.on("@pause",(t,n)=>{this._awaitQueue.push(async()=>await this._handler.pauseSending(e.localId),"producer @pause event").then(t).catch(n)}),e.on("@resume",(t,n)=>{this._awaitQueue.push(async()=>await this._handler.resumeSending(e.localId),"producer @resume event").then(t).catch(n)}),e.on("@replacetrack",(t,n,s)=>{this._awaitQueue.push(async()=>await this._handler.replaceTrack(e.localId,t),"producer @replacetrack event").then(n).catch(s)}),e.on("@setmaxspatiallayer",(t,n,s)=>{this._awaitQueue.push(async()=>await this._handler.setMaxSpatialLayer(e.localId,t),"producer @setmaxspatiallayer event").then(n).catch(s)}),e.on("@setrtpencodingparameters",(t,n,s)=>{this._awaitQueue.push(async()=>await this._handler.setRtpEncodingParameters(e.localId,t),"producer @setrtpencodingparameters event").then(n).catch(s)}),e.on("@getstats",(t,n)=>{if(this._closed)return n(new Q.InvalidStateError("closed"));this._handler.getSenderStats(e.localId).then(t).catch(n)})}handleConsumer(e){e.on("@close",()=>{this._consumers.delete(e.id),this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.delete(e.id),!this._closed&&(this._pendingCloseConsumers.set(e.id,e),this._consumerCloseInProgress===!1&&this.closePendingConsumers())}),e.on("@pause",()=>{this._pendingResumeConsumers.has(e.id)&&this._pendingResumeConsumers.delete(e.id),this._pendingPauseConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerPauseInProgress===!1&&this.pausePendingConsumers()})}),e.on("@resume",()=>{this._pendingPauseConsumers.has(e.id)&&this._pendingPauseConsumers.delete(e.id),this._pendingResumeConsumers.set(e.id,e),queueMicrotask(()=>{this._closed||this._consumerResumeInProgress===!1&&this.resumePendingConsumers()})}),e.on("@getstats",(t,n)=>{if(this._closed)return n(new Q.InvalidStateError("closed"));this._handler.getReceiverStats(e.localId).then(t).catch(n)})}handleDataProducer(e){e.on("@close",()=>{this._dataProducers.delete(e.id)})}handleDataConsumer(e){e.on("@close",()=>{this._dataConsumers.delete(e.id)})}};An.Transport=li});var Ln=D((Ag,Ja)=>{"use strict";var Qa=Ja.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(r){return r.encoding?"rtpmap:%d %s/%s/%s":r.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(r){return r.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(r){return r.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(r){return"extmap:%d"+(r.direction?"/%s":"%v")+(r["encrypt-uri"]?" %s":"%v")+" %s"+(r.config?" %s":"")}},{name:"extmapAllowMixed",reg:/^(extmap-allow-mixed)/},{push:"crypto",reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:["id","suite","config","sessionConfig"],format:function(r){return r.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"},{push:"msid",reg:/^msid:([\w-]+)(?: ([\w-]+))?/,names:["id","appdata"],format:"msid:%s %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(r){var e="candidate:%s %d %s %d %s %d typ %s";return e+=r.raddr!=null?" raddr %s rport %d":"%v%v",e+=r.tcptype!=null?" tcptype %s":"%v",r.generation!=null&&(e+=" generation %d"),e+=r["network-id"]!=null?" network-id %d":"%v",e+=r["network-cost"]!=null?" network-cost %d":"%v",e}},{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(r){var e="ssrc:%d";return r.attribute!=null&&(e+=" %s",r.value!=null&&(e+=":%s")),e}},{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(r){return r.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(r){return r.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(r){return"imageattr:%s %s %s"+(r.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(r){return"simulcast:%s %s"+(r.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(r){return"ts-refclk:%s"+(r.clksrcExt!=null?"=%s":"")}},{name:"mediaClk",reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:["id","mediaClockName","mediaClockValue","rateNumerator","rateDenominator"],format:function(r){var e="mediaclk:";return e+=r.id!=null?"id=%s %s":"%v%s",e+=r.mediaClockValue!=null?"=%s":"",e+=r.rateNumerator!=null?" rate=%s":"",e+=r.rateDenominator!=null?"/%s":"",e}},{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"]}]};Object.keys(Qa).forEach(function(r){var e=Qa[r];e.forEach(function(t){t.reg||(t.reg=/(.*)/),t.format||(t.format="%s")})})});var ec=D(He=>{"use strict";var Gt=function(r){return String(Number(r))===r?Number(r):r},jp=function(r,e,t,n){if(n&&!t)e[n]=Gt(r[1]);else for(var s=0;s<t.length;s+=1)r[s+1]!=null&&(e[t[s]]=Gt(r[s+1]))},qp=function(r,e,t){var n=r.name&&r.names;r.push&&!e[r.push]?e[r.push]=[]:n&&!e[r.name]&&(e[r.name]={});var s=r.push?{}:n?e[r.name]:e;jp(t.match(r.reg),s,r.names,r.name),r.push&&e[r.push].push(s)},Xa=Ln(),$p=RegExp.prototype.test.bind(/^([a-z])=(.*)/);He.parse=function(r){var e={},t=[],n=e;return r.split(/(\r\n|\r|\n)/).filter($p).forEach(function(s){var i=s[0],o=s.slice(2);i==="m"&&(t.push({rtp:[],fmtp:[]}),n=t[t.length-1]);for(var a=0;a<(Xa[i]||[]).length;a+=1){var c=Xa[i][a];if(c.reg.test(o))return qp(c,n,o)}}),e.media=t,e};var Za=function(r,e){var t=e.split(/=(.+)/,2);return t.length===2?r[t[0]]=Gt(t[1]):t.length===1&&e.length>1&&(r[t[0]]=void 0),r};He.parseParams=function(r){return r.split(/;\s?/).reduce(Za,{})};He.parseFmtpConfig=He.parseParams;He.parsePayloads=function(r){return r.toString().split(" ").map(Number)};He.parseRemoteCandidates=function(r){for(var e=[],t=r.split(" ").map(Gt),n=0;n<t.length;n+=3)e.push({component:t[n],ip:t[n+1],port:t[n+2]});return e};He.parseImageAttributes=function(r){return r.split(" ").map(function(e){return e.substring(1,e.length-1).split(",").reduce(Za,{})})};He.parseSimulcastStreamList=function(r){return r.split(";").map(function(e){return e.split(",").map(function(t){var n,s=!1;return t[0]!=="~"?n=Gt(t):(n=Gt(t.substring(1,t.length)),s=!0),{scid:n,paused:s}})})}});var rc=D((Mg,tc)=>{"use strict";var pi=Ln(),Bp=/%[sdv%]/g,Hp=function(r){var e=1,t=arguments,n=t.length;return r.replace(Bp,function(s){if(e>=n)return s;var i=t[e];switch(e+=1,s){case"%%":return"%";case"%s":return String(i);case"%d":return Number(i);case"%v":return""}})},Mr=function(r,e,t){var n=e.format instanceof Function?e.format(e.push?t:t[e.name]):e.format,s=[r+"="+n];if(e.names)for(var i=0;i<e.names.length;i+=1){var o=e.names[i];e.name?s.push(t[e.name][o]):s.push(t[e.names[i]])}else s.push(t[e.name]);return Hp.apply(null,s)},Vp=["v","o","s","i","u","e","p","c","b","t","r","z","a"],zp=["i","c","b","a"];tc.exports=function(r,e){e=e||{},r.version==null&&(r.version=0),r.name==null&&(r.name=" "),r.media.forEach(function(i){i.payloads==null&&(i.payloads="")});var t=e.outerOrder||Vp,n=e.innerOrder||zp,s=[];return t.forEach(function(i){pi[i].forEach(function(o){o.name in r&&r[o.name]!=null?s.push(Mr(i,o,r)):o.push in r&&r[o.push]!=null&&r[o.push].forEach(function(a){s.push(Mr(i,o,a))})})}),r.media.forEach(function(i){s.push(Mr("m",pi.m[0],i)),n.forEach(function(o){pi[o].forEach(function(a){a.name in i&&i[a.name]!=null?s.push(Mr(o,a,i)):a.push in i&&i[a.push]!=null&&i[a.push].forEach(function(c){s.push(Mr(o,a,c))})})})}),s.join(`\r
|
|
6
6
|
`)+`\r
|
|
7
|
-
`}});var Ve=D(Fe=>{"use strict";var lt=Xa(),zp=ec(),Gp=An();Fe.grammar=Gp;Fe.write=zp;Fe.parse=lt.parse;Fe.parseParams=lt.parseParams;Fe.parseFmtpConfig=lt.parseFmtpConfig;Fe.parsePayloads=lt.parsePayloads;Fe.parseRemoteCandidates=lt.parseRemoteCandidates;Fe.parseImageAttributes=lt.parseImageAttributes;Fe.parseSimulcastStreamList=lt.parseSimulcastStreamList});var pt=D(li=>{"use strict";Object.defineProperty(li,"__esModule",{value:!0});li.parse=Yp;var Kp=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function Yp(r){let e=Kp.exec(r??"");return e?{spatialLayers:Number(e[1]),temporalLayers:Number(e[2])}:{spatialLayers:1,temporalLayers:1}}});var nc=D(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.OfferMediaSection=Xe.AnswerMediaSection=Xe.MediaSection=void 0;var Qp=Ve(),tc=ct(),Mr=class{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(let s of t){let i={foundation:s.foundation,component:1,ip:s.address??s.ip,port:s.port,priority:s.priority,transport:s.protocol,type:s.type};s.tcpType&&(i.tcptype=s.tcpType),this._mediaObject.candidates.push(i)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}n&&this.setDtlsRole(n.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return this._mediaObject.port===0}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}};Xe.MediaSection=Mr;var pi=class extends Mr{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n,sctpParameters:s,plainRtpParameters:i,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:u}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:n}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":{this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(let d of c.codecs){let l={payload:d.payloadType,codec:rc(d),rate:d.clockRate};d.channels>1&&(l.encoding=d.channels),this._mediaObject.rtp.push(l);let p=tc.clone(d.parameters)??{},f=tc.clone(d.rtcpFeedback)??[];if(u){let{opusStereo:m,opusFec:g,opusDtx:_,opusMaxPlaybackRate:v,opusMaxAverageBitrate:y,opusPtime:S,opusNack:w,videoGoogleStartBitrate:b,videoGoogleMaxBitrate:O,videoGoogleMinBitrate:j}=u,F=a.codecs.find($=>$.payloadType===d.payloadType);switch(d.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{m!==void 0&&(F.parameters["sprop-stereo"]=m?1:0,p.stereo=m?1:0),g!==void 0&&(F.parameters.useinbandfec=g?1:0,p.useinbandfec=g?1:0),_!==void 0&&(F.parameters.usedtx=_?1:0,p.usedtx=_?1:0),v!==void 0&&(p.maxplaybackrate=v),y!==void 0&&(p.maxaveragebitrate=y),S!==void 0&&(F.parameters.ptime=S,p.ptime=S),w||(F.rtcpFeedback=F.rtcpFeedback.filter($=>$.type!=="nack"||$.parameter),f=f.filter($=>$.type!=="nack"||$.parameter));break}case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":{b!==void 0&&(p["x-google-start-bitrate"]=b),O!==void 0&&(p["x-google-max-bitrate"]=O),j!==void 0&&(p["x-google-min-bitrate"]=j);break}}}let h={payload:d.payloadType,config:""};for(let m of Object.keys(p))h.config&&(h.config+=";"),h.config+=`${m}=${p[m]}`;h.config&&this._mediaObject.fmtp.push(h);for(let m of f)this._mediaObject.rtcpFb.push({payload:d.payloadType,type:m.type,subtype:m.parameter})}this._mediaObject.payloads=c.codecs.map(d=>d.payloadType).join(" "),this._mediaObject.ext=[];for(let d of c.headerExtensions)(o.ext??[]).some(p=>p.uri===d.uri)&&this._mediaObject.ext.push({uri:d.uri,value:d.id});if(o.extmapAllowMixed==="extmap-allow-mixed"&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(let d of o.rids??[])d.direction==="send"&&this._mediaObject.rids.push({id:d.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(let d of o.rids??[])d.direction==="send"&&this._mediaObject.rids.push({id:d.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break}case"application":{typeof o.sctpPort=="number"?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=s.port,this._mediaObject.maxMessageSize=s.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=String(s.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:s.port,maxMessageSize:s.maxMessageSize});break}}}setDtlsRole(e){switch(e){case"client":{this._mediaObject.setup="active";break}case"server":{this._mediaObject.setup="passive";break}case"auto":{this._mediaObject.setup="actpass";break}}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;let t={};for(let i of e)i.rid&&(t[i.rid]=i);let n=this._mediaObject.simulcast.list1,s=Qp.parseSimulcastStreamList(n);for(let i of s)for(let o of i)o.paused=!t[o.scid]?.active;this._mediaObject.simulcast.list1=s.map(i=>i.map(o=>`${o.paused?"~":""}${o.scid}`).join(",")).join(";")}};Xe.AnswerMediaSection=pi;var hi=class extends Mr{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n,sctpParameters:s,plainRtpParameters:i,mid:o,kind:a,offerRtpParameters:c,streamId:u,trackId:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:n}),this._mediaObject.mid=String(o),this._mediaObject.type=a,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},s?this._mediaObject.protocol="UDP/DTLS/SCTP":this._mediaObject.protocol="UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:u,appdata:d}];for(let h of c.codecs){let m={payload:h.payloadType,codec:rc(h),rate:h.clockRate};h.channels>1&&(m.encoding=h.channels),this._mediaObject.rtp.push(m);let g={payload:h.payloadType,config:""};for(let _ of Object.keys(h.parameters??{}))g.config&&(g.config+=";"),g.config+=`${_}=${h.parameters[_]}`;g.config&&this._mediaObject.fmtp.push(g);for(let _ of h.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:h.payloadType,type:_.type,subtype:_.parameter})}this._mediaObject.payloads=c.codecs.map(h=>h.payloadType).join(" "),this._mediaObject.ext=[];for(let h of c.headerExtensions)this._mediaObject.ext.push({uri:h.uri,value:h.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let l=c.encodings[0],p=l.ssrc,f=l.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],p&&c.rtcp.cname&&this._mediaObject.ssrcs.push({id:p,attribute:"cname",value:c.rtcp.cname}),f&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:f,attribute:"cname",value:c.rtcp.cname}),p&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${p} ${f}`}));break}case"application":{this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=s.port,this._mediaObject.maxMessageSize=s.maxMessageSize;break}}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}};Xe.OfferMediaSection=hi;function rc(r){let t=new RegExp("^(audio|video)/(.+)","i").exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}});var Gt=D(On=>{"use strict";Object.defineProperty(On,"__esModule",{value:!0});On.RemoteSdp=void 0;var Jp=Ve(),Xp=se(),Ln=nc(),Zp=mi(),eh=["av1","h264"],Mn=new Xp.Logger("RemoteSdp"),fi=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n,sctpParameters:s,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=n,this._sctpParameters=s,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`media-client-v${Zp.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),n){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};let o=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:n.fingerprints[o-1].algorithm,hash:n.fingerprints[o-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){Mn.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(let t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){Mn.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(let t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){Mn.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){let t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:n,answerRtpParameters:s,codecOptions:i}){let o=new Ln.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:n,answerRtpParameters:s,codecOptions:i}),a=o.getObject();a.rtp.find(u=>eh.includes(u.codec.toLowerCase()))||(a.ext=a.ext?.filter(u=>u.uri!=="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension")),t?this.replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this.replaceMediaSection(o):this.addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:n,streamId:s,trackId:i}){this.setSessionExtmapAllowMixed();let o=new Ln.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:n,streamId:s,trackId:i}),a=this._mediaSections.find(c=>c.closed&&c.getObject().type===t);a?this.replaceMediaSection(o,a.mid):this.addMediaSection(o)}pauseMediaSection(e){this.findMediaSection(e).pause()}resumeSendingMediaSection(e){this.findMediaSection(e).resume()}resumeReceivingMediaSection(e){this.findMediaSection(e).resume()}disableMediaSection(e){this.findMediaSection(e).disable()}closeMediaSection(e){let t=this.findMediaSection(e);return e===this._firstMid?(Mn.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){let n=this.findMediaSection(e);n.muxSimulcastStreams(t),this.replaceMediaSection(n)}sendSctpAssociation({offerMediaObject:e}){let t=new Ln.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this.addMediaSection(t)}receiveSctpAssociation(){let e=new Ln.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(e)}getSdp(){return this._sdpObject.origin.sessionVersion++,Jp.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if(typeof t=="string"){let n=this._midToIndex.get(t);if(n===void 0)throw new Error(`no media section found for reuseMid '${t}'`);let s=this._mediaSections[n];this._mediaSections[n]=e,this._midToIndex.delete(s.mid),this._midToIndex.set(e.mid,n),this._sdpObject.media[n]=e.getObject(),this.regenerateBundleMids()}else{let n=this._midToIndex.get(e.mid);if(n===void 0)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[n]=e,this._sdpObject.media[n]=e.getObject()}}findMediaSection(e){let t=this._midToIndex.get(e);if(t===void 0)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(e=>!e.closed).map(e=>e.mid).join(" "))}};On.RemoteSdp=fi});var Kt=D(ht=>{"use strict";Object.defineProperty(ht,"__esModule",{value:!0});ht.extractRtpCapabilities=th;ht.extractDtlsParameters=rh;ht.getCname=nh;ht.applyCodecParameters=sh;ht.addHeaderExtension=ih;var sc=Ve();function th({sdpObject:r}){let e=new Map,t=new Map;for(let s of r.media){let i=s.type;switch(i){case"audio":case"video":break;default:continue}for(let o of s.rtp){let a={kind:i,mimeType:`${i}/${o.codec}`,preferredPayloadType:o.payload,clockRate:o.rate,channels:o.encoding,parameters:{},rtcpFeedback:[]};e.set(a.preferredPayloadType,a)}for(let o of s.fmtp??[]){let a=sc.parseParams(o.config),c=e.get(o.payload);c&&(a?.hasOwnProperty("profile-level-id")&&(a["profile-level-id"]=String(a["profile-level-id"])),c.parameters=a)}for(let o of s.rtcpFb??[]){let a={type:o.type,parameter:o.subtype};if(a.parameter||delete a.parameter,o.payload!=="*"){let c=e.get(Number(o.payload));if(!c)continue;c.rtcpFeedback.push(a)}else for(let c of e.values())c.kind===i&&!/.+\/rtx$/i.test(c.mimeType)&&c.rtcpFeedback.push(a)}for(let o of s.ext??[]){if(o["encrypt-uri"])continue;let a={kind:i,uri:o.uri,preferredId:o.value};t.set(a.preferredId,a)}}return{codecs:Array.from(e.values()),headerExtensions:Array.from(t.values())}}function rh({sdpObject:r}){let e=r.setup,t=r.fingerprint;if(!e||!t){let i=(r.media??[]).find(o=>o.port!==0);i&&(e=e??i.setup,t=t??i.fingerprint)}if(e){if(!t)throw new Error("no a=fingerprint found at SDP session or media level")}else throw new Error("no a=setup found at SDP session or media level");let n;switch(e){case"active":{n="client";break}case"passive":{n="server";break}case"actpass":{n="auto";break}}return{role:n,fingerprints:[{algorithm:t.type,value:t.hash}]}}function nh({offerMediaObject:r}){let e=(r.ssrcs??[]).find(t=>t.attribute==="cname");return e?e.value:""}function sh({offerRtpParameters:r,answerMediaObject:e}){for(let t of r.codecs){let n=t.mimeType.toLowerCase();if(n!=="audio/opus"||!(e.rtp??[]).find(a=>a.payload===t.payloadType))continue;e.fmtp=e.fmtp??[];let i=e.fmtp.find(a=>a.payload===t.payloadType);i||(i={payload:t.payloadType,config:""},e.fmtp.push(i));let o=sc.parseParams(i.config);if(n==="audio/opus"){let a=t.parameters?.["sprop-stereo"];a!==void 0&&(o.stereo=Number(a)?1:0)}i.config="";for(let a of Object.keys(o))i.config&&(i.config+=";"),i.config+=`${a}=${o[a]}`}}function ih({offerMediaObject:r,headerExtensionUri:e,headerExtensionId:t}){r.ext||(r.ext=[]),r.ext.push({uri:e,value:t})}});var Yt=D(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.getRtpEncodings=oh;Un.addLegacySimulcast=ah;function oh({offerMediaObject:r,codecs:e}){let t=new Set;for(let i of r.ssrcs??[]){let o=i.id;o&&t.add(o)}if(t.size===0)throw new Error("no a=ssrc lines found");let n=new Map;for(let i of r.ssrcGroups??[]){if(i.semantics!=="FID")continue;let o=i.ssrcs.split(/\s+/),a=Number(o[0]),c=Number(o[1]);t.has(a)&&(t.delete(a),t.delete(c),n.set(a,c))}for(let i of t)n.set(i,void 0);let s=[];for(let[i,o]of n){let a={ssrc:i};o&&e.length>1&&(a.rtx={ssrc:o}),s.push(a)}return s}function ah({offerMediaObject:r,numStreams:e}){if(e<=1)throw new TypeError("numStreams must be greater than 1");let t=(r.ssrcs??[]).find(l=>l.attribute==="msid");if(!t)throw new Error("a=ssrc line with msid information not found");let[n,s]=t.value.split(" "),i=Number(t.id),o;(r.ssrcGroups??[]).some(l=>{if(l.semantics!=="FID")return!1;let p=l.ssrcs.split(/\s+/);return Number(p[0])===i?(o=Number(p[1]),!0):!1});let a=(r.ssrcs??[]).find(l=>l.attribute==="cname");if(!a)throw new Error("a=ssrc line with cname information not found");let c=a.value,u=[],d=[];for(let l=0;l<e;++l)u.push(i+l),o&&d.push(o+l);r.ssrcGroups=[],r.ssrcs=[],r.ssrcGroups.push({semantics:"SIM",ssrcs:u.join(" ")});for(let l of u)r.ssrcs.push({id:l,attribute:"cname",value:c}),r.ssrcs.push({id:l,attribute:"msid",value:`${n} ${s}`});for(let l=0;l<d.length;++l){let p=u[l],f=d[l];r.ssrcs.push({id:f,attribute:"cname",value:c}),r.ssrcs.push({id:f,attribute:"msid",value:`${n} ${s}`}),r.ssrcGroups.push({semantics:"FID",ssrcs:`${p} ${f}`})}}});var Qt=D(Or=>{"use strict";Object.defineProperty(Or,"__esModule",{value:!0});Or.addNackSupportForOpus=ch;Or.addHeaderExtensionSupport=dh;Or.getMsidStreamIdAndTrackId=uh;function ch(r){for(let e of r.codecs??[])(e.mimeType.toLowerCase()==="audio/opus"||e.mimeType.toLowerCase()==="audio/multiopus")&&!e.rtcpFeedback?.some(t=>t.type==="nack"&&!t.parameter)&&(e.rtcpFeedback||(e.rtcpFeedback=[]),e.rtcpFeedback.push({type:"nack"}))}function dh(r,e){let t,n=r.headerExtensions?.find(i=>i.uri===e.uri);if(n){if(n.kind===e.kind)return;t=n.preferredId}if(r.headerExtensions||(r.headerExtensions=[]),t===void 0){t=1;let i=new Set(r.headerExtensions.map(o=>o.preferredId));for(;i.has(t);)++t}let s={kind:e.kind,uri:e.uri,preferredId:t,preferredEncrypt:!1,direction:e.direction};r.headerExtensions.push(s)}function uh(r){if(!r||typeof r!="string")return{msidStreamId:void 0,msidTrackId:void 0};let[e,t]=r.trim().split(/\s+/);return e?{msidStreamId:e,msidTrackId:t}:{msidStreamId:void 0,msidTrackId:void 0}}});var cc=D(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.Chrome111=void 0;var We=Ve(),lh=pe(),ph=se(),Ur=Oe(),hh=we(),fh=pt(),mh=Gt(),Nr=Kt(),ic=Yt(),gi=Qt(),x=new ph.Logger("Chrome111"),oc="Chrome111",ac={OS:65535,MIS:65535},_i=class r extends lh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:oc,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{x.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});let n=await t.createOffer();try{t.close()}catch{}t=void 0;let s=We.parse(n.sdp);return r.getLocalRtpCapabilities(s)}catch(n){try{t?.close()}catch{}throw t=void 0,n}},getNativeSctpCapabilities:async()=>(x.debug("getNativeSctpCapabilities()"),{numStreams:ac})}}static getLocalRtpCapabilities(e,t=[]){let n=Nr.extractRtpCapabilities({sdpObject:e});Ur.validateAndNormalizeRtpCapabilities(n),gi.addNackSupportForOpus(n);for(let s of t)gi.addHeaderExtensionSupport(n,s);return n}constructor({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:u}){super(),x.debug("constructor()"),this._direction=e,this._remoteSdp=new mh.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=u,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(x.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return oc}close(){if(x.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),x.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),x.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});x.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let n={type:"answer",sdp:this._remoteSdp.getSdp()};x.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};x.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();x.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:n,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){if(this.assertNotClosed(),this.assertSendDirection(),x.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),n&&n.length>1){let S=1;for(let w of n){let b=w.scalabilityMode?(0,fh.parse)(w.scalabilityMode).temporalLayers:3;b>S&&(S=b)}n.forEach((w,b)=>{w.rid=`r${b}`,w.scalabilityMode=`L1T${S}`})}let c=this._remoteSdp.getNextMediaSectionIdx(),u=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:n});a&&a(u.sender);let d=await this._pc.createOffer(),l=We.parse(d.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=r.getLocalRtpCapabilities(l,p),h=this._getSendExtendedRtpCapabilities(f),m=Ur.getSendingRtpParameters(e.kind,h);m.codecs=Ur.reduceCodecs(m.codecs,o);let g=Ur.getSendingRemoteRtpParameters(e.kind,h);if(g.codecs=Ur.reduceCodecs(g.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),i?.absCaptureTime){let S=l.media[c.idx];Nr.addHeaderExtension({offerMediaObject:S,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(w=>w.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:We.write(l)}}x.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let _=u.mid;m.mid=_,l=We.parse(this._pc.localDescription.sdp);let v=l.media[c.idx];if(m.rtcp.cname=Nr.getCname({offerMediaObject:v}),m.msid=`${t??this._sendStream.id} ${e.id}`,!n)m.encodings=ic.getRtpEncodings({offerMediaObject:v,codecs:m.codecs});else if(n.length===1){let S=ic.getRtpEncodings({offerMediaObject:v,codecs:m.codecs});Object.assign(S[0],n[0]),m.encodings=S}else m.encodings=n;this._remoteSdp.send({offerMediaObject:v,reuseMid:c.reuseMid,offerRtpParameters:m,answerRtpParameters:g,codecOptions:s});let y={type:"answer",sdp:this._remoteSdp.getSdp()};return x.debug("send() | calling pc.setRemoteDescription() [answer:%o]",y),await this._pc.setRemoteDescription(y),this._mapMidTransceiver.set(_,u),{localId:_,rtpParameters:m,rtpSender:u.sender}}async stopSending(e){if(this.assertSendDirection(),x.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();x.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};x.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),x.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let n=await this._pc.createOffer();x.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};x.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),x.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let n=await this._pc.createOffer();x.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};x.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?x.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):x.debug("replaceTrack() [localId:%s, no track]",e);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),x.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();x.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};x.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),x.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();x.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};x.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};x.debug("sendDataChannel() [options:%o]",t);let n=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%ac.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=We.parse(i.sdp),a=o.media.find(u=>u.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),x.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};x.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:n,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],n=new Map;for(let a of e){let{trackId:c,kind:u,rtpParameters:d,streamId:l}=a;x.debug("receive() [trackId:%s, kind:%s]",c,u);let p=d.mid??String(this._mapMidTransceiver.size);n.set(c,p);let{msidStreamId:f}=gi.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:u,offerRtpParameters:d,streamId:l??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};x.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:u}=a;if(u){let d=n.get(c),l=this._pc.getTransceivers().find(p=>p.mid===d);if(!l)throw new Error("transceiver not found");u(l.receiver)}}let i=await this._pc.createAnswer(),o=We.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:u}=a,d=n.get(c),l=o.media.find(p=>String(p.mid)===d);Nr.applyCodecParameters({offerRtpParameters:u,answerMediaObject:l})}i={type:"answer",sdp:We.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),x.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,u=n.get(c),d=this._pc.getTransceivers().find(l=>l.mid===u);if(d)this._mapMidTransceiver.set(u,d),t.push({localId:u,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){x.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};x.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();x.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){x.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};x.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();x.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){x.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};x.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();x.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:n,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};x.debug("receiveDataChannel() [options:%o]",u);let d=this._pc.createDataChannel(n,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};x.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let p=await this._pc.createAnswer(),f=We.parse(p.sdp),h=f.media.find(m=>m.type==="application");h.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:We.write(f)},x.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=We.parse(this._pc.localDescription.sdp));let n=Nr.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:n},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new hh.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};Nn.Chrome111=_i});var lc=D(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.Chrome74=void 0;var ye=Ve(),gh=se(),_h=pe(),Fr=Oe(),vh=we(),wh=pt(),yh=Gt(),Wr=Kt(),vi=Yt(),wi=Qt(),E=new gh.Logger("Chrome74"),dc="Chrome74",uc={OS:1024,MIS:1024},yi=class r extends _h.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:dc,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{E.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let n=await t.createOffer();try{t.close()}catch{}t=void 0;let s=ye.parse(n.sdp);return r.getLocalRtpCapabilities(s)}catch(n){try{t?.close()}catch{}throw t=void 0,n}},getNativeSctpCapabilities:async()=>(E.debug("getNativeSctpCapabilities()"),{numStreams:uc})}}static getLocalRtpCapabilities(e,t=[]){let n=Wr.extractRtpCapabilities({sdpObject:e});Fr.validateAndNormalizeRtpCapabilities(n),wi.addNackSupportForOpus(n);for(let s of t)wi.addHeaderExtensionSupport(n,s);return n}constructor({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:u}){super(),E.debug("constructor()"),this._direction=e,this._remoteSdp=new yh.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=u,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(E.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return dc}close(){if(E.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),E.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),E.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});E.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let n={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();E.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:n,codecOptions:s,headerExtensionOptions:i,codec:o}){this.assertNotClosed(),this.assertSendDirection(),E.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),n&&n.length>1&&n.forEach((w,b)=>{w.rid=`r${b}`});let a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:n}),u=await this._pc.createOffer(),d=ye.parse(u.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let p=r.getLocalRtpCapabilities(d,l),f=this._getSendExtendedRtpCapabilities(p),h=Fr.getSendingRtpParameters(e.kind,f);h.codecs=Fr.reduceCodecs(h.codecs,o);let m=Fr.getSendingRemoteRtpParameters(e.kind,f);m.codecs=Fr.reduceCodecs(m.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:d});let g=!1,_=(0,wh.parse)((n??[{}])[0].scalabilityMode),v;n?.length===1&&_.spatialLayers>1&&h.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(E.debug("send() | enabling legacy simulcast for VP9 SVC"),g=!0,d=ye.parse(u.sdp),v=d.media[a.idx],vi.addLegacySimulcast({offerMediaObject:v,numStreams:_.spatialLayers}),u={type:"offer",sdp:ye.write(d)}),E.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),i?.absCaptureTime&&(v=d.media[a.idx],Wr.addHeaderExtension({offerMediaObject:v,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find(w=>w.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),u={type:"offer",sdp:ye.write(d)}),await this._pc.setLocalDescription(u);let y=c.mid;if(h.mid=y,d=ye.parse(this._pc.localDescription.sdp),v=d.media[a.idx],h.rtcp.cname=Wr.getCname({offerMediaObject:v}),h.msid=`${t??this._sendStream.id} ${e.id}`,!n)h.encodings=vi.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});else if(n.length===1){let w=vi.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});Object.assign(w[0],n[0]),g&&(w=[w[0]]),h.encodings=w}else h.encodings=n;if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let w of h.encodings)w.scalabilityMode?w.scalabilityMode=`L1T${_.temporalLayers}`:w.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:v,reuseMid:a.reuseMid,offerRtpParameters:h,answerRtpParameters:m,codecOptions:s});let S={type:"answer",sdp:this._remoteSdp.getSdp()};return E.debug("send() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.set(y,c),{localId:y,rtpParameters:h,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),E.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();E.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),E.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let n=await this._pc.createOffer();E.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),E.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let n=await this._pc.createOffer();E.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?E.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):E.debug("replaceTrack() [localId:%s, no track]",e);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),E.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();E.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),E.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();E.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};E.debug("sendDataChannel() [options:%o]",t);let n=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%uc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=ye.parse(i.sdp),a=o.media.find(u=>u.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),E.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:n,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],n=new Map;for(let a of e){let{trackId:c,kind:u,rtpParameters:d,streamId:l}=a;E.debug("receive() [trackId:%s, kind:%s]",c,u);let p=d.mid??String(this._mapMidTransceiver.size);n.set(c,p);let{msidStreamId:f}=wi.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:u,offerRtpParameters:d,streamId:l??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);let i=await this._pc.createAnswer(),o=ye.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:u}=a,d=n.get(c),l=o.media.find(p=>String(p.mid)===d);Wr.applyCodecParameters({offerRtpParameters:u,answerMediaObject:l})}i={type:"answer",sdp:ye.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),E.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,u=n.get(c),d=this._pc.getTransceivers().find(l=>l.mid===u);if(d)this._mapMidTransceiver.set(u,d),t.push({localId:u,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){E.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();E.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){E.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();E.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){E.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();E.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:n,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};E.debug("receiveDataChannel() [options:%o]",u);let d=this._pc.createDataChannel(n,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let p=await this._pc.createAnswer(),f=ye.parse(p.sdp),h=f.media.find(m=>m.type==="application");h.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:ye.write(f)},E.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ye.parse(this._pc.localDescription.sdp));let n=Wr.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:n},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new vh.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};Fn.Chrome74=yi});var gc=D(jn=>{"use strict";Object.defineProperty(jn,"__esModule",{value:!0});jn.Firefox120=void 0;var ze=Ve(),bh=pe(),Sh=se(),pc=we(),jr=Oe(),kh=pt(),Th=Gt(),Wn=Kt(),hc=Yt(),Rh=Qt(),A=new Sh.Logger("Firefox120"),fc="Firefox120",mc={OS:16,MIS:2048},bi=class r extends bh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:fc,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{A.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),n=document.createElement("canvas");n.getContext("2d");let i=n.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(i,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});let o=await t.createOffer();try{n.remove()}catch{}try{i.stop()}catch{}try{t.close()}catch{}t=void 0;let a=ze.parse(o.sdp);return r.getLocalRtpCapabilities(a)}catch(o){try{n.remove()}catch{}try{i.stop()}catch{}try{t?.close()}catch{}throw t=void 0,o}},getNativeSctpCapabilities:async()=>(A.debug("getNativeSctpCapabilities()"),{numStreams:mc})}}static getLocalRtpCapabilities(e){let t=Wn.extractRtpCapabilities({sdpObject:e});return jr.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:u}){super(),A.debug("constructor()"),this._direction=e,this._remoteSdp=new Th.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=u,this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(A.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return fc}close(){if(A.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){throw this.assertNotClosed(),new pc.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),A.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});A.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let n={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();A.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:n,codecOptions:s,codec:i,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),A.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),n&&n.length>1&&n.forEach((v,y)=>{v.rid=`r${y}`});let a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:n});o&&o(a.sender);let c=await this._pc.createOffer(),u=ze.parse(c.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let d=r.getLocalRtpCapabilities(u),l=this._getSendExtendedRtpCapabilities(d),p=jr.getSendingRtpParameters(e.kind,l);p.codecs=jr.reduceCodecs(p.codecs,i);let f=jr.getSendingRemoteRtpParameters(e.kind,l);f.codecs=jr.reduceCodecs(f.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:u});let h=(0,kh.parse)((n??[{}])[0].scalabilityMode);A.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);let m=a.mid;p.mid=m,u=ze.parse(this._pc.localDescription.sdp);let g=u.media[u.media.length-1];if(p.rtcp.cname=Wn.getCname({offerMediaObject:g}),p.msid=`${t??this._sendStream.id} ${e.id}`,!n)p.encodings=hc.getRtpEncodings({offerMediaObject:g,codecs:p.codecs});else if(n.length===1){let v=hc.getRtpEncodings({offerMediaObject:g,codecs:p.codecs});Object.assign(v[0],n[0]),p.encodings=v}else p.encodings=n;if(p.encodings.length>1&&(p.codecs[0].mimeType.toLowerCase()==="video/vp8"||p.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let v of p.encodings)v.scalabilityMode?v.scalabilityMode=`L1T${h.temporalLayers}`:v.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:g,offerRtpParameters:p,answerRtpParameters:f,codecOptions:s});let _={type:"answer",sdp:this._remoteSdp.getSdp()};return A.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(m,a),{localId:m,rtpParameters:p,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),A.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);let n=await this._pc.createOffer();A.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),A.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let n=await this._pc.createOffer();A.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),A.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let n=await this._pc.createOffer();A.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?A.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):A.debug("replaceTrack() [localId:%s, no track]",e);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),A.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated transceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();A.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),A.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();A.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};A.debug("sendDataChannel() [options:%o]",t);let n=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%mc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=ze.parse(i.sdp),a=o.media.find(u=>u.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),A.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:n,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],n=new Map;for(let a of e){let{trackId:c,kind:u,rtpParameters:d,streamId:l}=a;A.debug("receive() [trackId:%s, kind:%s]",c,u);let p=d.mid??String(this._mapMidTransceiver.size);n.set(c,p);let{msidStreamId:f}=Rh.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:u,offerRtpParameters:d,streamId:l??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:u}=a;if(u){let d=n.get(c),l=this._pc.getTransceivers().find(p=>p.mid===d);if(!l)throw new Error("transceiver not found");u(l.receiver)}}let i=await this._pc.createAnswer(),o=ze.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:u}=a,d=n.get(c),l=o.media.find(p=>String(p.mid)===d);Wn.applyCodecParameters({offerRtpParameters:u,answerMediaObject:l}),i={type:"answer",sdp:ze.write(o)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),A.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,u=n.get(c),d=this._pc.getTransceivers().find(l=>l.mid===u);if(!d)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(u,d),t.push({localId:u,track:d.receiver.track,rtpReceiver:d.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){A.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();A.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){A.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();A.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){A.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();A.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:n,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};A.debug("receiveDataChannel() [options:%o]",u);let d=this._pc.createDataChannel(n,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let p=await this._pc.createAnswer(),f=ze.parse(p.sdp),h=f.media.find(m=>m.type==="application");h.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:f}),p={type:"answer",sdp:ze.write(f)},A.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ze.parse(this._pc.localDescription.sdp));let n=Wn.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:n},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new pc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};jn.Firefox120=bi});var yc=D(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.Safari12=void 0;var be=Ve(),Ch=pe(),Eh=se(),qr=Oe(),Ph=we(),Dh=pt(),xh=Gt(),$r=Kt(),_c=Yt(),Si=Qt(),P=new Eh.Logger("Safari12"),vc="Safari12",wc={OS:65535,MIS:65535},ki=class r extends Ch.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:vc,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{P.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let n=await t.createOffer();try{t.close()}catch{}t=void 0;let s=be.parse(n.sdp);return r.getLocalRtpCapabilities(s)}catch(n){try{t?.close()}catch{}throw t=void 0,n}},getNativeSctpCapabilities:async()=>(P.debug("getNativeSctpCapabilities()"),{numStreams:wc})}}static getLocalRtpCapabilities(e,t=[]){let n=$r.extractRtpCapabilities({sdpObject:e});qr.validateAndNormalizeRtpCapabilities(n),Si.addNackSupportForOpus(n);for(let s of t)Si.addHeaderExtensionSupport(n,s);return n}constructor({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:u}){super(),P.debug("constructor()"),this._direction=e,this._remoteSdp=new xh.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=u,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",d=>{this.emit("@icecandidateerror",d)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(P.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return vc}close(){if(P.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),P.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),P.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});P.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let n={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();P.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:n,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),P.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);let c=this._remoteSdp.getNextMediaSectionIdx(),u=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});a&&a(u.sender);let d=await this._pc.createOffer(),l=be.parse(d.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=r.getLocalRtpCapabilities(l,p),h=this._getSendExtendedRtpCapabilities(f),m=qr.getSendingRtpParameters(e.kind,h);m.codecs=qr.reduceCodecs(m.codecs,o);let g=qr.getSendingRemoteRtpParameters(e.kind,h);g.codecs=qr.reduceCodecs(g.codecs,o);let _;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let v=(0,Dh.parse)((n??[{}])[0].scalabilityMode);n&&n.length>1&&(P.debug("send() | enabling legacy simulcast"),l=be.parse(d.sdp),_=l.media[c.idx],_c.addLegacySimulcast({offerMediaObject:_,numStreams:n.length}),d={type:"offer",sdp:be.write(l)}),i?.absCaptureTime&&(_=l.media[c.idx],$r.addHeaderExtension({offerMediaObject:_,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(w=>w.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:be.write(l)}),P.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let y=u.mid;if(m.mid=y,l=be.parse(this._pc.localDescription.sdp),_=l.media[c.idx],m.rtcp.cname=$r.getCname({offerMediaObject:_}),m.msid=`${t??this._sendStream.id} ${e.id}`,m.encodings=_c.getRtpEncodings({offerMediaObject:_,codecs:m.codecs}),n)for(let w=0;w<m.encodings.length;++w)n[w]&&Object.assign(m.encodings[w],n[w]);if(m.encodings.length>1&&(m.codecs[0].mimeType.toLowerCase()==="video/vp8"||m.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let w of m.encodings)w.scalabilityMode?w.scalabilityMode=`L1T${v.temporalLayers}`:w.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:_,reuseMid:c.reuseMid,offerRtpParameters:m,answerRtpParameters:g,codecOptions:s});let S={type:"answer",sdp:this._remoteSdp.getSdp()};return P.debug("send() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.set(y,u),{localId:y,rtpParameters:m,rtpSender:u.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;P.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();P.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),P.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let n=await this._pc.createOffer();P.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),P.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let n=await this._pc.createOffer();P.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?P.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):P.debug("replaceTrack() [localId:%s, no track]",e);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),P.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();P.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),P.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();P.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};P.debug("sendDataChannel() [options:%o]",t);let n=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%wc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=be.parse(i.sdp),a=o.media.find(u=>u.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),P.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:n,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],n=new Map;for(let a of e){let{trackId:c,kind:u,rtpParameters:d,streamId:l}=a;P.debug("receive() [trackId:%s, kind:%s]",c,u);let p=d.mid??String(this._mapMidTransceiver.size);n.set(c,p);let{msidStreamId:f}=Si.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:u,offerRtpParameters:d,streamId:l??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:u}=a;if(u){let d=n.get(c),l=this._pc.getTransceivers().find(p=>p.mid===d);if(!l)throw new Error("transceiver not found");u(l.receiver)}}let i=await this._pc.createAnswer(),o=be.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:u}=a,d=n.get(c),l=o.media.find(p=>String(p.mid)===d);$r.applyCodecParameters({offerRtpParameters:u,answerMediaObject:l})}i={type:"answer",sdp:be.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),P.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,u=n.get(c),d=this._pc.getTransceivers().find(l=>l.mid===u);if(!d)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(u,d),t.push({localId:u,track:d.receiver.track,rtpReceiver:d.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){P.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();P.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){P.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();P.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){P.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();P.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:n,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};P.debug("receiveDataChannel() [options:%o]",u);let d=this._pc.createDataChannel(n,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let p=await this._pc.createAnswer(),f=be.parse(p.sdp),h=f.media.find(m=>m.type==="application");h.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:be.write(f)},P.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=be.parse(this._pc.localDescription.sdp));let n=$r.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:n},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Ph.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};qn.Safari12=ki});var kc=D($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.ReactNative106=void 0;var Se=Ve(),Ih=pe(),Ah=se(),Br=Oe(),Lh=we(),Mh=pt(),Oh=Gt(),Hr=Kt(),Ti=Yt(),Ri=Qt(),C=new Ah.Logger("ReactNative106"),bc="ReactNative106",Sc={OS:65535,MIS:65535},Ci=class r extends Ih.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:bc,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{C.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let n=await t.createOffer();try{t.close()}catch{}t=void 0;let s=Se.parse(n.sdp);return r.getLocalRtpCapabilities(s)}catch(n){try{t?.close()}catch{}throw t=void 0,n}},getNativeSctpCapabilities:async()=>(C.debug("getNativeSctpCapabilities()"),{numStreams:Sc})}}static getLocalRtpCapabilities(e,t=[]){let n=Hr.extractRtpCapabilities({sdpObject:e});Br.validateAndNormalizeRtpCapabilities(n),Ri.addNackSupportForOpus(n);for(let s of t)Ri.addHeaderExtensionSupport(n,s);return n}constructor({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:u}){super(),C.debug("constructor()"),this._direction=e,this._remoteSdp=new Oh.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=u,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(C.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return bc}close(){if(C.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),C.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),C.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});C.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let n={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();C.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:n,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),C.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),n&&n.length>1&&n.forEach((b,O)=>{b.rid=`r${O}`});let c=this._remoteSdp.getNextMediaSectionIdx(),u=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:n});a&&a(u.sender);let d=await this._pc.createOffer(),l=Se.parse(d.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=r.getLocalRtpCapabilities(l,p),h=this._getSendExtendedRtpCapabilities(f),m=Br.getSendingRtpParameters(e.kind,h);m.codecs=Br.reduceCodecs(m.codecs,o);let g=Br.getSendingRemoteRtpParameters(e.kind,h);g.codecs=Br.reduceCodecs(g.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let _=!1,v=(0,Mh.parse)((n??[{}])[0].scalabilityMode),y;n?.length===1&&v.spatialLayers>1&&m.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(C.debug("send() | enabling legacy simulcast for VP9 SVC"),_=!0,l=Se.parse(d.sdp),y=l.media[c.idx],Ti.addLegacySimulcast({offerMediaObject:y,numStreams:v.spatialLayers}),d={type:"offer",sdp:Se.write(l)}),i?.absCaptureTime&&(y=l.media[c.idx],Hr.addHeaderExtension({offerMediaObject:y,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(b=>b.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:Se.write(l)}),C.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let S=u.mid??void 0;if(S||C.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),m.mid=S,l=Se.parse(this._pc.localDescription.sdp),y=l.media[c.idx],m.rtcp.cname=Hr.getCname({offerMediaObject:y}),m.msid=`${t??this._sendStream.id} ${e.id}`,!n)m.encodings=Ti.getRtpEncodings({offerMediaObject:y,codecs:m.codecs});else if(n.length===1){let b=Ti.getRtpEncodings({offerMediaObject:y,codecs:m.codecs});Object.assign(b[0],n[0]),_&&(b=[b[0]]),m.encodings=b}else m.encodings=n;if(m.encodings.length>1&&(m.codecs[0].mimeType.toLowerCase()==="video/vp8"||m.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let b of m.encodings)b.scalabilityMode?b.scalabilityMode=`L1T${v.temporalLayers}`:b.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:y,reuseMid:c.reuseMid,offerRtpParameters:m,answerRtpParameters:g,codecOptions:s});let w={type:"answer",sdp:this._remoteSdp.getSdp()};return C.debug("send() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w),S||(S=u.mid,m.mid=S),this._mapMidTransceiver.set(S,u),{localId:S,rtpParameters:m,rtpSender:u.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;C.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();C.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),C.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let n=await this._pc.createOffer();C.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),C.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let n=await this._pc.createOffer();C.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?C.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):C.debug("replaceTrack() [localId:%s, no track]",e);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),C.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();C.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),C.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();C.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};C.debug("sendDataChannel() [options:%o]",t);let n=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Sc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Se.parse(i.sdp),a=o.media.find(u=>u.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),C.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:n,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],n=new Map;for(let a of e){let{trackId:c,kind:u,rtpParameters:d,streamId:l}=a;C.debug("receive() [trackId:%s, kind:%s]",c,u);let p=d.mid??String(this._mapMidTransceiver.size);n.set(c,p);let{msidStreamId:f}=Ri.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:u,offerRtpParameters:d,streamId:l??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:u}=a;if(u){let d=n.get(c),l=this._pc.getTransceivers().find(p=>p.mid===d);if(!l)throw new Error("transceiver not found");u(l.receiver)}}let i=await this._pc.createAnswer(),o=Se.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:u}=a,d=n.get(c),l=o.media.find(p=>String(p.mid)===d);Hr.applyCodecParameters({offerRtpParameters:u,answerMediaObject:l})}i={type:"answer",sdp:Se.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),C.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,u=n.get(c),d=this._pc.getTransceivers().find(l=>l.mid===u);if(d)this._mapMidTransceiver.set(u,d),t.push({localId:u,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){C.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();C.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){C.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();C.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){C.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();C.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:n,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};C.debug("receiveDataChannel() [options:%o]",u);let d=this._pc.createDataChannel(n,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let p=await this._pc.createAnswer(),f=Se.parse(p.sdp),h=f.media.find(m=>m.type==="application");h.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:Se.write(f)},C.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Se.parse(this._pc.localDescription.sdp));let n=Hr.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:n},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Lh.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};$n.ReactNative106=Ci});var Ec=D(Jt=>{"use strict";Object.defineProperty(Jt,"__esModule",{value:!0});Jt.Device=void 0;Jt.detectDevice=Tc;Jt.detectDeviceAsync=Rc;var Uh=se(),Nh=pe(),Ze=we(),Bn=ct(),he=Oe(),Fh=Ga(),Wh=cc(),jh=lc(),qh=gc(),$h=yc(),Bh=kc(),T=new Uh.Logger("Device");function Tc(r,e){return T.debug("detectDevice()"),!r&&typeof navigator=="object"&&(r=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),Cc(r,e)}async function Rc(r,e){return T.debug("detectDeviceAsync()"),!r&&typeof navigator=="object"&&(r=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),Cc(r,e)}var Ei=class r{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new Nh.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(T.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&(e=await Rc(),!e))throw new Ze.UnsupportedError("device not supported");return new r({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(T.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)T.debug("constructor() | handler given: %s",e);else if(e=Tc(),e)T.debug("constructor() | detected handler: %s",e);else throw new Ze.UnsupportedError("device not supported");switch(e){case"Chrome111":{this._handlerFactory=Wh.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=jh.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=qh.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=$h.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=Bh.ReactNative106.createFactory();break}default:throw new TypeError(`unknown handlerName "${e}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new Ze.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new Ze.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new Ze.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(T.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new Ze.InvalidStateError("already loaded");let n=Bn.clone(e);he.validateAndNormalizeRtpCapabilities(n);let{getNativeRtpCapabilities:s,getNativeSctpCapabilities:i}=this._handlerFactory,o=Bn.clone(await s({direction:"recvonly"}));T.debug("load() | got native receiving RTP capabilities:%o",o),he.validateAndNormalizeRtpCapabilities(o);let a=Bn.clone(await s({direction:"sendonly"}));T.debug("load() | got native sending RTP capabilities:%o",a),he.validateAndNormalizeRtpCapabilities(a),this._getSendExtendedRtpCapabilities=d=>Bn.clone(he.getExtendedRtpCapabilities(d,n,t));let c=he.getExtendedRtpCapabilities(o,n,!1);this._recvRtpCapabilities=he.getRecvRtpCapabilities(c),T.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),he.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);let u=he.getExtendedRtpCapabilities(a,n,t);this._sendRtpCapabilities=he.getSendRtpCapabilities(u),T.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),he.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=he.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=he.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),he.validateSctpCapabilities(this._sctpCapabilities),T.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),T.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(this._loaded){if(e!=="audio"&&e!=="video")throw new TypeError(`invalid kind "${e}"`)}else throw new Ze.InvalidStateError("not loaded");return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:u}){return T.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:u})}createRecvTransport({id:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:u}){return T.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:u})}createTransport({direction:e,id:t,iceParameters:n,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:u,appData:d}){if(this._loaded){if(typeof t!="string")throw new TypeError("missing id");if(typeof n!="object")throw new TypeError("missing iceParameters");if(Array.isArray(s)){if(typeof i!="object")throw new TypeError("missing dtlsParameters");if(o&&typeof o!="object")throw new TypeError("wrong sctpParameters");if(d&&typeof d!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing iceCandidates")}else throw new Ze.InvalidStateError("not loaded");let l=new Fh.Transport({direction:e,id:t,iceParameters:n,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:u,appData:d,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",l),l}};Jt.Device=Ei;function Cc(r,e){T.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',r,e);let t=Hh(r,e);if(t){if(t>=111)return T.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111";if(t>=74)return T.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74";T.warn("detectDeviceImpl() | unsupported Chromium based browser/version");return}let n=Vh(r);if(n){if(n>=120)return T.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";T.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let s=zh(r);if(s){if(s>=605)return T.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";T.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");return}let i=Gh(r);if(i){if(i>=605)return T.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";T.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");return}if(Vr()){if(typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u")return T.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106";T.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");return}T.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',r,e)}function Hh(r,e){if(T.debug("getChromiumMajorVersion()"),Hn(r,e)){T.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(Vr()){T.debug("getChromiumMajorVersion() | this is React-Native => undefined");return}if(e){let s=(Array.isArray(e.brands)?e.brands:[]).find(i=>i.brand==="Chromium");if(s){let i=Number(s.version);return T.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${i}`),i}}let t=r?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(t?.[1]){let n=Number(t[1]);return T.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${n}`),n}T.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}function Vh(r){if(T.debug("getFirefoxMajorVersion()"),Hn(r)){T.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(Vr()){T.debug("getFirefoxMajorVersion() | this is React-Native => undefined");return}let e=r?.match(/\bFirefox\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return T.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${t}`),t}T.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}function zh(r){if(T.debug("getMacOSWebKitMajorVersion()"),Hn(r)){T.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(Vr()){T.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");return}if(!(r&&/\bSafari\b/i.test(r)&&!/\bChrome\b/i.test(r)&&!/\bChromium\b/i.test(r)&&!/\bFirefox\b/i.test(r))){T.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");return}let t=r.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){let n=Number(t[1]);return T.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${n}`),n}T.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}function Gh(r){if(T.debug("getIOSWebKitMajorVersion()"),!Hn(r)){T.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(Vr()){T.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");return}let e=r?.match(/AppleWebKit\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return T.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${t}`),t}T.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}function Hn(r,e){return T.debug("isIOS()"),e?.platform==="iOS"?(T.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):e?.platform?(T.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):r&&/iPad|iPhone|iPod/.test(r)?(T.debug("isIOS() | this is iOS based on User-Agent => true"),!0):typeof navigator=="object"&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?(T.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(T.debug("isIOS() | this is not iOS => false"),!1)}function Vr(){return T.debug("isReactNative()"),typeof navigator=="object"&&navigator.product==="ReactNative"?(T.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(T.debug("isReactNative() | this is not React-Native => false"),!1)}});var Dc=D(Pc=>{"use strict";var ft=256,zn=[],Vn;for(;ft--;)zn[ft]=(ft+256).toString(16).substring(1);function Kh(){var r=0,e,t="";if(!Vn||ft+16>256){for(Vn=Array(r=256);r--;)Vn[r]=256*Math.random()|0;r=ft=0}for(;r<16;r++)e=Vn[ft+r],r==6?t+=zn[e&15|64]:r==8?t+=zn[e&63|128]:t+=zn[e],r&1&&r>1&&r<11&&(t+="-");return ft++,t}Pc.v4=Kh});var xc=D(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.FakeEventTarget=void 0;var Pi=class{listeners={};addEventListener(e,t,n){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof n=="object"&&n.once===!0}))}removeEventListener(e,t,n){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(s=>s.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let n of[...t]){try{n.callback.call(this,e)}catch(s){setTimeout(()=>{throw s},0)}n.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}};Gn.FakeEventTarget=Pi});var Ic=D(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.FakeEvent=void 0;var Di=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=this.NONE;isTrusted=!0;target=null;timeStamp=0;cancelBubble=!1;returnValue=!0;srcElement=null;constructor(e,t={}){this.type=e,this.bubbles=t.bubbles??!1,this.cancelable=t.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(e,t,n){}};Kn.FakeEvent=Di});var Ac=D(xi=>{"use strict";Object.defineProperty(xi,"__esModule",{value:!0});xi.clone=Yh;function Yh(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}});var Mc=D(Qn=>{"use strict";Object.defineProperty(Qn,"__esModule",{value:!0});Qn.FakeMediaStreamTrack=void 0;var Lc=Dc(),Qh=xc(),Xt=Ic(),Yn=Ac(),Ii=class r extends Qh.FakeEventTarget{#m;#l;#p;#e;#r;#t;#n;#h;#s;#f;#i;#o=null;#a=null;#c=null;#d=null;#u=null;constructor({kind:e,id:t,label:n,contentHint:s,enabled:i,muted:o,readyState:a,capabilities:c,constraints:u,settings:d,data:l}){super(),this.#m=t??(0,Lc.v4)(),this.#l=e,this.#p=n??"",this.#n=s??"",this.#r=i??!0,this.#t=o??!1,this.#e=a??"live",this.#h=c??{},this.#s=u??{},this.#f=d??{},this.#i=l??{}}get id(){return this.#m}get kind(){return this.#l}get label(){return this.#p}get contentHint(){return this.#n}set contentHint(e){this.#n=e}get enabled(){return this.#r}set enabled(e){let t=this.#r!==e;this.#r=e,t&&this.dispatchEvent(new Xt.FakeEvent("enabledchange"))}get muted(){return this.#t}get readyState(){return this.#e}get data(){return this.#i}set data(e){this.#i=e}get onmute(){return this.#o}set onmute(e){this.#o&&this.removeEventListener("mute",this.#o),this.#o=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#a}set onunmute(e){this.#a&&this.removeEventListener("unmute",this.#a),this.#a=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#c}set onended(e){this.#c&&this.removeEventListener("ended",this.#c),this.#c=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#d}set onenabledchange(e){this.#d&&this.removeEventListener("enabledchange",this.#d),this.#d=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#u}set onstopped(e){this.#u&&this.removeEventListener("stopped",this.#u),this.#u=e,e&&this.addEventListener("stopped",e)}addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}stop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new Xt.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new r({id:e??(0,Lc.v4)(),kind:this.#l,label:this.#p,contentHint:this.#n,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,Yn.clone)(this.#h),constraints:(0,Yn.clone)(this.#s),settings:(0,Yn.clone)(this.#f),data:t??(0,Yn.clone)(this.#i)})}getCapabilities(){return this.#h}getConstraints(){return this.#s}async applyConstraints(e={}){return this.#s=e,Promise.resolve()}getSettings(){return this.#f}remoteStop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new Xt.FakeEvent("stopped")),this.dispatchEvent(new Xt.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new Xt.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new Xt.FakeEvent("unmute")))}};Qn.FakeMediaStreamTrack=Ii});var Oc=D(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.FakeEventTarget=void 0;var Ai=class{listeners={};addEventListener(e,t,n){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof n=="object"&&n.once===!0}))}removeEventListener(e,t,n){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(s=>s.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let n of[...t]){try{n.callback.call(this,e)}catch(s){setTimeout(()=>{throw s},0)}n.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}};Jn.FakeEventTarget=Ai});var Fc=D(Zn=>{"use strict";Object.defineProperty(Zn,"__esModule",{value:!0});Zn.FakeHandler=void 0;var Jh=Mc(),Xh=pe(),Zh=se(),Zt=ct(),Li=Oe(),Nc=we(),ef=Oc(),Z=new Zh.Logger("FakeHandler"),Uc="FakeHandler",Mi=class r extends Xh.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${Zt.generateRandomNumber()}`;_defaultSendStreamId=`${Zt.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:Uc,factory:t=>new r(t,e),getNativeRtpCapabilities:async({direction:t})=>(Z.debug("getNativeRtpCapabilities() [direction:%o]",t),r.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(Z.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){let t=e.generateNativeRtpCapabilities();return Li.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),Z.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return Uc}close(){Z.debug("close()"),!this._closed&&(this._closed=!0,super.close())}setIceGatheringState(e){this.emit("@icegatheringstatechange",e)}setConnectionState(e){this.emit("@connectionstatechange",e)}async updateIceServers(e){this.assertNotClosed(),Z.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),Z.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:n,codecOptions:s,codec:i}){this.assertNotClosed(),Z.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});let o=r.getLocalRtpCapabilities(this._fakeParameters),a=this._getSendExtendedRtpCapabilities(o),c=Li.getSendingRtpParameters(e.kind,a);c.codecs=Li.reduceCodecs(c.codecs,i);let u=c.codecs.some(l=>/.+\/rtx$/i.test(l.mimeType));c.mid=`mid-${Zt.generateRandomNumber()}`,c.msid=`${t??"-"} ${e.id}`,n||(n=[{}]);for(let l of n)l.ssrc=Zt.generateRandomNumber(),u&&(l.rtx={ssrc:Zt.generateRandomNumber()});c.encodings=n,c.rtcp={cname:this._cname,reducedSize:!0,mux:!0},c.msid=`${t??this._defaultSendStreamId} ${e.id}`;let d=this._nextLocalId++;return this._tracks.set(d,e),{localId:String(d),rtpParameters:c}}async stopSending(e){if(Z.debug("stopSending() [localId:%s]",e),!this._closed){if(!this._tracks.has(Number(e)))throw new Error("local track not found");this._tracks.delete(Number(e))}}async pauseSending(e){this.assertNotClosed()}async resumeSending(e){this.assertNotClosed()}async replaceTrack(e,t){this.assertNotClosed(),t?Z.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Z.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),Z.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),Z.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),Z.debug("sendDataChannel()");let t=new Xn({id:this._nextSctpStreamId++,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:e.label,protocol:e.protocol}),n={streamId:this._nextSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits};return{dataChannel:t,sctpStreamParameters:n}}async receive(e){this.assertNotClosed();let t=[];for(let n of e){let{trackId:s,kind:i}=n;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),Z.debug("receive() [trackId:%s, kind:%s]",s,i);let o=this._nextLocalId++,a=new Jh.FakeMediaStreamTrack({kind:i});this._tracks.set(o,a),t.push({localId:String(o),track:a})}return t}async stopReceiving(e){if(!this._closed)for(let t of e)Z.debug("stopReceiving() [localId:%s]",t),this._tracks.delete(Number(t))}async pauseReceiving(e){this.assertNotClosed()}async resumeReceiving(e){this.assertNotClosed()}async getReceiverStats(e){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){return this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),Z.debug("receiveDataChannel()"),{dataChannel:new Xn({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:n})}}getDataChannelMaxMessageSize(){return 5e5}async setupTransport({localDtlsRole:e,localSdpObject:t}){let n=Zt.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(n.role=e),this.emit("@connectionstatechange","connecting"),await new Promise((s,i)=>this.emit("@connect",{dtlsParameters:n},s,i)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Nc.InvalidStateError("method called in a closed handler")}};Zn.FakeHandler=Mi;var Xn=class extends ef.FakeEventTarget{_id;_negotiated=!0;_ordered;_maxPacketLifeTime;_maxRetransmits;_label;_protocol;_readyState="connecting";_bufferedAmount=0;_bufferedAmountLowThreshold=0;_binaryType="arraybuffer";_onopen=null;_onclosing=null;_onclose=null;_onmessage=null;_onbufferedamountlow=null;_onerror=null;constructor({id:e,ordered:t=!0,maxPacketLifeTime:n=null,maxRetransmits:s=null,label:i="",protocol:o=""}){super(),Z.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${n}, maxRetransmits:${s}, label:${i}, protocol:${o}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=n,this._maxRetransmits=s,this._label=i,this._protocol=o}get id(){return this._id}get negotiated(){return this._negotiated}get ordered(){return this._ordered}get maxPacketLifeTime(){return this._maxPacketLifeTime}get maxRetransmits(){return this._maxRetransmits}get label(){return this._label}get protocol(){return this._protocol}get readyState(){return this._readyState}get bufferedAmount(){return this._bufferedAmount}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._bufferedAmountLowThreshold=e}get binaryType(){return this._binaryType}set binaryType(e){this._binaryType=e}get onopen(){return this._onopen}set onopen(e){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=e,e&&this.addEventListener("open",e)}get onclosing(){return this._onclosing}set onclosing(e){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=e,e&&this.addEventListener("closing",e)}get onclose(){return this._onclose}set onclose(e){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=e,e&&this.addEventListener("close",e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=e,e&&this.addEventListener("message",e)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(e){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=e,e&&this.addEventListener("bufferedamountlow",e)}get onerror(){return this._onerror}set onerror(e){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=e,e&&this.addEventListener("error",e)}addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(e){if(this._readyState!=="open")throw new Nc.InvalidStateError("not open")}}});var Wc=D(De=>{"use strict";Object.defineProperty(De,"__esModule",{value:!0});De.generateRouterRtpCapabilities=tf;De.generateNativeRtpCapabilities=rf;De.generateNativeSctpCapabilities=nf;De.generateLocalDtlsParameters=sf;De.generateTransportRemoteParameters=of;De.generateProducerRemoteParameters=af;De.generateConsumerRemoteParameters=cf;De.generateDataProducerRemoteParameters=df;De.generateDataConsumerRemoteParameters=uf;var oe=ct();function fe(){return String(oe.generateRandomNumber())}function tf(){return oe.deepFreeze({codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}},{mimeType:"video/H264",kind:"video",preferredPayloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:105,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"profile-id":0,"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:106,clockRate:9e4,rtcpFeedback:[],parameters:{apt:105}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",preferredId:2,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",preferredId:3,preferredEncrypt:!1,direction:"recvonly"},{kind:"audio",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:11,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:12,preferredEncrypt:!1,direction:"sendrecv"}]})}function rf(){return{codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:111,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{minptime:10,useinbandfec:1}},{mimeType:"audio/ISAC",kind:"audio",preferredPayloadType:103,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/CN",kind:"audio",preferredPayloadType:106,clockRate:32e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/foo",kind:"audio",preferredPayloadType:107,clockRate:9e4,channels:4,rtcpFeedback:[{type:"foo-qwe-qwe"}],parameters:{foo:"lalala"}},{mimeType:"video/BAZCODEC",kind:"video",preferredPayloadType:100,clockRate:9e4,rtcpFeedback:[{type:"foo"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[],parameters:{apt:100}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:96,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:97,clockRate:9e4,rtcpFeedback:[],parameters:{apt:96}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:98,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{"profile-id":0}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:99,clockRate:9e4,rtcpFeedback:[],parameters:{apt:98}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:2},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:3},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:4},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",preferredId:6},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",preferredId:7},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing",preferredId:8},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10}]}}function nf(){return oe.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function sf(){return oe.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"}],role:"auto"})}function of(){return{id:fe(),iceParameters:oe.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:oe.deepFreeze([{foundation:"udpcandidate",address:"9.9.9.9",ip:"9.9.9.9",port:40533,priority:1078862079,protocol:"udp",type:"host",tcpType:"passive"},{foundation:"udpcandidate",address:"9.9.9.9",ip:"9:9:9:9:9:9",port:41333,priority:1078862089,protocol:"udp",type:"host",tcpType:"passive"}]),dtlsParameters:oe.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"},{algorithm:"sha-384",value:"03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"},{algorithm:"sha-512",value:"84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"}],role:"auto"}),sctpParameters:oe.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function af(){return oe.deepFreeze({id:fe()})}function cf({id:r,codecMimeType:e}={}){switch(e){case"audio/opus":return{id:r??fe(),producerId:fe(),kind:"audio",rtpParameters:oe.deepFreeze({codecs:[{mimeType:"audio/opus",payloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}}],encodings:[{ssrc:46687003}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",id:10}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"audio/ISAC":return{id:r??fe(),producerId:fe(),kind:"audio",rtpParameters:oe.deepFreeze({codecs:[{mimeType:"audio/ISAC",payloadType:111,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}}],encodings:[{ssrc:46687004}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/VP8":return{id:r??fe(),producerId:fe(),kind:"video",rtpParameters:oe.deepFreeze({codecs:[{mimeType:"video/VP8",payloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",payloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}}],encodings:[{ssrc:99991111,rtx:{ssrc:99991112}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/H264":return{id:r??fe(),producerId:fe(),kind:"video",rtpParameters:oe.deepFreeze({codecs:[{mimeType:"video/H264",payloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",payloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}}],encodings:[{ssrc:99991113,rtx:{ssrc:99991114}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};default:throw new TypeError(`unknown codecMimeType '${e}'`)}}function df(){return oe.deepFreeze({id:fe()})}function uf({id:r}={}){return{id:r??fe(),dataProducerId:fe(),sctpStreamParameters:oe.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}});var mi=D(H=>{"use strict";Object.defineProperty(H,"__esModule",{value:!0});H.debug=H.testFakeParameters=H.FakeHandler=H.enhancedEvents=H.ortc=H.parseScalabilityMode=H.detectDeviceAsync=H.detectDevice=H.Device=H.version=H.types=void 0;var lf=xr();H.debug=lf.default;H.types=ua();H.version="3.20.0";var Oi=Ec();Object.defineProperty(H,"Device",{enumerable:!0,get:function(){return Oi.Device}});Object.defineProperty(H,"detectDevice",{enumerable:!0,get:function(){return Oi.detectDevice}});Object.defineProperty(H,"detectDeviceAsync",{enumerable:!0,get:function(){return Oi.detectDeviceAsync}});var pf=pt();Object.defineProperty(H,"parseScalabilityMode",{enumerable:!0,get:function(){return pf.parse}});H.ortc=Oe();H.enhancedEvents=pe();var hf=Fc();Object.defineProperty(H,"FakeHandler",{enumerable:!0,get:function(){return hf.FakeHandler}});H.testFakeParameters=Wc()});var qc=D((r_,Ui)=>{"use strict";var ff=Object.prototype.hasOwnProperty,ae="~";function zr(){}Object.create&&(zr.prototype=Object.create(null),new zr().__proto__||(ae=!1));function mf(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function jc(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new mf(t,n||r,s),o=ae?ae+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],i]:r._events[o].push(i):(r._events[o]=i,r._eventsCount++),r}function es(r,e){--r._eventsCount===0?r._events=new zr:delete r._events[e]}function ee(){this._events=new zr,this._eventsCount=0}ee.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)ff.call(t,n)&&e.push(ae?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};ee.prototype.listeners=function(e){var t=ae?ae+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=new Array(i);s<i;s++)o[s]=n[s].fn;return o};ee.prototype.listenerCount=function(e){var t=ae?ae+e:e,n=this._events[t];return n?n.fn?1:n.length:0};ee.prototype.emit=function(e,t,n,s,i,o){var a=ae?ae+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,d,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,s),!0;case 5:return c.fn.call(c.context,t,n,s,i),!0;case 6:return c.fn.call(c.context,t,n,s,i,o),!0}for(l=1,d=new Array(u-1);l<u;l++)d[l-1]=arguments[l];c.fn.apply(c.context,d)}else{var p=c.length,f;for(l=0;l<p;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,s);break;default:if(!d)for(f=1,d=new Array(u-1);f<u;f++)d[f-1]=arguments[f];c[l].fn.apply(c[l].context,d)}}return!0};ee.prototype.on=function(e,t,n){return jc(this,e,t,n,!1)};ee.prototype.once=function(e,t,n){return jc(this,e,t,n,!0)};ee.prototype.removeListener=function(e,t,n,s){var i=ae?ae+e:e;if(!this._events[i])return this;if(!t)return es(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!s||o.once)&&(!n||o.context===n)&&es(this,i);else{for(var a=0,c=[],u=o.length;a<u;a++)(o[a].fn!==t||s&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[i]=c.length===1?c[0]:c:es(this,i)}return this};ee.prototype.removeAllListeners=function(e){var t;return e?(t=ae?ae+e:e,this._events[t]&&es(this,t)):(this._events=new zr,this._eventsCount=0),this};ee.prototype.off=ee.prototype.removeListener;ee.prototype.addListener=ee.prototype.on;ee.prefixed=ae;ee.EventEmitter=ee;typeof Ui<"u"&&(Ui.exports=ee)});var Ym={};yo(Ym,{ACTIVATION_COLD_BOOT_AFTER_MS:()=>xo,ACTIVATION_DEGRADED_AFTER_MS:()=>Io,ACTIVATION_HINT_PATH:()=>an,ACTIVATION_STILL_AFTER_MS:()=>Do,ACTIVITY_DOM_EVENTS:()=>ps,ACTIVITY_FIELD:()=>Vi,ACTIVITY_STAMP_MIN_INTERVAL_MS:()=>Ed,ActivationMonitor:()=>Rt,App:()=>zd,BACKOFF_BASE_MS:()=>wr,BACKOFF_MAX_ATTEMPTS:()=>Ye,BACKOFF_MAX_MS:()=>Ct,CaptureController:()=>tn,CaptureUnavailableError:()=>en,ClientTokenError:()=>tt,CreditsClient:()=>Zr,CreditsError:()=>gt,CreditsUnauthorizedError:()=>mr,DATA_CHANNEL_MESSAGE_CEILING:()=>cu,DEFAULT_DOC_SYNC_TIMEOUT_MS:()=>uo,DEFAULT_GATEWAY_URL:()=>ho,DEFAULT_PRODUCE_ACK_TIMEOUT_MS:()=>Tt,DEFAULT_REFERENCE_JPEG_QUALITY:()=>au,DEFAULT_REFERENCE_MAX_SIZE:()=>ou,DEFAULT_WHEN_LIVE_TIMEOUT_MS:()=>Ds,DERIVED_LEG_SEP:()=>nr,DGRAM_HEADER_BYTES:()=>de,FOCUS_FIELD:()=>Ki,FOREGROUND_COALESCE_MS:()=>xd,FrameReassembler:()=>cr,GENERATION_TICK_EMIT_INTERVAL_MS:()=>Rd,GENERATION_TICK_MAX_EXTRAPOLATION_MS:()=>Cd,INPUT_PRESENCE_DEFAULT_HZ:()=>ru,INPUT_PRESENCE_FIELD:()=>_o,InvalidDurationError:()=>it,LEGACY_ACTIVATION_HINT_PATH:()=>cn,PLATFORM_DOC_NAME:()=>on,PermanentLockedError:()=>Dr,PinRequiresActiveTempError:()=>Pr,PresenceTracker:()=>ir,ProduceAckTimeoutError:()=>St,RecordingNotFoundError:()=>Cr,RecordingsClient:()=>ot,RecordingsError:()=>_e,RecordingsUnauthorizedError:()=>xt,RequestAbortError:()=>rt,RequestCancelledError:()=>kt,RequestDocSyncError:()=>yt,RequestError:()=>ke,RequestTimeoutError:()=>wt,RetainNotTempError:()=>Er,RuntimeArtifactNotFoundError:()=>Tr,RuntimeArtifactsClient:()=>Qe,RuntimeArtifactsError:()=>ne,RuntimeArtifactsUnauthorizedError:()=>kr,SIGNALING_PROTOCOL_VERSION:()=>Wi,STREAM_END:()=>mt,Session:()=>hr,SessionAllocationError:()=>z,SessionDirectory:()=>fr,SessionDirectoryError:()=>ge,SessionEndError:()=>re,SessionEndUnavailableError:()=>Ae,SessionFailedError:()=>Le,StreamDirectionConflict:()=>bt,TransportNegotiator:()=>ur,TransportSessionMismatchError:()=>nt,TransportSessionSignaling:()=>lr,URUN_DEV_ENV:()=>fo,USER_ACTIVITY_FIELD:()=>Gi,USER_ACTIVITY_MIN_INTERVAL_MS:()=>Dd,VISIBILITY_FIELD:()=>zi,WIRE_MESSAGE_BUDGET:()=>du,WT_CONTROL_FRAME_MAX:()=>Qi,WT_DATA_STREAM_VERSION:()=>Xi,WebRtcSession:()=>pr,WebTransportSession:()=>dr,WtControlDecoder:()=>or,WtDataStreamParser:()=>Jr,activationHintFrom:()=>xs,cameraCaptureAvailable:()=>hu,captureStillFromVideo:()=>fu,computeBackoffDelay:()=>Et,consumeWtDataStreams:()=>Ss,createActivityTracker:()=>hs,createCameraWarp:()=>mu,createClientToken:()=>Gd,createCreditsClient:()=>Zd,createInputPresencePublisher:()=>nu,createRecordingsClient:()=>Zo,createRuntimeArtifactsClient:()=>Jo,createStore:()=>Qd,decodeStreamEnvelope:()=>is,derivedLegName:()=>_d,derivedLegRole:()=>os,describeSessionFailure:()=>vr,describeSessionPhase:()=>Po,encodeStreamEnvelope:()=>Gr,encodeWtControlFrame:()=>ws,fitWithin:()=>Ps,isDurationString:()=>hn,isPausedPhase:()=>Eo,isPendingRecording:()=>Xd,isRetryableSessionError:()=>yr,isWakingPhase:()=>nn,mediaRecorderChunkSource:()=>_s,normalizeReferenceImage:()=>lu,normalizeRetention:()=>Xo,observeLeaveConfirm:()=>gs,observePageLifecycle:()=>fs,observePageTeardown:()=>ms,parseDgramHeader:()=>ar,prewake:()=>zo,referenceImageErrorMessage:()=>pu,releaseSessionBeacon:()=>Sr,sessionDirectory:()=>Vd,sessionFailureFromMediaError:()=>Ro,sharedCaptureController:()=>tu,videoStream:()=>Jd,watchGenerationTick:()=>ls,whenLive:()=>sn,writeDgramHeader:()=>bs});module.exports=So(Ym);var _t=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(e){this._ws=e,this._onMessage=t=>{if(typeof t.data!="string")return;let n;try{n=JSON.parse(t.data)}catch{console.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!n.channel)return;let s=this._handlers.get(n.channel);if(s)for(let i of s)i(n)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&this._handlers.delete(e)}}emit(e,t){if(this._disposed)return;let n=JSON.stringify({channel:e,...t});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(n);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(n),this.listenForOpen())}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1}flushPendingSends(){if(this._disposed||this._ws.readyState!==WebSocket.OPEN)return;this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1;let e=this._pendingSends;this._pendingSends=[];for(let t of e)this._ws.send(t)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},vt=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(e){if(this._disposed)return;this.detachTarget(),this._target=e;for(let[n,s]of this._handlers)for(let i of s)this._targetUnsubscribes.push(e.on(n,i));let t=this._pendingSends;this._pendingSends=[];for(let n of t)e.emit(n.channel,n.data)}rewriteSessionChannels(e,t){if(e===t)return;let n=`session:${e}:`,s=`session:${t}:`,i=new Map;for(let[o,a]of this._handlers)i.set(o.startsWith(n)?s+o.slice(n.length):o,a);this._handlers=i,this._pendingSends=this._pendingSends.map(o=>({...o,channel:o.channel.startsWith(n)?s+o.channel.slice(n.length):o.channel}))}on(e,t){if(this._disposed)return()=>{};let n=this._handlers.get(e);n||(n=new Set,this._handlers.set(e,n)),n.add(t);let s=this._target?.on(e,t);return s&&this._targetUnsubscribes.push(s),()=>{n?.delete(t),n?.size===0&&this._handlers.delete(e),s?.(),s&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(i=>i!==s))}}emit(e,t){if(!this._disposed){if(this._target){this._target.emit(e,t);return}this._pendingSends.push({channel:e,data:t})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let e of this._targetUnsubscribes)e();this._targetUnsubscribes=[],this._target=null}};var Ae=class extends Error{code="session_end_unavailable";constructor(e="[urun] this session handle cannot terminally end the session; disconnect the viewer instead",t){super(e),this.name="SessionEndUnavailableError",t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},re=class extends Error{code;httpStatus;requestId;sessionId;constructor(e,t){super(e),this.name="SessionEndError",this.code=t.code??"session_end_failed",this.httpStatus=t.httpStatus,this.requestId=t.requestId,this.sessionId=t.sessionId,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},ge=class extends Error{code;httpStatus;constructor(e,t){super(e),this.name="SessionDirectoryError",this.code=t?.code??"session_directory_failed",this.httpStatus=t?.httpStatus,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},ke=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},wt=class extends ke{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},yt=class extends ke{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},bt=class extends Error{stream;owner;attempted;constructor(e,t,n){super(`[urun] stream "${e}" is already produced by the ${t}; this (${n}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=n,Object.setPrototypeOf(this,new.target.prototype)}},Tt=15e3,St=class extends Error{kind;stream;timeoutMs;constructor(e,t){let n=t?.timeoutMs??Tt,s=t?.stream??e,i=s!==e?` "${s}"`:"";super(`[urun] SFU did not ack producer ${e}${i} within ${Math.round(n/1e3)}s \u2014 the server never replied to 'produce'. The runtime's inbound port for this stream is likely unadvertised (a cold or capacity-queued runtime), so the SFU has nothing to forward the track to; the published track never reached the runtime.`),this.name="ProduceAckTimeout",this.kind=e,this.stream=s,this.timeoutMs=n,Object.setPrototypeOf(this,new.target.prototype)}},rt=class extends ke{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},kt=class extends ke{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}},Su=/^\[urun\] (?:timed out waiting for session allocation at|session allocation poll failed at|session allocation failed at|session allocation at|session create at) \S+(?::[ \t]+|[ \t]+|$)/;function ku(r){return r.replace(/\bhttps?:\/\/[^\s)]+/g,"the session gateway")}function ko(r){let e=r.replace(Su,"");return ku(e||r.replace(/^\[urun\] /,""))}function To(r){let e=r.error?.httpStatus;if(e===401||e===403)return"The backend rejected this client \u2014 sign in again or check the auth token / org access.";if(r.error?.code==="session_archived")return"This session is archived \u2014 call directory.unarchive(sessionId) (the session directory's un-archive verb), then reconnect with the same id.";let t=r.error?.retryAfterSeconds,n=t!==void 0?` It asked for ${Math.round(t)}s.`:"";return e===429?`The backend is shedding load \u2014 its admission queue is full, so this is capacity, not your request.${n} The SDK already retried with backoff; try again in a moment.`:e===408?`The request timed out before the backend answered \u2014 that is a timeout, not a verdict on your request.${n} The SDK already retried with backoff; try again in a moment.`:e!==void 0&&e>=500?"The backend is having an outage (nothing is wrong with your request) \u2014 the SDK already retried with backoff, so try again shortly and report the status above if it persists.":"The backend could not create a session \u2014 check the app/function name and auth, then retry."}function vr(r,e){let t=e.error?.reason,n=e.elapsedMs!==void 0?Math.round(e.elapsedMs/1e3):void 0;switch(r){case"create-failed":{let s=e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:"",i=e.error?.code;return i==="queue_ttl_expired"||i==="stale_poll_expired"?{message:`[urun] the queued session REQUEST timed out while waiting${s} (${i}) \u2014 the session itself is untouched`,hint:"Nothing was lost and nothing needs replacing: connect again with the same session and the control plane re-admits the request (a poll that arrives in time re-drives it on its own)."}:i==="session_archived"?{message:`[urun] this session is archived${s} \u2014 un-archive it before resuming`+(t?`: ${ko(t)}`:""),hint:To(e)}:{message:`[urun] session create failed${s}${t?`: ${ko(t)}`:""}`,hint:To(e)}}case"never-live":{let s=n!==void 0?` after ${n}s`:"",i=` (last server status: ${e.lastServerStatus??"none"})`;return e.error?.code==="expired"?{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before media connected${s} \u2014 the control plane reclaims sessions whose media transport never establishes (~80s after create)`,hint:"Retry to mint a fresh session, and connect promptly after start (a backgrounded tab or paused debugger can miss the window)."}:e.sessionId?{message:`[urun] session ${e.sessionId} was created but never went live${s}${i} \u2014 the backend is busy or wedged (no runtime picked the session up)`,hint:"The backend is at capacity or stuck. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] no session went live${s} (phase=${e.phase}${e.lastServerStatus?`, last server status: ${e.lastServerStatus}`:""})`,hint:"The session never got past admission. Retry; if it persists, check the backend deployment."}}case"transport-failed":return e.error?.code==="transport-consumed"?{message:`[urun] the retry reused a session whose media transport was already connected${e.sessionId?` (id ${e.sessionId})`:""} \u2014 the session was consumed by an earlier attempt`,hint:"Start a fresh session (reload the page) \u2014 this session leg cannot be connected again."}:{message:`[urun] media/transport connection failed${t?`: ${t}`:""} (transport state: ${e.transportState})`,hint:"The network is likely blocking the media connection (WebRTC/WebSocket) \u2014 try a different network or disable VPN/proxy, then retry."};case"media-permission":return{message:`[urun] microphone/camera unavailable${t?`: ${t}`:""}`,hint:e.error?.code==="NotFoundError"||e.error?.code==="OverconstrainedError"?"No matching input device was found \u2014 connect or select a microphone/camera and retry.":"Allow microphone/camera access for this site (browser permission \u2014 or, when embedded, the parent page's permissions policy), then retry."};case"runtime-failed":return{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} failed at runtime${t?`: ${t}`:""}`,hint:"The session function crashed on the backend \u2014 check the app logs. The session itself is parked, not gone: attach to it again once the app is fixed."};case"produce-timeout":return{message:`[urun] publishing a track timed out${t?`: ${t}`:""} \u2014 the SFU never acked the produce (the runtime\u2019s inbound port for the stream was not advertised in time)`,hint:"The runtime was still cold or the backend was at capacity when the track was published. Retry in a moment; if it persists, the backend never opened the stream to receive it."};case"insufficient-credits":return{message:`[urun] session create refused${e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:""} \u2014 the org has insufficient credits${t?`: ${t}`:""}`,hint:"Out of credits \u2014 add credits to keep running sessions."}}}var Le=class extends Error{kind;status;hint;constructor(e,t,n){let{message:s,hint:i}=vr(e,t);super(s),this.name="SessionFailedError",this.kind=e,this.status=t,this.hint=i,n?.cause!==void 0&&(this.cause=n.cause),Object.setPrototypeOf(this,new.target.prototype)}};function Ro(r,e){if(r instanceof Le)return r;let t=r instanceof Error?r:new Error(String(r)),n={phase:e?.phase??"idle",transportState:e?.transportState??"disconnected",...e,error:{reason:t.message,code:t.name,kind:"media-permission"}};return new Le("media-permission",n,{cause:r})}var nt=class extends Error{code="transport_session_mismatch";connectedSessionId;requestedSessionId;constructor(e,t){super(`[urun] cannot retarget a connected transport to a different session: this leg is live on ${e??"(unknown)"} but setConnection() asked for ${t} \u2014 disconnect() this leg first (or use a fresh session handle)`),this.name="TransportSessionMismatchError",this.connectedSessionId=e,this.requestedSessionId=t,Object.setPrototypeOf(this,new.target.prototype)}},z=class extends Error{httpStatus;code;balanceCredits;platformStatus;retryAfterSeconds;constructor(e,t){super(e),this.name="SessionAllocationError",this.httpStatus=t?.httpStatus,this.code=t?.code,this.balanceCredits=t?.balanceCredits,this.platformStatus=t?.platformStatus,this.retryAfterSeconds=t?.retryAfterSeconds,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}};function nn(r){if(!r)return!1;let e=typeof r=="string"?r:r.name;return e==="queued"||e==="unavailable"||e==="provisioning"||e==="waiting_for_capacity"}function Eo(r){return r?(typeof r=="string"?r:r.name)==="paused":!1}var Ds=45e3,Co=6e5;function sn(r,e={}){let{timeout:t=Ds,signal:n}=e;return new Promise((s,i)=>{if(n?.aborted){i(n.reason instanceof Error?n.reason:new Error("whenLive aborted"));return}if(r.phase?.name==="live"){s();return}if(r.phase?.name==="error"){let v=r.phase,y=r.status??{phase:v.name,transportState:"disconnected",sessionId:v.sessionId,requestId:v.requestId,queue:v.queue,error:v.error,region:v.region};i(new Le(v.error?.kind??"transport-failed",y));return}let a,c,u=!1,d=v=>{u||(u=!0,c!==void 0&&clearTimeout(c),n?.removeEventListener("abort",l),a?.(),v?i(v):s())},l=()=>{d(n?.reason instanceof Error?n.reason:new Error("whenLive aborted"))};n?.addEventListener("abort",l,{once:!0});let p=()=>{let v=r.phase;return r.status??{phase:v?.name??"idle",transportState:"disconnected",sessionId:v?.sessionId,requestId:v?.requestId,queue:v?.queue,error:v?.error,region:v?.region}},f=v=>d(new Le(v,p())),h=Date.now(),m=t,g=()=>{if(m<=0)return;c!==void 0&&clearTimeout(c);let v=h+m-Date.now();c=setTimeout(()=>{let y=p();y.elapsedMs===void 0&&(y.elapsedMs=m),d(new Le("never-live",y))},Math.max(0,v))},_=v=>{u||m<=0||v?.runtime?.wake?.expectedWakePath==="cold-boot"&&(Co<=m||(m=Co,g()))};g(),a=r.onPhase(v=>{v?.name==="live"?d():v?.name==="error"?f(v.error?.kind??"transport-failed"):_(v)}),u||_(r.phase),u&&a()})}function Po(r){switch(r.name){case"idle":return"Initializing\u2026";case"unavailable":return"Starting the app\u2026";case"queued":return r.queue?`Waiting in queue (position ${r.queue.position} of ${r.queue.depth})\u2026`:r.runtime?.state==="busy"?"All runtimes are busy \u2014 waiting for capacity\u2026":"Waiting for capacity\u2026";case"provisioning":return r.runtime?.state==="starting"?"Starting model\u2026":"Provisioning\u2026";case"waiting_for_capacity":return r.queue?`Waiting for GPU capacity (position ${r.queue.position} of ${r.queue.depth})\u2026`:"Waiting for GPU capacity";case"connecting":return"Connecting\u2026";case"live":return"Live";case"paused":return Tu(r.reason);case"error":{if(r.error?.kind==="insufficient-credits")return"Out of credits \u2014 add credits to keep running sessions.";let e=r.error?.kind;if(e){let{message:t,hint:n}=vr(e,{phase:r.name,transportState:"disconnected",sessionId:r.sessionId,requestId:r.requestId,queue:r.queue,error:r.error});return`${t.replace(/^\[urun\] /,"")} \u2014 ${n}`}return r.error?.reason?`Session failed \u2014 ${r.error.reason}`:"Session failed"}case"unknown":return r.reason?`Session in an unrecognized state ("${r.reason}") \u2014 the client SDK may be out of date`:"Session in an unrecognized state \u2014 the client SDK may be out of date"}}function Tu(r){switch(r){case"client_ended":return"Paused \u2014 you hung up. Resume any time.";case"client_paused":return"Paused \u2014 you paused it. Resume any time.";case"client_detached":return"Paused \u2014 this device let go. Resume any time.";case"client_gone":return"Paused \u2014 every device disconnected. Resume any time.";case"session_ended":case"ended":case"closed":return"Paused \u2014 the compute was released. Resume any time.";case"idle_timeout":return"Paused \u2014 idle. Resume any time.";case"max_session_age":return"Paused \u2014 reached its maximum length. Resume any time.";case"credits_exhausted":return"Paused \u2014 out of credits. Add credits, then resume.";case"capacity_pressure":return"Paused \u2014 the GPU was reclaimed while the platform was under load. Resume any time.";case"control_plane_release":return"Paused \u2014 the platform reclaimed the compute. Resume any time.";case"superseded":return"Paused \u2014 another client attached. Resume any time.";case"superseded_by_redial":return"Paused \u2014 a newer connection from this session took over. Resume any time.";case"connect_deadline":return"Paused \u2014 the runtime never finished connecting in time. Resume to try again.";case"adoption_expired":return"Paused \u2014 the runtime was assigned but never picked the session up. Resume to try again.";case"media_lane_bind_failed":return"Paused \u2014 the audio/video lane could not be set up. Resume to try again.";case"lease_lost":return"Paused \u2014 the runtime stopped renewing its lease. Resume any time.";case"presence_unconfirmed":return"Paused \u2014 the platform could not confirm anyone was still attached. Resume any time.";case"runtime_inert":case"assignment_unconfirmable":return"Paused \u2014 the runtime never acknowledged its assignment. Resume to try again.";case"runtime_unreachable":return"Paused \u2014 the platform could not reach the runtime. Resume to try again.";case"runtime_silent":return"Paused \u2014 the runtime stopped sending audio/video. Resume to try again.";case"assignment_undelivered":return"Paused \u2014 the assignment never reached a runtime. Resume to try again.";case"dispatch_released":return"Paused \u2014 the worker finished and gave its GPU seat back. Resume any time.";case"dispatch_parked":return"Paused \u2014 the worker finished and parked the session. Resume any time.";case"runtime_swap_exhausted":return"Paused \u2014 the platform ran out of runtimes to try. Resume any time.";case"dispatch_failed":return"Paused \u2014 handing the session to a worker did not succeed. Resume to try again.";default:return r?`Paused \u2014 ${r}. Resume any time.`:"Paused \u2014 resume any time."}}var Do=15e3,xo=45e3,Io=12e4,on="platform",an="activation",cn="desired.activation";function xs(r){if(typeof r=="string"&&r.length>0)return r;if(r&&typeof r=="object"){let e=r.note;if(typeof e=="string"&&e.length>0)return e}}var Ru=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],Rt=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let n of this._watches.values())this._arm(n)}}else(t?.name==="error"||t?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let e of this._watches.values())if(!e.done){for(let t of e.timers)clearTimeout(t);e.timers=[],e.startedAt=null,e.lastEvent=null}}watch(e,t){if(this._stopped||this._watches.has(e))return;let n={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,n),this._hookFirstMediaSignals(n),!n.done&&this._liveAt!==null&&this._arm(n)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=n=>{if(!(!n||e.done)){if(n.muted===!0&&typeof n.addEventListener=="function"){let s=()=>this._firstMedia(e);n.addEventListener("unmute",s,{once:!0}),e.cleanups.push(()=>n.removeEventListener?.("unmute",s));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",n=>t(n))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of Ru){let n=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);n.unref?.(),e.timers.push(n)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,n){let s={state:t,elapsedMs:n,stream:e.name},i=xs(this._options.hint());i!==void 0&&(s.hint=i),e.lastEvent=s;for(let o of Array.from(this._handlers))o(s)}};var wr=500,Ct=15e3,Ye=6;function Et(r,e=Math.random){if(!Number.isFinite(r)||r<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${r}`);let t=Math.min(Ct,wr*2**r);return Math.round(e()*t)}function yr(r){if(r instanceof z){let e=r.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return r instanceof Error?r.name==="TypeError"||r.name==="TimeoutError"||r.name==="AbortError":!1}var Ao=10,Cu=.5,dn=Ao;function Is(){return dn<1?!1:(dn-=1,!0)}function As(){dn=Math.min(Ao,dn+Cu)}var Eu="session-api.prod.cloud.urun.sh",Pu=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function K(r){return r.trim().replace(/\/+$/,"")}function br(r,e){let t=[],n=s=>{if(!s)return;let i=K(s);i&&!t.includes(i)&&t.push(i)};n(r);for(let s of e??[])n(s);for(let s of rl(r))n(s);return t}function Sr(r){try{if(typeof fetch!="function")return;let e=K(r.baseUrl),t=r.sessionId?`${e}/api/sessions/${encodeURIComponent(r.sessionId)}/end`:`${e}/api/session-requests/${encodeURIComponent(r.requestId)}/cancel`;fetch(t,{method:"POST",headers:r.reason!==void 0?{...Re(r,r.jwt),"Content-Type":"application/json"}:Re(r,r.jwt),...r.reason!==void 0?{body:JSON.stringify({reason:r.reason})}:{},keepalive:!0}).catch(()=>{})}catch{}}async function Ls(r){try{let e=`${K(r.baseUrl)}/api/session-requests/${encodeURIComponent(r.requestId)}/cancel`,t=await Me(r);if(r.getAccessToken&&!t)throw new re("[urun] session request cancel refused: getAccessToken resolved no token (an unauthenticated cancel is never sent)",{requestId:r.requestId,code:"no_access_token"});let n=await fetch(e,{method:"POST",headers:Re(r,t),keepalive:!0});if((n.status===401||n.status===403)&&r.getAccessToken){let o=await Me(r,{forceRefresh:!0,reason:"unauthorized"});o&&o!==t&&(n=await fetch(e,{method:"POST",headers:Re(r,o),keepalive:!0}))}let s=await Dt(n);if(!n.ok)throw new re(`[urun] session request cancel failed: ${pn(s,n.status)}`,{requestId:r.requestId,code:s.error_code,httpStatus:n.status});let i=String(s.status??"");if(i==="cancelled"||i==="canceled"||i==="closed")return{status:"canceled",requestId:r.requestId};if(i==="failed"||i==="rejected"||i==="expired")return{status:"canceled",requestId:r.requestId,platformStatus:i};throw new re(`[urun] session request cancel returned an unrecognized request status ${JSON.stringify(i)} (recognized: cancelled/canceled, closed, failed, rejected, expired)`,{requestId:r.requestId,code:"invalid_release_response",httpStatus:n.status})}catch(e){throw e instanceof re?e:new re("[urun] session request cancel failed",{requestId:r.requestId,cause:e})}}async function Ms(r){let e;try{e=await Os(r,`/api/sessions/${encodeURIComponent(r.sessionId)}/end`,{method:"POST",keepalive:!0},"session end")}catch(s){if(s instanceof re)throw s;let i=s;throw new re(i?.message??"[urun] session end request failed",{sessionId:r.sessionId,...i?.code!==void 0?{code:i.code}:{},...i?.httpStatus!==void 0?{httpStatus:i.httpStatus}:{},cause:s})}let t=String(e.status??""),n=e.pause_reason;if(t==="paused")return{status:"paused",sessionId:String(e.logical_id??e.id??r.sessionId),reason:typeof n=="string"&&n.length>0?n:"client_ended"};throw new re(`[urun] session end returned ${JSON.stringify(t)} for session ${r.sessionId} \u2014 an end PARKS the session, so the only contract-valid answer is "paused" (a terminal word on this route would be a session-plane terminal write, which is forbidden)`,{sessionId:r.sessionId,code:"invalid_end_response"})}function Wo(r){if(typeof r!="string"||r.length===0)return null;let e=new Date(r);return Number.isFinite(e.getTime())?e:null}var Du=120,xu=1e3,Iu=20,Au=5,Lu=500,jo=1e4,Mu=new Set([502,503,504]),Ou=Ye,Uu=2,Nu=50,Lo=1e4;async function Mo(r,e){let t=Date.now()+Lo;for(;;){await Pt(Nu);let n=await Me(r);if(n)return n;if(Date.now()>=t)throw new z(`[urun] session allocation at ${e} never got an access token: the wired getAccessToken resolved nothing within ${Math.round(Lo/1e3)}s (no unauthenticated request was sent)`)}}function Fu(r,e){if(!r)return null;try{let t=new URL(r),n=e?new URL(K(e)):null,s=t.pathname==="/api/sessions/create"||t.pathname==="/api/sessions/create/";return t.protocol!=="https:"||!s||!$u(t,n)?null:K(t.origin)}catch{return null}}function Wu(r,e){if(!r||!r.trim())return{outcome:"absent"};if(!ju(e))return{outcome:"bootstrap-only"};let t=r.includes("://")?r:`https://${r}`,n;try{n=new URL(t)}catch{return{outcome:"rejected",reason:"not a parseable URL or host"}}return n.protocol!=="https:"?{outcome:"rejected",reason:`scheme ${n.protocol} is not https:`}:n.pathname!=="/"&&n.pathname!==""?{outcome:"rejected",reason:`expected a bare origin, got path ${n.pathname}`}:ln(n.hostname)?{outcome:"pinned",base:K(n.origin)}:{outcome:"rejected",reason:`host ${n.hostname} is outside the urun.sh trust set`}}function ju(r){if(!r)return!1;try{let e=new URL(K(r));return e.protocol==="https:"&&ln(e.hostname)}catch{return!1}}function qu(r){let e=K(r);try{return K(new URL(e).origin)}catch{return e}}function $u(r,e){return ln(r.hostname)&&(!e||ln(e.hostname))}function ln(r){let e=r.toLowerCase();return e==="urun.sh"||e.endsWith(".urun.sh")}function Bu(r){let e=r instanceof z?r.retryAfterSeconds:void 0;return e===void 0||!Number.isFinite(e)||e<=0?0:Math.min(e*1e3,Ct)}function qo(r,e){let t=Bu(e);return t>0?Math.max(r,Date.now()+t):r}async function $o(r){let e=br(r.baseUrl,r.fallbackUrls),t=null,n=0,s=e.length>1;for(let i=0;i<Ye;i++){for(let o of e)try{let a=await Hu(o,r,{pollAttempts:Du,retryAfterLimitMs:s?xu:void 0});return As(),a}catch(a){if(t=a instanceof Error?a:new Error(String(a)),n=qo(n,t),t instanceof Te||t instanceof st||Gu(t))throw t}if(!yr(t))break;if(i+1<Ye){if(!Is())break;await Pt(Math.max(Et(i),n-Date.now()))}}throw t??new Error("[urun] session allocation failed")}async function Hu(r,e,t){let n,s,i,o=qu(r),a=0,c=new Set,u=Date.now()+t.pollAttempts*jo;for(let d=0;d<t.pollAttempts;d++){s=i??await Me(e),i=void 0,e.getAccessToken&&!s&&(s=await Mo(e,o));let l=!!n,p=Date.now(),f;if(n){let y=0,S=0,w=b=>{let O=Math.min(Ct,wr*2**y),j=Math.max(Math.ceil(O/2),Et(y));return y+=1,Math.min(Math.max(b,j),Math.max(0,u-Date.now()))};for(;;){let b=u-Date.now();if(b<=0)throw un(o,!0);let O=Math.max(1,Math.min(Iu,Math.floor(b/1e3)));p=Date.now();try{f=await fetch(`${o}/api/session-requests/${encodeURIComponent(n)}?wait_s=${O}`,{headers:Re(e,s),redirect:"manual",signal:Zu((O+Au)*1e3)})}catch(F){if(S+=1,S>=Ou)throw new st(`[urun] session allocation poll failed at ${o} after ${S} consecutive transport failures`,{cause:F});let $=w(0);if($<=0)throw un(o,!0);await Pt($);continue}if(S=0,!Mu.has(f.status))break;try{await f.body?.cancel()}catch(F){throw new st(`[urun] session allocation poll response cleanup failed at ${o}`,{cause:F})}let j=w(No(f,{},t.retryAfterLimitMs));if(j<=0)throw un(o,!0);await Pt(j)}}else f=await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...Re(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(Vu(e))});if(f.type==="opaqueredirect"||f.status>=300&&f.status<400){try{await f.body?.cancel()}catch{}throw new Te(`[urun] ${l?"session poll":"session create"} at ${o} answered an HTTP redirect (status ${f.status}) \u2014 browsers cannot follow a cross-origin redirect with credentials; the control plane must emit the JSON redirect envelope ({status:"redirect", location})`)}let h=await Dt(f);if(!n&&h.status==="redirect"){let y=Fu(h.location,o);if(!y)throw new z(`[urun] session create at ${o} answered a redirect envelope without a usable location (${JSON.stringify(h.location??null)}) \u2014 refusing to re-issue an authenticated create to an untrusted target`);if(y===o)throw new z(`[urun] session create at ${o} redirected to ITSELF \u2014 control-plane region apex map misconfiguration`);if(a>=Uu)throw new z(`[urun] session create followed ${a} region redirects and was redirected AGAIN (${o} -> ${y}) \u2014 region forward loop, giving up loudly`);a+=1,o=y;continue}if(h.request_id)try{e.onRequest?.({requestId:h.request_id,baseUrl:o,...h.session_id?{sessionId:h.session_id}:{}})}catch{}if(f.ok&&(h.status==="allocated"||!h.status&&!!h.session_id)&&!!h.session_id){let y=h.session_id,S=Wu(h.session_api_base,o);if(S.outcome==="rejected")throw new Te(`[urun] gateway allocated session ${h.session_id} with an unusable session_api_base (${JSON.stringify(h.session_api_base)}): ${S.reason} \u2014 refusing to pin the session to a region it may not belong to`);if(S.outcome==="pinned"&&S.base!==o&&(o=S.base,h.request_id))try{e.onRequest?.({requestId:h.request_id,baseUrl:o,...h.session_id?{sessionId:h.session_id}:{}})}catch{}let w=Ko(h.ws_url,o,y,"gateway allocated session");return{baseUrl:o,sessionId:y,wsUrl:w,endsAt:Wo(h.ends_at),response:h}}if(f.status===202||h.status==="pending"||h.status==="queued"||h.queued){if(n=h.request_id||n,!n)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(Xu(h,n))}catch{}let y=Date.now()-p<Lu;l&&y&&await Pt(No(f,h,t.retryAfterLimitMs));continue}if((f.status===401||f.status===403)&&e.getAccessToken&&h.error_code!=="session_name_not_yours"){let y=s??"";c.add(y);let S=await Me(e,{forceRefresh:!0,reason:"unauthorized"});if(S&&!c.has(S)){i=S;continue}if(S===void 0){let w=await Mo(e,o);if(!c.has(w)){i=w;continue}}}let g=pn(h,f.status),_=h.error_code??(f.status===402?"insufficient_credits":void 0),v=l?st:z;throw new v(`[urun] session allocation failed at ${o}: ${g}`,{httpStatus:f.status,code:_,balanceCredits:typeof h.balance_credits=="number"?h.balance_credits:void 0,platformStatus:h.status,retryAfterSeconds:Fs(f,h)})}throw un(o,!!n)}function un(r,e=!1){let t=e?st:z;return new t(`[urun] timed out waiting for session allocation at ${r}`)}function Re(r,e){let t={"X-Tenant-Id":r.orgId,"X-Auth-Provider":r.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function Me(r,e){return r.getAccessToken?await r.getAccessToken(e)??void 0:r.jwt}function Vu(r){let e=r.priority==="preempt";return{app:r.app,function:r.functionName,gpus:1,idempotency_key:r.idempotencyKey,...r.sessionKey&&!e?{logical_id:r.sessionKey}:{},...r.label&&!r.sessionKey?{label:r.label}:{},...e?{priority:"preempt"}:{}}}async function Os(r,e,t,n){let s=await Me(r);if(r.getAccessToken&&!s)throw new ge(`[urun] ${n} refused: getAccessToken resolved no token (an unauthenticated request is never sent)`,{code:"no_access_token"});let i=br(r.baseUrl,r.fallbackUrls),o;for(let a of i){let c=`${K(a)}${e}`,u=p=>fetch(c,{method:t.method,headers:t.body!==void 0?{...Re(r,p),"Content-Type":"application/json"}:Re(r,p),...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...t.keepalive?{keepalive:!0}:{}}),d;try{if(d=await u(s),(d.status===401||d.status===403)&&r.getAccessToken){let p=await Me(r,{forceRefresh:!0,reason:"unauthorized"});p&&p!==s&&(d=await u(p))}}catch(p){o=p;continue}let l=await Dt(d);if(!d.ok)throw new ge(`[urun] ${n} failed: ${pn(l,d.status)}`,{code:l.error_code,httpStatus:d.status});return l}throw new ge(`[urun] ${n} request failed`,{cause:o})}async function Bo(r){let e=new URLSearchParams;r.app&&e.set("app",r.app),r.functionName&&e.set("function",r.functionName),r.includeArchived&&e.set("include_archived","true"),r.limit!==void 0&&e.set("limit",String(r.limit)),r.cursor&&e.set("cursor",r.cursor);let t=e.toString(),n=await Os(r,`/api/sessions${t?`?${t}`:""}`,{method:"GET"},"session list");if(!Array.isArray(n?.sessions))throw new ge("[urun] session list returned no `sessions` array \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_response"});return{rows:n.sessions,nextCursor:n.next_cursor??null}}async function Us(r){let e=r.archived?"archive":"unarchive";await Os(r,`/api/sessions/${encodeURIComponent(r.sessionId)}/${e}`,{method:"POST"},`session ${e}`)}async function Ho(r){await Ms(r)}async function Vo(r){let e=br(r.baseUrl,r.fallbackUrls),t=null,n=0;for(let s=0;s<Ye;s++){for(let i of e)try{let o={baseUrl:i,app:"",functionName:"",orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider,idempotencyKey:""},a=`${K(i)}/api/sessions/${encodeURIComponent(r.sessionId)}/viewer-connect`,c=await Me(o);if(r.getAccessToken&&!c)throw new z(`[urun] viewer-connect for ${r.sessionId} refused: getAccessToken resolved no token (an unauthenticated viewer-connect is never sent)`);let u=await fetch(a,{headers:Re(o,c)});if((u.status===401||u.status===403)&&r.getAccessToken){let p=await Me(o,{forceRefresh:!0,reason:"unauthorized"});p&&p!==c&&(u=await fetch(a,{headers:Re(o,p)}))}if(!u.ok){let p=await Dt(u);throw new z(`[urun] viewer-connect for ${r.sessionId} failed: `+pn(p,u.status),{httpStatus:u.status,retryAfterSeconds:Fs(u,p)})}let d=await Dt(u),l=Ko(d.ws_url,i,r.sessionId,"viewer-connect");return As(),{baseUrl:K(i),sessionId:r.sessionId,wsUrl:l,endsAt:Wo(d.ends_at),response:d}}catch(o){if(t=o instanceof Error?o:new Error(String(o)),n=qo(n,t),t instanceof Te)throw t}if(!yr(t))break;if(s+1<Ye){if(!Is())break;await Pt(Math.max(Et(s),n-Date.now()))}}throw t??new Error("[urun] viewer-connect failed")}async function zo(r){try{let e=K(r.baseUrl),t=await Me(r);if(r.getAccessToken&&!t)return{status:"unavailable"};let n=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...Re(r,t),"Content-Type":"application/json"},body:JSON.stringify({app:r.app,function:r.functionName})});if(n.status===404)return{status:"unknown-app"};if(!n.ok)return{status:"unavailable"};let s=await Dt(n),i={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(i.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(i.warmCapable=s.warm_capable),i}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function Dt(r){try{let e=await r.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function pn(r,e){let t=r.error_code,n=r.error_message||r.message||r.error,s=t&&n&&n!==t?`${t}: ${n}`:n||t;return s?`${s} (HTTP ${e})`:`HTTP ${e}`}var zu=new Set([400,402,409]);function Gu(r){return r instanceof z&&r.httpStatus!==void 0&&zu.has(r.httpStatus)}var Ku=new Set(["capture-attested","no-portable-golden","portable-golden-release-mismatch","portable-golden-attestation-invalid"]);function Go(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Oo(r){return typeof r=="string"&&r.trim().length>0}function Uo(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Yu(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0}function Qu(r){if(Go(r)&&!(!Oo(r.snapshot_id)||!Oo(r.snapshot_compat_key)||!Uo(r.artifact_size_bytes)||!Uo(r.durable_arena_bytes)||r.volatile_arena_bytes!==0||!Yu(r.uncovered_weight_bytes)))return{snapshotId:r.snapshot_id,snapshotCompatKey:r.snapshot_compat_key,artifactSizeBytes:r.artifact_size_bytes,durableArenaBytes:r.durable_arena_bytes,volatileArenaBytes:0,uncoveredWeightBytes:r.uncovered_weight_bytes}}function Ju(r){if(!Go(r)||r.schema!=="urun.runtime.wake.v1"||r.portability!=="portable"&&r.portability!=="none"||r.expected_wake_path!=="portable-golden-restore"&&r.expected_wake_path!=="cold-boot"||typeof r.reason_code!="string"||!Ku.has(r.reason_code)||r.expectation_basis!=="snapshot-registry"||r.restore_observation!=="not-observed")return;let e=r.reason_code;if(r.portability==="portable"&&r.expected_wake_path==="portable-golden-restore"&&e==="capture-attested"){let t=Qu(r.golden);return t?{schema:"urun.runtime.wake.v1",portability:"portable",expectedWakePath:"portable-golden-restore",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed",golden:t}:void 0}if(r.portability==="none"&&r.expected_wake_path==="cold-boot"&&e!=="capture-attested"&&r.golden===void 0)return{schema:"urun.runtime.wake.v1",portability:"none",expectedWakePath:"cold-boot",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed"}}function Ns(r){if("serving_region"in r)return typeof r.serving_region=="string"&&r.serving_region.length>0?r.serving_region:null}function Xu(r,e){let n={status:typeof r.status=="string"&&r.status.length>0?r.status:r.queued?"queued":"pending",requestId:e},s=Ns(r);s!==void 0&&(n.region=s),typeof r.reason=="string"&&r.reason.length>0&&(n.reason=r.reason),typeof r.decision_reason=="string"&&r.decision_reason.length>0&&(n.decisionReason=r.decision_reason),typeof r.provisioning_refusal_source=="string"&&r.provisioning_refusal_source.length>0&&(n.refusalSource=r.provisioning_refusal_source),typeof r.provisioning_refusal_message=="string"&&r.provisioning_refusal_message.length>0&&(n.refusalMessage=r.provisioning_refusal_message),typeof r.queue_position=="number"&&typeof r.queue_depth=="number"&&(n.queue={position:r.queue_position,depth:r.queue_depth});let i=r.runtime_state;if(i==="unavailable"||i==="starting"||i==="busy"){n.runtime={state:i},typeof r.runtime_reason=="string"&&r.runtime_reason.length>0&&(n.runtime.reason=r.runtime_reason);let o=Ju(r.runtime_wake);o&&(n.runtime.wake=o)}return n}function Fs(r,e){let t=Number(r.headers.get("Retry-After")||""),n=Number(e.retry_after_seconds??t);return Number.isFinite(n)&&n>0?n:void 0}function No(r,e,t){let n=Fs(r,e),s=t??jo;return n!==void 0?Math.min(n*1e3,s):1e3}function Pt(r){return new Promise(e=>setTimeout(e,r))}function Zu(r){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(r):void 0}var Te=class extends Error{},st=class extends z{};function Ko(r,e,t,n){if(!r)throw new Te(`[urun] ${n} ${t} without ws_url`);let s,i;try{s=new URL(r)}catch{throw new Te(n==="viewer-connect"?`[urun] viewer-connect returned no usable ws_url for ${t}`:`[urun] ${n} ${t} with non-absolute ws_url`)}try{i=new URL(K(e))}catch{throw new Te(`[urun] ${n} ${t} has invalid gateway base URL`)}let o=el(i.hostname)&&i.protocol==="http:";if(!(o&&s.protocol==="ws:"||s.protocol==="wss:"))throw new Te(`[urun] ${n} ${t} with insecure ws_url`);if(!tl(s,i,o))throw new Te(`[urun] ${n} ${t} with cross-origin ws_url`);return s.toString()}function el(r){return r==="localhost"||r==="127.0.0.1"||r==="::1"||r.endsWith(".localhost")}function tl(r,e,t){return!!(t||r.hostname===e.hostname&&r.port===e.port||Fo(r.hostname)&&Fo(e.hostname))}function Fo(r){return r==="urun.sh"||r.endsWith(".urun.sh")}function rl(r){try{return new URL(r).hostname!==Eu?[]:Pu}catch{return[]}}var ne=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},kr=class extends ne{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Tr=class extends ne{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function Rr(r){return{baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}function Jo(r){return new Qe(r)}var Qe=class{_options;constructor(e){this._options=e}async list(e){let n=Qo(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new ne("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map(Yo)}async getDownloadUrl(e,t){let n=Qo(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=n.download_url;if(typeof s!="string"||!sl(s))throw new ne("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Yo(n.artifact),downloadUrl:s}}async _request(e,t){let n=br(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of n)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof ne&&il(s.status))throw s}throw s??new ne("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let s=`${K(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:c}=await this._readError(o,e);throw ol(o.status,a,c)}try{return await o.json()}catch(a){throw new ne(`[urun] runtime artifacts: invalid JSON response from ${K(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let n=K(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${n}: ${a}`:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}};function Yo(r){if(!r||typeof r!="object")throw new ne("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=r,t=qe(e,"artifact_id")||qe(e,"id"),n=qe(e,"filename"),s=qe(e,"kind"),i=qe(e,"status")||"ready",o=nl(e,"size_bytes"),a=qe(e,"sha256");if(!t||!n||!s||o==null||!a)throw new ne("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:n,contentType:qe(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:qe(e,"created_at"),expiresAt:qe(e,"expires_at")}}function qe(r,e){let t=r[e];return typeof t=="string"&&t.length>0?t:void 0}function nl(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function sl(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function il(r){return r===401||r===403}function ol(r,e,t){return r===401?new kr(t,e):r===404?new Tr(t,e):new ne(t,r,e)}function Qo(r){if(!r||typeof r!="object"||Array.isArray(r))throw new ne("[urun] runtime artifacts: malformed response",0,"bad_response");return r}var _e=class extends Error{status;code;constructor(e,t){super(e),this.name="RecordingsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},xt=class extends _e{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Cr=class extends _e{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Er=class extends _e{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},Pr=class extends _e{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},Dr=class extends _e{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},it=class extends _e{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function hn(r){return/^(\d+[smhdw])+$/.test(r)}function Xo(r){if(r==="pin")return{action:"pin"};if(hn(r))return{action:"retain",duration:r};throw new it(`[urun] recordings: "${r}" is not a duration or "pin"`)}function al(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new xt(n,e??"unauthorized");if(r===404)return new Cr(n,e??"not_found");if(r===400)return new it(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new Er(n,e);case"pin_requires_active_temp":return new Pr(n,e);case"permanent_locked":return new Dr(n,e)}return new _e(n,{status:r,code:e??`http_${r}`})}var ot=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!hn(t))throw new it(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new _e("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let s=this._buildUrl(t,n.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,n.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,n.body))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw al(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(n+=`?${s}`),n}_fetch(e,t,n,s){let i={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new xt("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:s,message:i}=n;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Zo(r){return new ot(r)}var gd=Ke(mi());var Ni=Ke(qc(),1);function et(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function Bc(){return et()?"Chrome111":void 0}var gf=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],ts=null,Hc=null;function Vc(){return typeof globalThis.RTCPeerConnection<"u"?null:Hc??"the WebRTC peer globals (RTCPeerConnection) are not installed in this runtime"}function er(){return et()?ts||(ts=_f(),ts):Promise.resolve()}async function _f(){let r=globalThis;if(typeof r.WebSocket>"u")try{let e=await import("ws"),t=e.default??e;r.WebSocket=t}catch(e){$c("WebSocket",e)}if(typeof r.RTCPeerConnection>"u")try{let e=await import("werift");vf(r,e)}catch(e){Hc=$c("werift",e)}}function vf(r,e){let{RTCPeerConnection:t,useH264:n,useVP8:s,useOPUS:i,useSdesMid:o,useSdesRTPStreamId:a,useAbsSendTime:c,useTransportWideCC:u,useVideoOrientation:d}=e,l=()=>({video:[n(),s()],audio:[i()]}),p=()=>({video:[o(),a(),c(),u(),d()],audio:[o(),c(),u()]});class f extends t{constructor(m){super({...m,codecs:m?.codecs??l(),headerExtensions:m?.headerExtensions??p()})}}r.RTCPeerConnection=f;for(let h of gf)e[h]!=null&&typeof r[h]>"u"&&(r[h]=e[h])}function $c(r,e){let t=e instanceof Error?e.message:String(e),n=`optional dependency "${r}" unavailable (${t})`;return console.warn(`[urun-sh/core] Node WebRTC support: ${n}. Realtime media will not work in this Node process; install "${r}" to enable it. Doc/KV transport over WebSocket is unaffected.`),n}var zc="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function wf(r){let e=globalThis.crypto,t=new Uint8Array(r);if(e?.getRandomValues)return e.getRandomValues(t),t;for(let n=0;n<r;n++)t[n]=Math.floor(Math.random()*256);return t}function tr(r=16){let e=wf(r),t="";for(let n=0;n<r;n++)t+=zc[e[n]%zc.length];return t}function Kc(r){return`stream:${r}`}var Yc="urun-stream-v1";var Fi=1,ce={BINARY:0,TEXT:1,JSON:2,END:3,CHUNK:4},rr=2,Gc=253952,yf=[ce.BINARY,ce.TEXT,ce.JSON],mt=Symbol("urun:stream:end");function Gr(r){if(r===mt)return Uint8Array.from([Fi,ce.END]);let{kind:e,body:t}=Qc(r);return rs(e,t)}function Qc(r){return r instanceof Uint8Array?{kind:ce.BINARY,body:r}:r instanceof ArrayBuffer?{kind:ce.BINARY,body:new Uint8Array(r)}:typeof r=="string"?{kind:ce.TEXT,body:new TextEncoder().encode(r)}:{kind:ce.JSON,body:new TextEncoder().encode(JSON.stringify(r))}}function rs(r,e){let t=new Uint8Array(rr+e.length);return t[0]=Fi,t[1]=r,t.set(e,rr),t}function Jc(r){if(r===mt)return[Gr(r)];let{kind:e,body:t}=Qc(r);if(t.length+rr<=Gc)return[rs(e,t)];let n=Gc-rr,s=[],i=0;for(;t.length-i>n;)s.push(rs(ce.CHUNK,t.subarray(i,i+n))),i+=n;return s.push(rs(e,t.subarray(i))),s}function is(r){let{kind:e,body:t}=Xc(r);if(e===ce.CHUNK)throw new Error("[urun] CHUNK envelope requires StreamFragmentReassembler (oversized payload)");return ns(e,t)}function Xc(r){let e=r instanceof Uint8Array?r:new Uint8Array(r);if(e.length<rr||e[0]!==Fi)throw new Error(`[urun] bad stream envelope (version=${e[0]}, len=${e.length})`);return{kind:e[1],body:e.subarray(rr)}}function ns(r,e){switch(r){case ce.BINARY:return e.slice();case ce.TEXT:return new TextDecoder().decode(e);case ce.JSON:return JSON.parse(new TextDecoder().decode(e));case ce.END:return mt;default:throw new Error(`[urun] unknown stream envelope KIND 0x${r.toString(16)}`)}}var ss=class{_chunks=[];_bufferedLength=0;feed(e){let{kind:t,body:n}=Xc(e);if(t===ce.CHUNK){this._chunks.push(n.slice()),this._bufferedLength+=n.length;return}if(yf.includes(t)){if(this._chunks.length===0)return ns(t,n);let s=new Uint8Array(this._bufferedLength+n.length),i=0;for(let o of this._chunks)s.set(o,i),i+=o.length;return s.set(n,i),this._chunks=[],this._bufferedLength=0,ns(t,s)}if(this._chunks.length>0)throw this._chunks=[],this._bufferedLength=0,new Error(`[urun] stream envelope KIND 0x${t.toString(16)} arrived mid-fragment-sequence; discarding partial payload`);return ns(t,n)}};function Zc(r){return{get consumerId(){return r.consumerId},onData(e,t){return r.onStreamData(e,t)},sendData(e,t,n){return r.sendStreamData(e,t,n)}}}var ed=[1e3,2e3,4e3,8e3,3e4],td=5,bf=15e3,Sf=15e3,rd=15e3,nd=15e3,kf=2e3,Tf=6e3,Rf=2e3,Cf=300,sd=4e3,Ef=2,Pf=750,Df=3,id=[1e3,2e3,4e3],xf=15e3;var nr="--",If=["video","audio"];function os(r){let e=r.lastIndexOf(nr);if(e<=0)return;let t=r.slice(e+nr.length);return If.includes(t)?t:void 0}function _d(r,e){return`${r}${nr}${e}`}var Wi="v1";function Af(r,e){return r.name!==e.name||r.reason!==e.reason||r.sessionId!==e.sessionId||r.requestId!==e.requestId||r.wakingSince!==e.wakingSince||r.region!==e.region||(r.endsAt?.getTime()??null)!==(e.endsAt?.getTime()??null)||r.queue?.position!==e.queue?.position||r.queue?.depth!==e.queue?.depth||r.runtime?.state!==e.runtime?.state||r.runtime?.reason!==e.runtime?.reason||r.runtime?.wake!==e.runtime?.wake?!1:r.error?.reason===e.error?.reason&&r.error?.code===e.error?.code&&r.error?.kind===e.error?.kind&&r.error?.httpStatus===e.error?.httpStatus&&r.error?.retryAfterSeconds===e.error?.retryAfterSeconds}var od={requested:"provisioning",queued:"queued",pending:"provisioning",allocating:"provisioning",provisioning:"provisioning",waking:"provisioning",waiting_for_capacity:"waiting_for_capacity",allocated:"connecting",connecting:"connecting",establishing:"connecting",live:"live",running:"live",paused:"paused",error:"error",failed:"error",rejected:"error",expired:"paused",cancelled:"paused",canceled:"paused",closed:"paused",releasing:"paused",released:"paused",reaped:"paused",superseded:"paused"};function ad(r){return Object.prototype.hasOwnProperty.call(od,r)?{phase:od[r],unknown:!1}:{phase:"unknown",unknown:!0}}function Lf(r){return r==="queued"||r==="pending"}function cd(r){return r==="credits_exhausted"}var dd=3,ud=4e3,ld=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}];function pd(r){if(!r)return;let e=/\/(?:ws\/)?rtc\/([^/?#]+)/.exec(r);if(e)try{return decodeURIComponent(e[1])}catch{return e[1]}}var sr=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new Ni.default;_ws=null;_connectedUrl=null;_device=null;_mediaUnavailableReason=null;_mediaVerdictResolve;_mediaVerdict=new Promise(e=>{this._mediaVerdictResolve=e});_recvTransport=null;_sendTransport=null;_consumers=new Map;_audioProducer=null;_videoProducer=null;_publishedAudio=null;_publishedVideo=null;_wtMicUplink=null;_wtCamUplink=null;_wtDataUpSender=null;_pendingProduce=null;_multiplexer=null;_reconnectAttempts=0;_intentionalDisconnect=!1;_reconnectTimer=null;_cancelPendingDial=null;_stableResetTimer=null;_generation=0;_lastStartOptions;_resolveConnection=null;_recvIceRestartAttempts=0;_recvIceRestartTimer=null;_sendIceRestartAttempts=0;_sendIceRestartTimer=null;_phase={name:"idle"};_requestId;_liveReached=!1;_lastServerStatus;_endsAt=null;_forceResolveOnNextConnect=!1;_connectStartedAt;_wakingSince;_mediaProbeTimer=null;_statsTimer=null;_statsSampleInFlight=!1;_joinProbes=new Map;_decodeDeathHandled=!1;_selectedCandidatePair=wd();_reportedCandidatePairKey=null;_candidatePairRefreshSeq=0;_diagnosticSinkFailed=!1;_currentEpoch=0;_selfEpochAdoptUntil=0;_pausedIncarnation=null;_consumerId=null;_streamDataHandlers=new Map;_streamDataLane="sctp";_dataProducers=new Map;_dataProducerPromises=new Map;_dataConsumers=new Map;_pendingDataProduce=new Map;_sendTransportWaiters=[];get consumerId(){return this._consumerId===null&&(this._consumerId=Mf()),this._consumerId}get state(){return this._state}get currentIncarnation(){return this._currentEpoch}get phase(){return this._phase}get isProducingMedia(){let e=n=>n!==null&&!n.closed&&!n.paused,t=(n,s)=>n!==null&&s!==null&&s.track.readyState!=="ended"&&n.deliveredDatagrams()>0;return e(this._audioProducer)||e(this._videoProducer)||t(this._wtMicUplink,this._publishedAudio)||t(this._wtCamUplink,this._publishedVideo)}get endsAt(){return this._endsAt}setEndsAt(e){this._endsAt=e}seedRegion(e){e!==void 0&&this._setPhase(this._phase.name,{reason:this._phase.reason,queue:this._phase.queue,runtime:this._phase.runtime,error:this._phase.error,region:e})}_pastDeadline(){return this._endsAt!==null&&Date.now()>=this._endsAt.getTime()}get status(){let e={phase:this._phase.name,transportState:this._state};return this._sessionId&&(e.sessionId=this._sessionId),this._requestId&&(e.requestId=this._requestId),this._lastServerStatus!==void 0&&(e.lastServerStatus=this._lastServerStatus),this._connectStartedAt!==void 0&&(e.elapsedMs=Date.now()-this._connectStartedAt),this._endsAt!==null&&(e.endsAt=this._endsAt),this._phase.queue&&(e.queue=this._phase.queue),this._phase.runtime&&(e.runtime=this._phase.runtime),this._phase.wakingSince!==void 0&&(e.wakingSince=this._phase.wakingSince),this._phase.error&&(e.error=this._phase.error),this._phase.region!==void 0&&(e.region=this._phase.region),e}get region(){return this._phase.region}get sessionId(){return this._sessionId}get tracks(){return this._tracks}get multiplexer(){return this._multiplexer}get isOpen(){return this._ws!==null&&this._ws.readyState===WebSocket.OPEN}get connectedUrl(){return this._connectedUrl}get intentionalDisconnect(){return this._intentionalDisconnect}getTrackByName(e){if(os(e)!==void 0)return;let t=this._tracksByName.get(e);if(t&&t.readyState!=="ended")return t;for(let n of this._tracks.values())if(!(n.kind!==e||n.readyState==="ended")&&this._streamNameOf(n)===void 0)return n;return t}_streamNameOf(e){for(let[t,n]of this._tracksByName)if(n===e)return t}setAuth(e){this._options={...this._options,...e},this.isOpen&&this._send({type:"auth",orgId:this._options.orgId,jwt:this._options.jwt,authProvider:this._options.authProvider})}constructor(e){this._options=e??{url:""},e?.sessionId&&(this._sessionId=e.sessionId)}setConnection(e){if(this.isOpen){let t=pd(e.url);if(e.sessionId!==void 0&&e.sessionId!==this._sessionId)throw new nt(this._sessionId,e.sessionId);if(t!==void 0&&t!==this._sessionId)throw new nt(this._sessionId,t);this._options={...this._options,...e};return}this._options={...this._options,...e},e.sessionId&&(this._sessionId=e.sessionId)}setConnectionResolver(e){this._resolveConnection=e}applyControlDocState(e){let t=e&&typeof e=="object"?e.session:void 0,n=jf(t);if(n!==void 0&&this.setIncarnation(n),!t||typeof t!="object")return;let s=t,i=typeof s.status=="string"?s.status:void 0;if(i&&!this.isStaleClosedMarker(s)){if(i==="error"){let o=s.error_reason??s.errorReason,a=typeof o=="string"&&o?o:"session failed";this._setPhase("error",{error:{reason:a,code:"runtime-failed",kind:"runtime-failed"}})}else if(i==="closed"||i==="ended"||i==="paused"){let o=s.close_reason??s.closeReason??s.pause_reason??s.pauseReason;if(cd(o)){this._setPhase("paused",{reason:"credits_exhausted"});return}if(this._pastDeadline()){this._setPhase("paused",{reason:"max_session_age"});return}this._setPhase("paused",{reason:typeof o=="string"&&o?o:i})}}}setIncarnation(e){if(!Number.isFinite(e)||e<=this._currentEpoch)return;let t=this._currentEpoch>0,n=this._state==="connected";this._currentEpoch=e;let i=this._selfEpochAdoptUntil>0&&Date.now()<=this._selfEpochAdoptUntil;this._selfEpochAdoptUntil=0,!i&&t&&n&&!this._intentionalDisconnect&&this._renegotiate()}isStaleIncarnation(e){return Number.isFinite(e)?e<this._currentEpoch:!1}isStaleClosedMarker(e){if(!e)return!1;let t=typeof e.status=="string"?e.status:void 0;if(t!=="closed"&&t!=="ended"&&t!=="paused"&&t!=="error")return!1;let n=e.status_epoch??e.statusEpoch,s=typeof n=="number"?n:Number(n);return Number.isFinite(s)?s<this._currentEpoch:!1}_isStaleLivenessEvidence(){return this._phase.name!=="paused"||this._pausedIncarnation===null?!1:this._currentEpoch<=this._pausedIncarnation}async connect(e){if(this.isOpen&&this._state==="connected"&&!this._intentionalDisconnect){e!==void 0&&(this._lastStartOptions=e);return}this._lastStartOptions=e,this._intentionalDisconnect=!1,this._pausedIncarnation=null,this._connectStartedAt??=Date.now(),this._cancelPendingDial?.(new Error("TransportSession: connect superseded by a newer connect()"));let t=++this._generation,n=this._state==="reconnecting"||this._state==="renegotiating";n||this._setState("connecting");let s=null,i=()=>t!==this._generation||this._intentionalDisconnect,o=()=>{if(i())throw new Error("TransportSession: connect cancelled")},a=async()=>{for(let l of this._connectUrls()){o();try{return await this._connectOnce(l,t,e),!0}catch(p){s=p instanceof Error?p:new Error(String(p)),i()||this._cleanupSocket()}}return!1},c=this._forceResolveOnNextConnect&&this._resolveConnection!==null;this._forceResolveOnNextConnect=!1;let u=c?0:this._resolveConnection?Ef:1;for(let l=0;l<u;l++)if(l>0&&(await hd(Pf),o()),await a())return;if(this._resolveConnection)for(let l=0;l<Df;l++){this._setState("reconnecting"),await hd(id[Math.min(l,id.length-1)]),o();try{let p=await this._resolveConnection();o(),this.setAuth({jwt:p.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:p.url,sessionId:p.sessionId,iceServers:p.iceServers??this._options.iceServers}),p.endsAt!==void 0&&(this._endsAt=p.endsAt)}catch(p){if(i())throw new Error("TransportSession: connect cancelled");s=p instanceof Error?p:new Error(String(p));continue}if(await a())return}if(i())throw s??new Error("TransportSession: connect cancelled");this._setState("failed");let d=s??new Error("TransportSession: connect failed");throw n||this._emitError(d),d}leaveLeg(){if(!this.isOpen)return!1;this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null);try{this._send({type:"leave"})}catch{}try{this._ws?.close()}catch{}return!0}disconnect(e="client_detached"){this._generation+=1,this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._cancelPendingDial?.(new Error("TransportSession: connect cancelled by disconnect()")),this._stopMediaProbe(),this._stopStatsSampler(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._clearReconnectBudgetReset(),this._reconnectAttempts=0;try{this._publishedAudio?.track.stop()}catch{}try{this._publishedVideo?.track.stop()}catch{}if(this._publishedAudio=null,this._publishedVideo=null,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}try{this._videoProducer.close()}catch{}this._videoProducer=null}for(let t of this._consumers.values())try{t.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._settleSendTransportWaiters(null,new Error("[urun] sendStreamData: transport disconnected before the send transport arrived")),this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}if(this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce.reject(new Error("TransportSession: disconnected")),this._pendingProduce=null),this._device=null,this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null),this._cleanupSocket(),this._tracks.clear(),this._tracksByName.clear(),this._setState("disconnected"),this._liveReached=!1,this._setPhase("paused",{reason:e}),this._emitter.emit("disconnected")}on(e,t){return this._emitter.on(e,t),()=>{this._emitter.off(e,t)}}_emitDiagnostic(e){let t=this._options.diagnosticSink;if(t)try{t(e)}catch(n){this._diagnosticSinkFailed||(this._diagnosticSinkFailed=!0,console.warn(`[urun] diagnosticSink threw (${String(n instanceof Error?n.message:n)}) \u2014 further diagnostics ride only the structured 'diagnostic' event`))}else e.level==="debug"?console.debug(`[urun] ${e.message}`,e.detail??{}):e.level==="error"?console.error(`[urun] ${e.message}`,e.detail??{}):console.warn(`[urun] ${e.message}`,e.detail??{});this._emitter.emit("diagnostic",e)}sendInput(e,t){this._send({type:"input",data:e,sequence:t})}sendSignal(e){return this._send(e)}onSignal(e){return this.on("signal",e)}emitDiagnostic(e){this._emitDiagnostic(e)}onStreamData(e,t){let n=this._streamDataHandlers.get(e);return n||(n=new Set,this._streamDataHandlers.set(e,n)),n.add(t),()=>{let s=this._streamDataHandlers.get(e);s?.delete(t),s&&s.size===0&&this._streamDataHandlers.delete(e)}}sendStreamData(e,t,n){try{this._requireMediaSupport("sendStreamData")}catch(s){return Promise.reject(s)}return this._wtDataUpSender?this._wtDataUpSender.send(e,Gr(t)):this._ensureDataProducer(e).then(s=>{for(let i of Jc(t))s.send(i)})}get wtDataUplinkSeam(){return{onUplink:e=>{this._wtDataUpSender=e},onUplinkLost:e=>{this._wtDataUpSender&&(this._wtDataUpSender=null,console.warn(`[urun-sh/core] WT data uplink lost (${e}) \u2014 data-up reverts to SCTP for this leg`))}}}_awaitSendTransport(){return this._sendTransport?Promise.resolve(this._sendTransport):new Promise((e,t)=>{let n={resolve:i=>{clearTimeout(s),e(i)},reject:i=>{clearTimeout(s),t(i)}},s=setTimeout(()=>{let i=this._sendTransportWaiters.indexOf(n);i>=0&&this._sendTransportWaiters.splice(i,1),t(new Error(`[urun] sendStreamData: no send transport after ${rd}ms (the server never offered createSendTransport \u2014 data-up produce is impossible on this leg)`))},rd);this._sendTransportWaiters.push(n)})}_settleSendTransportWaiters(e,t){let n=this._sendTransportWaiters;this._sendTransportWaiters=[];for(let s of n)e?s.resolve(e):s.reject(t??new Error("TransportSession: disconnected"))}_ensureDataProducer(e){let t=this._dataProducers.get(e);if(t&&!t.closed)return Promise.resolve(t);let n=this._dataProducerPromises.get(e);if(n)return n;let s=this._awaitSendTransport().then(i=>i.produceData({label:Kc(e),protocol:Yc,ordered:!0})).then(i=>this._awaitDataChannelOpen(i)).then(i=>(this._dataProducers.set(e,i),this._dataProducerPromises.delete(e),i)).catch(i=>{throw this._dataProducerPromises.delete(e),i});return this._dataProducerPromises.set(e,s),s}_awaitDataChannelOpen(e){if(e.closed)return Promise.reject(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"));let t=e.readyState;return t==="open"?Promise.resolve(e):t==="closing"||t==="closed"?Promise.reject(new Error(`[urun] sendStreamData: DataChannel is ${t} \u2014 cannot deliver data-up payloads`)):new Promise((n,s)=>{let i=()=>{u(),n(e)},o=l=>{d(new Error(`[urun] sendStreamData: DataChannel error before open: ${l.message}`))},a=()=>{u(),s(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"))},c=setTimeout(()=>{d(new Error(`[urun] sendStreamData: DataChannel not open after ${nd}ms (the SCTP handshake never completed \u2014 data-up produce is impossible on this channel)`))},nd),u=()=>{clearTimeout(c),e.off("open",i),e.off("error",o),e.observer.off("close",a)},d=l=>{u();try{e.close()}catch{}s(l)};e.on("open",i),e.on("error",o),e.observer.on("close",a)})}_dispatchStreamData(e,t){for(let n of this._streamDataHandlers.get(e)??[])n(t)}markStreamDataLaneQuic(){this._streamDataLane="quic"}dispatchQuicStreamData(e,t){this._dispatchStreamData(e,t)}raiseQuicStreamDataError(e){console.error(e.message),this._emitter.emit("error",e)}quicStreamDataLaneLost(e){if(this._streamDataLane!=="quic")return;this._streamDataLane="sctp";let t=[...this._streamDataHandlers.keys()];if(t.length===0)return;let n=new Error(`[urun] QUIC data lane lost mid-stream (${e}) \u2014 active named streams [${t.join(", ")}] resume over SCTP on the failover leg from now; envelopes in flight on the dead lane are gone (mid-stream-join semantics)`);console.error(n.message),this._emitter.emit("error",n)}_streamNameFromLabel(e){if(e)return e.startsWith("stream:")?e.slice(7):void 0}mediaUnavailableReason(){return this._mediaUnavailableReason}mediaAvailability(){return this._mediaVerdict}_requireMediaSupport(e){if(this._mediaUnavailableReason)throw new Error(`[urun-sh/core] ${e}: realtime media is unavailable in this process \u2014 ${this._mediaUnavailableReason}. This session joined in doc/KV-only mode (the media device was skipped); install the optional "werift" dependency to enable realtime media.`)}async addTrack(e,t){this._requireMediaSupport("addTrack"),await this._publishTrack(e,t)}async _publishTrack(e,t){let n=e.kind==="video";if(!n&&this._wtMicUplink){this._wtMicUplink.setSource(e),this._rememberPublishIntent(!1,e,t);return}if(n&&this._wtCamUplink){this._wtCamUplink.setSource(e),this._rememberPublishIntent(!0,e,t);return}let s=n?this._videoProducer:this._audioProducer;if(s&&!s.closed){if(s.track===e)return;await s.replaceTrack({track:e}),this._rememberPublishIntent(n,e,t);return}if(!this._sendTransport)throw new Error("TransportSession: send transport not ready");let i=await this._sendTransport.produce({track:e,...n?{}:{codecOptions:{opusStereo:!1,opusDtx:!1,opusFec:!1}},stopTracks:!1,...t?{appData:{name:t}}:{}});n?this._videoProducer=i:this._audioProducer=i,this._rememberPublishIntent(n,e,t)}_rememberPublishIntent(e,t,n){let s={track:t,...n!==void 0?{name:n}:{}};e?this._publishedVideo=s:this._publishedAudio=s}removeTrack(){let e=this._publishedAudio;if(this._publishedAudio=null,this._wtMicUplink){this._wtMicUplink.setSource(null);try{e?.track.stop()}catch{}}if(this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}this._audioProducer.close(),this._audioProducer=null}}async addVideoTrack(e,t){this._requireMediaSupport("addVideoTrack"),await this._publishTrack(e,t)}stopVideo(){let e=this._publishedVideo;if(this._publishedVideo=null,this._wtCamUplink){this._wtCamUplink.setSource(null);try{e?.track.stop()}catch{}}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}this._videoProducer.close(),this._videoProducer=null}}requestDiagnostics(){this._send({type:"diagnostics"})}seekStream(e,t){this._send({type:"stream.seek",stream:e,target:t})}async _handleMessage(e){switch(e.type){case"routerRtpCapabilities":await this._onRouterCapabilities(e.rtpCapabilities);break;case"createWebRtcTransport":await this._onCreateRecvTransport(e);break;case"createSendTransport":await this._onCreateSendTransport(e);break;case"consume":await this._onConsume(e);break;case"consumerClosed":this._closeConsumer(e.consumerId);break;case"producerClosed":this._closeConsumersByProducer(e.producerId);break;case"consumerPaused":this._consumers.get(e.consumerId)?.pause();break;case"consumerResumed":this._consumers.get(e.consumerId)?.resume();break;case"iceRestarted":this._onIceRestarted(e);break;case"produced":if(this._pendingProduce){let t=this._pendingProduce;this._pendingProduce=null,clearTimeout(t.timeoutId),t.resolve(e.id)}break;case"dataProduced":{let t=e.label,n=t?this._pendingDataProduce.get(t):void 0;n&&t&&(this._pendingDataProduce.delete(t),n.resolve(e.id));break}case"consumeData":await this._onConsumeData(e);break;case"started":this._emitter.emit("started");break;case"status":this._onStatus(e);break;case"stream.seeked":this._onStreamSeeked(e);break;case"error":this._onServerError(e);break;default:this._emitter.emit("signal",e);break}}_onServerError(e){let t=typeof e.message=="string"?e.message:"signaling error",n=typeof e.code=="string"?e.code:void 0;if(/connect\(\) already called/i.test(t)){if(this._resolveConnection){this._generation++;let s=this._ws;this._ws=null;try{s?.close()}catch{}this._cleanupMedia(),this._forceResolveOnNextConnect=!0,this._renegotiate();return}this._setPhase("error",{error:{reason:t,code:"transport-consumed",kind:"transport-failed"}}),this._emitter.emit("error",new Error(t));return}if(n==="TRANSPORT_BIND_FAILED"){this._emitError(new Error(t),n);return}if(n==="PROTOCOL_VERSION_UNSUPPORTED"){this._setPhase("error",{error:{reason:t,code:n,kind:"create-failed"},reason:t}),this._emitter.emit("error",new Error(t));return}console.warn("[urun] signaling error from server:",t)}_onStreamSeeked(e){let t=typeof e.stream=="string"?e.stream:void 0;if(!t)return;let n=e.target,s=n==="live"?"live":typeof n=="number"?n:Number(n);this._emitter.emit("seeked",t,s)}_reportUnknownServerStatus(e,t,n="signaling",s){let o=`server reported unrecognized ${n==="admission"?"admission response":"session status"} status ${JSON.stringify(e)}`+(t?` (reason: ${JSON.stringify(t)})`:"")+' \u2014 this @urun-sh/core build does not know this word; refusing to render it as "provisioning". The SDK may be out of date for this server.';this._emitDiagnostic({level:"error",kind:"unknown-server-status",message:o,detail:{status:e,origin:n,...t?{reason:t}:{}}}),!this._liveReached&&(this._lastServerStatus=e,this._setPhase("unknown",{reason:e,region:s}))}_onStatus(e){let t=e.request_id??e.requestId;t&&(this._requestId=t);let n=typeof e.status=="string"?e.status:void 0,s=typeof e.reason=="string"&&e.reason?e.reason:void 0,i="region"in e?typeof e.region=="string"&&e.region.length>0?e.region:null:void 0,o=n!==void 0?ad(n):void 0;if(n!==void 0&&o?.unknown){this._reportUnknownServerStatus(n,s,"signaling",i);return}let a=o?.phase??"provisioning";if(this._liveReached&&a!=="paused"&&a!=="error"){a==="live"&&i!==void 0&&i!==this._phase.region&&this._setPhase("live",{reason:s,region:i});return}if(this._isStaleLivenessEvidence()&&a!=="live"&&a!=="paused"&&a!=="error")return;n!==void 0&&(this._lastServerStatus=n);let c=e.queue_position??e.queuePosition,u=e.queue_depth??e.queueDepth,d=typeof c=="number"&&typeof u=="number";if(a==="paused"){let l=e.reason??e.close_reason??e.closeReason??e.pause_reason??e.pauseReason,p=typeof l=="string"&&l?l:void 0,f=cd(l)?"credits_exhausted":this._pastDeadline()?"max_session_age":s??p??n??"paused";this._setPhase("paused",{reason:f,region:i??null}),this._stopMediaProbe();return}if(a==="error"){let l=s??n??"admission failed";this._setPhase("error",{error:{reason:l,code:n,kind:n==="error"?"runtime-failed":"create-failed"},reason:l,region:i});return}if(a==="queued"){this._setPhase("queued",{...d?{queue:{position:c,depth:u}}:{},reason:s,region:i});return}if(a==="waiting_for_capacity"){this._setPhase("waiting_for_capacity",{...d?{queue:{position:c,depth:u}}:{},reason:s,region:i});return}if(a==="connecting"){this._setPhase("connecting",{reason:s,region:i});return}if(a==="live"){this._setPhase("live",{reason:s,region:i});return}this._setPhase("provisioning",{reason:s,region:i})}_webRtcDialHeld=!1;_heldRouterCaps=null;holdWebRtcDial(){return this._webRtcDialHeld=!0,{proceed:e=>{if(!this._webRtcDialHeld)return;this._webRtcDialHeld=!1;let t=this._heldRouterCaps;this._heldRouterCaps=null,t&&(console.info(`[urun-sh/core] running the deferred WebRTC dial (${e})`),this._onRouterCapabilities(t).catch(n=>{console.error("[urun-sh/core] deferred WebRTC dial failed:",n)}))},skip:e=>{console.info(`[urun-sh/core] WebRTC dial SKIPPED (${e}) \u2014 WT-only leg, no RTCPeerConnection`)}}}async _onRouterCapabilities(e){if(this._webRtcDialHeld){this._heldRouterCaps=e;return}et()&&await er();let t=Vc();if(t){this._mediaUnavailableReason=t,this._mediaVerdictResolve(t);return}this._mediaVerdictResolve(null);let n=Bc(),s=new gd.Device(n?{handlerName:n}:void 0);await s.load({routerRtpCapabilities:e}),this._device=s,this._send({type:"rtpCapabilities",rtpCapabilities:s.rtpCapabilities})}async _onCreateRecvTransport(e){this._device&&this._buildRecvTransport(e)}_buildRecvTransport(e){if(!this._device)return;let t=e.iceCandidates,n=this._device.createRecvTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:t,dtlsParameters:e.dtlsParameters,...e.sctpParameters?{sctpParameters:e.sctpParameters}:{},iceServers:this._options.iceServers??ld});this._recvIceRestartAttempts=0,this._clearRecvIceRestart();let s=this._generation;n.on("connect",({dtlsParameters:i},o,a)=>{try{this._send({type:"connectTransport",transportId:n.id,dtlsParameters:i}),o()}catch(c){a(c)}}),n.on("connectionstatechange",i=>{if(s===this._generation){if(i==="connected"){this._clearRecvIceRestart(),this._recvIceRestartAttempts=0,this._reportSelectedCandidatePair(n);return}if(!(this._intentionalDisconnect&&i==="closed")&&(i==="failed"||i==="disconnected")){if(this._tryRestartRecvIce())return;i==="failed"&&this._emitError(new Error(`media transport ${i}`),i),this._renegotiate()}}}),this._recvTransport=n}async _reportSelectedCandidatePair(e){let t=++this._candidatePairRefreshSeq,n=null;if(typeof e.getStats=="function")try{n=await e.getStats()}catch{}if(this._recvTransport!==e||t!==this._candidatePairRefreshSeq)return;let s=Wf(n);if(s.localType===null&&s.remoteType===null&&s.protocol===null&&s.remoteAddress===null&&s.remotePort===null&&this._reportedCandidatePairKey!==null)return;this._selectedCandidatePair=s;let o=JSON.stringify(s);if(this._reportedCandidatePairKey===o)return;this._reportedCandidatePairKey=o;let a=Object.values(this._selectedCandidatePair).some(c=>c!==null);this._emitDiagnostic({level:a?"info":"debug",kind:"ice-candidate-pair",message:`selected ICE candidate pair: local=${this._selectedCandidatePair.localType??"unknown"} remote=${this._selectedCandidatePair.remoteType??"unknown"} protocol=${this._selectedCandidatePair.protocol??"unknown"} remote=${this._selectedCandidatePair.remoteAddress??"unknown"}:${this._selectedCandidatePair.remotePort??"unknown"}`,detail:{sessionId:this._options.sessionId,...this._selectedCandidatePair}})}_tryRestartRecvIce(){let e=this._recvTransport;return!e||e.closed?!1:this._recvIceRestartTimer?!0:this._recvIceRestartAttempts>=dd?!1:(this._recvIceRestartAttempts++,this._armRecvIceRestartWatchdog(),this._requestIceRestart(e.id),!0)}_trySendIceRestart(){let e=this._sendTransport;return!e||e.closed?!1:this._sendIceRestartTimer?!0:this._sendIceRestartAttempts>=dd?!1:(this._sendIceRestartAttempts++,this._armSendIceRestartWatchdog(),this._requestIceRestart(e.id),!0)}_requestIceRestart(e){this._send({type:"restartIce",transportId:e})}_onIceRestarted(e){let t=e.transportId??e.id,n=e.iceParameters;if(!n)return;let s=!!this._recvTransport&&this._recvTransport.id===t,i=!s&&!!this._sendTransport&&this._sendTransport.id===t,o=s?this._recvTransport:i?this._sendTransport:null;o&&(Promise.resolve(o.restartIce({iceParameters:n})).catch(a=>{this._emitter.emit("error",a instanceof Error?a:new Error(String(a)))}),s&&this._recvIceRestartTimer?this._armRecvIceRestartWatchdog():i&&this._sendIceRestartTimer&&this._armSendIceRestartWatchdog())}_armRecvIceRestartWatchdog(){this._clearRecvIceRestart();let e=this._generation;this._recvIceRestartTimer=setTimeout(()=>{this._recvIceRestartTimer=null,!(e!==this._generation||this._intentionalDisconnect)&&this._recvTransport?.connectionState!=="connected"&&(this._emitError(new Error("media transport failed (ice restart timeout)"),"failed"),this._renegotiate())},ud)}_armSendIceRestartWatchdog(){this._clearSendIceRestart();let e=this._generation;this._sendIceRestartTimer=setTimeout(()=>{this._sendIceRestartTimer=null,!(e!==this._generation||this._intentionalDisconnect)&&this._sendTransport?.connectionState!=="connected"&&this._emitError(new Error("media send transport failed (ice restart timeout)"),"failed")},ud)}_clearRecvIceRestart(){this._recvIceRestartTimer&&(clearTimeout(this._recvIceRestartTimer),this._recvIceRestartTimer=null)}_clearSendIceRestart(){this._sendIceRestartTimer&&(clearTimeout(this._sendIceRestartTimer),this._sendIceRestartTimer=null)}async _onCreateSendTransport(e){if(!this._device)return;let t=this._device.createSendTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:e.iceCandidates,dtlsParameters:e.dtlsParameters,...e.sctpParameters?{sctpParameters:e.sctpParameters}:{},iceServers:this._options.iceServers??ld});this._sendIceRestartAttempts=0,this._clearSendIceRestart();let n=this._generation;t.on("connect",({dtlsParameters:s},i,o)=>{try{this._send({type:"connectSendTransport",transportId:t.id,dtlsParameters:s}),i()}catch(a){o(a)}}),t.on("produce",({kind:s,rtpParameters:i,appData:o},a,c)=>{if(this._pendingProduce){c(new Error("produce already pending"));return}let u=o&&typeof o.name=="string"?o.name:void 0,d=setTimeout(()=>{let l=this._pendingProduce;if(!l||l.timeoutId!==d)return;this._pendingProduce=null;let p=new St(s,{stream:u,timeoutMs:Tt});this._setPhase("error",{error:{reason:p.message,code:"produce-ack-timeout",kind:"produce-timeout"}}),this._emitter.emit("error",p),l.reject(p)},Tt);this._pendingProduce={timeoutId:d,resolve:l=>{a({id:l})},reject:c};try{this._send(u?{type:"produce",kind:s,name:u,rtpParameters:i}:{type:"produce",kind:s,rtpParameters:i})}catch(l){this._pendingProduce?.timeoutId===d&&(this._pendingProduce=null,clearTimeout(d)),c(l)}}),t.on("producedata",({sctpStreamParameters:s,label:i,protocol:o},a,c)=>{try{i&&this._pendingDataProduce.set(i,{resolve:u=>a({id:u}),reject:c}),this._send({type:"produceData",sctpStreamParameters:s,label:i,protocol:o})}catch(u){i&&this._pendingDataProduce.delete(i),c(u)}}),t.on("connectionstatechange",s=>{if(n===this._generation){if(s==="connected"){this._clearSendIceRestart(),this._sendIceRestartAttempts=0;return}this._intentionalDisconnect&&s==="closed"||(s==="failed"||s==="disconnected")&&this._trySendIceRestart()||(s==="failed"||s==="closed")&&this._emitError(new Error(`media send transport ${s}`),s)}}),this._sendTransport=t,this._settleSendTransportWaiters(t),this._emitter.emit("audioTransportReady"),this._republishPublishedTracks()}async _republishPublishedTracks(){let e=this._publishedAudio;if(e&&e.track.readyState!=="ended"&&(!this._audioProducer||this._audioProducer.closed))try{await this.addTrack(e.track,e.name)}catch(n){console.warn("[urun] republish: mic re-produce after reconnect failed",n)}else e&&e.track.readyState==="ended"&&console.warn("[urun] republish: published mic track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)");let t=this._publishedVideo;if(t&&t.track.readyState!=="ended"&&(!this._videoProducer||this._videoProducer.closed))try{await this.addVideoTrack(t.track,t.name)}catch(n){console.warn("[urun] republish: camera re-produce after reconnect failed",n)}else t&&t.track.readyState==="ended"&&console.warn("[urun] republish: published camera track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)")}async _onConsumeData(e){if(this._streamDataLane==="quic"){this.raiseQuicStreamDataError(new Error(`[urun] consumeData (label=${String(e.label)}) pushed on a leg whose data lane is QUIC \u2014 refusing (one canonical data path per leg, contract urun-infra#1605)`));return}let t=this._recvTransport;if(!t)return;let n=e.label,s=this._streamNameFromLabel(n);if(!s)return;let i=this._generation,o=await t.consumeData({id:e.id,dataProducerId:e.dataProducerId,sctpStreamParameters:e.sctpStreamParameters,label:n,protocol:e.protocol});if(i!==this._generation||this._recvTransport!==t||t.closed||this._intentionalDisconnect){try{o.close()}catch{}return}this._dataConsumers.set(s,o);let a=new ss;o.on("message",d=>{try{let l=typeof d=="string"?new TextEncoder().encode(d):new Uint8Array(d),p=a.feed(l);p!==void 0&&this._dispatchStreamData(s,p)}catch(l){this._emitter.emit("error",l instanceof Error?l:new Error(String(l)))}});let c=!1,u=()=>{c||o.closed||(c=!0,this._send({type:"dataConsumerReady",id:e.id}))};o.readyState==="open"?u():o.on("open",u)}async _onConsume(e){let t=this._recvTransport;if(!t)return;let n=this._generation,s=await t.consume({id:e.id,producerId:e.producerId,kind:e.kind,rtpParameters:e.rtpParameters});if(n!==this._generation||this._recvTransport!==t||t.closed||this._intentionalDisconnect){try{s.close()}catch{}return}this._consumers.set(s.id,s),this._tracks.set(s.track.id,s.track),this._capJitterBuffer(s,s.kind==="video"?"video":"audio");let i=e.streamName??e.label;i&&this._tracksByName.set(i,s.track),s.track.addEventListener?.("unmute",()=>{n!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._liveReached||this._setPhase("live")},{once:!0}),this._emitter.emit("track",s.track);let o=s.id;s.track.addEventListener("ended",()=>{n!==this._generation||this._intentionalDisconnect||this._closeConsumer(o)},{once:!0}),this._send({type:"resumeConsumer",consumerId:s.id}),this._startMediaProbe(),this._startStatsSampler()}get audioPlayoutOptions(){return this._options.audioPlayout}get wtMicUplinkSeam(){return{onUplink:e=>{this._wtMicUplink=e;let t=this._publishedAudio;if(this._audioProducer&&!this._audioProducer.closed){console.warn("[urun-sh/core] WT mic uplink engaged \u2014 moving the mic from WebRTC produce to the QUIC lane"),this._send({type:"stopAudio"});try{this._audioProducer.close()}catch{}this._audioProducer=null}t&&e.setSource(t.track)},onUplinkLost:e=>{if(!this._wtMicUplink)return;this._wtMicUplink=null;let t=this._publishedAudio;if(!(!t||t.track.readyState==="ended")){if(console.warn(`[urun-sh/core] WT mic uplink lost (${e}) \u2014 republishing the mic over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-mic-uplink-dead",message:`WT mic uplink lost (${e}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the mic is now DEAD until the WT uplink re-engages.`,detail:{reason:e}});return}this._publishTrack(t.track,t.name).catch(n=>{console.error("[urun-sh/core] mic republish over WebRTC failed:",n)})}}}}get wtCamUplinkSeam(){return{onUplink:e=>{this._wtCamUplink=e;let t=this._publishedVideo;if(this._videoProducer&&!this._videoProducer.closed){console.warn("[urun-sh/core] WT video uplink engaged \u2014 moving the camera from WebRTC produce to the QUIC lane"),this._send({type:"stopVideo"});try{this._videoProducer.close()}catch{}this._videoProducer=null}t&&e.setSource(t.track)},onUplinkLost:e=>{if(!this._wtCamUplink)return;this._wtCamUplink=null;let t=this._publishedVideo;if(!(!t||t.track.readyState==="ended")){if(console.warn(`[urun-sh/core] WT video uplink lost (${e}) \u2014 republishing the camera over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-cam-uplink-dead",message:`WT camera uplink lost (${e}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the camera is now DEAD until the WT uplink re-engages.`,detail:{reason:e}});return}this._publishTrack(t.track,t.name).catch(n=>{console.error("[urun-sh/core] camera republish over WebRTC failed:",n)})}}}}_jitterBufferTargetMs(e){if(e==="audio"){let t=this._options.audioPlayout?.jitterBufferTargetMs;return t===void 0?Cf:t}return this._options.videoPlayout?.jitterBufferTargetMs}_capJitterBuffer(e,t){let n=this._jitterBufferTargetMs(t);if(n===void 0)return;let s=t==="video"?"videoPlayout":"audioPlayout",i={mediaKind:t,transportId:this._recvTransport?.id??null};if(!Number.isFinite(n)){this._emitDiagnostic({level:"warning",kind:`${t}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be a finite number of milliseconds; got ${String(n)}. No jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:String(n),...i}});return}if(n<=0)return;if(n>sd){this._emitDiagnostic({level:"warning",kind:`${t}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be within the W3C jitterBufferTarget range 0-${sd}ms; got ${n}. No jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:n,...i}});return}let o=e.rtpReceiver;if(!o){this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-unsupported`,message:`${t} consumer exposes no RTCRtpReceiver (node/werift leg); no jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:n,reason:"no-receiver",...i}});return}let a=[];if("jitterBufferTarget"in o&&(o.jitterBufferTarget=n,a.push("jitterBufferTarget")),"playoutDelayHint"in o&&(o.playoutDelayHint=n/1e3,a.push("playoutDelayHint")),a.length===0){this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-unsupported`,message:`${t==="audio"?"Audio":"Video"} receiver exposes neither jitterBufferTarget nor playoutDelayHint; standing ${t} playout delay is unbounded on this engine.`,detail:{consumerId:e.id,targetMs:n,...i}});return}this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-capped`,message:`${t==="audio"?"Audio":"Video"} receiver jitter buffer capped at ${n}ms.`,detail:{consumerId:e.id,targetMs:n,applied:a,...i}})}_closeConsumer(e){let t=this._consumers.get(e);if(!t)return;this._consumers.delete(e);let n=t.track;try{t.close()}catch{}if(n){this._tracks.delete(n.id);for(let[s,i]of this._tracksByName)i===n&&this._tracksByName.delete(s)}}_closeConsumersByProducer(e){for(let[t,n]of this._consumers)n.producerId===e&&this._closeConsumer(t)}_mediaPollMs(){let e=this._options.mediaLiveness?.pollMs;return e===void 0?kf:e}_firstFrameWindowMs(){let e=this._options.mediaLiveness?.stallTimeoutMs;return e===void 0?Tf:e}_startMediaProbe(){let e=this._mediaPollMs();if(e<=0||this._mediaProbeTimer)return;let t=this._generation;this._mediaProbeTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._sampleMediaArrival(t)},e)}_stopMediaProbe(){this._mediaProbeTimer&&(clearInterval(this._mediaProbeTimer),this._mediaProbeTimer=null)}_statsPollMs(){let e=this._options.sessionStats;if(!e)return 0;let t=e.pollMs;return t===void 0?Rf:Number.isFinite(t)&&t>0?t:0}_startStatsSampler(){let e=this._statsPollMs();if(e<=0||this._statsTimer)return;let t=this._generation;this._statsTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._isParkedPhase()||this._statsSampleInFlight||(this._statsSampleInFlight=!0,this._sampleSessionStats(t).catch(n=>{try{this._emitter.emit("error",n instanceof Error?n:new Error(String(n)))}catch{}}).finally(()=>{this._statsSampleInFlight=!1}))},e)}_stopStatsSampler(){this._statsTimer&&(clearInterval(this._statsTimer),this._statsTimer=null),this._statsSampleInFlight=!1}_lanePairKey(e){let t=e.track,n=t?this._streamNameOf(t):void 0;if(n===void 0)return null;let s=os(n);return s===void 0?n:n.slice(0,n.length-nr.length-s.length)}async _sampleSessionStats(e){if(this._consumers.size===0)return;let t=Array.from(this._consumers.values()),n=await Promise.all(t.map(async p=>({consumerId:p.id,kind:p.kind==="video"?"video":"audio",pairKey:this._lanePairKey(p),sample:await md(p)})));if(e!==this._generation||this._intentionalDisconnect||this._isParkedPhase())return;let s=n.filter(p=>p.pairKey===null),i=n.filter(p=>p.pairKey!==null),o=null,a=n;if(i.length>0){let p=new Map;for(let m of i){let g=m.pairKey,_=p.get(g);_?_.push(m):p.set(g,[m])}let f=-1,h=-1;for(let[m,g]of p){let _=new Set(g.map(y=>y.kind)).size>=2?1:0,v=g.reduce((y,S)=>y+S.sample.total,0);(_>f||_===f&&v>h)&&(f=_,h=v,o=m,a=[...g,...s])}}let c=p=>{let f=null,h=-1;for(let{consumerId:m,kind:g,sample:_}of a)g===p&&_.total>h&&(h=_.total,f={consumerId:m,..._});return f},u=c("audio"),d=c("video"),l=d?.estimatedPlayoutTimestamp!=null&&u?.estimatedPlayoutTimestamp!=null?d.estimatedPlayoutTimestamp-u.estimatedPlayoutTimestamp:null;this._emitter.emit("stats",{timestamp:Date.now(),stream:o,avSyncMs:l,audio:u,video:d})}_resetJoinProbes(){this._joinProbes.clear(),this._decodeDeathHandled=!1}async _sampleMediaArrival(e){if(this._consumers.size===0)return;let t=Array.from(this._consumers.entries()),n=await Promise.all(t.map(async([a,c])=>[a,await md(c)]));if(e!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence())return;for(let a of this._joinProbes.keys())this._consumers.has(a)||this._joinProbes.delete(a);let s=Date.now();!this._liveReached&&n.some(([,a])=>a.total>0)&&this._setPhase("live");let i=null,o=!1;for(let[a,c]of n){if(c.total<=0){o=!0;continue}let u=this._joinProbes.get(a);if(u||(u={firstBytesAt:s,startSample:c,settled:!1},this._joinProbes.set(a,u)),!u.settled){if(c.framesDecoded===null){u.settled=!0;continue}if(c.framesDecoded>0){u.settled=!0;continue}if(s-u.firstBytesAt>=this._firstFrameWindowMs()){i??={id:a,probe:u,sample:c};continue}o=!0}}if(i&&!this._decodeDeathHandled){this._decodeDeathHandled=!0;let a=this._firstFrameWindowMs(),c=Ff(i.probe.startSample,i.sample),u=c.lossPct!==null&&c.lossPct>=5?" \u2014 consistent with network packet loss between the SFU and this browser":"";this._emitDiagnostic({level:"warning",kind:"decode-wall",message:`video is arriving but the decoder never produced its first frame within ${a/1e3}s of join (framesDecoded still 0) \u2014 no keyframe to start from${u}; re-consuming the stream`,detail:{sessionId:this._options.sessionId,consumerId:i.id,firstFrameWindowMs:a,inboundTotal:i.sample.total,framesDecoded:i.sample.framesDecoded,...Nf(i.sample),...c,likelyCause:c.lossPct!==null&&c.lossPct>=5?"network-packet-loss":null,...this._selectedCandidatePair}}),this._renegotiate();return}!o&&!i&&this._stopMediaProbe()}_renegotiate(){this._intentionalDisconnect||this._isParkedPhase()||this._reconnectTimer||(this._stopMediaProbe(),this._stopStatsSampler(),this._setState("renegotiating"),this._attemptReconnect())}recover(){if(this._intentionalDisconnect||this._isParkedPhase()||this._connectStartedAt===void 0||this._cancelPendingDial)return;if(!this.isOpen){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0,this._attemptReconnect(void 0,!0);return}let e=this._recvTransport?.connectionState;(e==="disconnected"||e==="failed")&&(this._recvIceRestartTimer||(this._recvIceRestartAttempts=0),this._tryRestartRecvIce()||this._renegotiate());let t=this._sendTransport?.connectionState;(t==="disconnected"||t==="failed")&&(this._sendIceRestartTimer||(this._sendIceRestartAttempts=0),this._trySendIceRestart())}_attemptReconnect(e,t=!1){if(this._intentionalDisconnect||this._isParkedPhase()||this._reconnectTimer)return;if(this._reconnectAttempts>=td){this._setState("failed"),this._emitError(new Error(`Failed after ${td} attempts`));return}let n=t?0:ed[Math.min(this._reconnectAttempts,ed.length-1)];this._reconnectAttempts++,this._state!=="renegotiating"&&this._setState("reconnecting"),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null,this._replaceCurrentLegForReconnect();try{await this.connect(e??this._lastStartOptions)}catch(s){if(s instanceof Error&&s.message==="TransportSession: connect cancelled")return;this._attemptReconnect(e)}},n)}_connectUrls(){let e=[],t=n=>{if(!n)return;let s=pd(n)!==void 0,i=this._sessionId&&!s?`${n}${n.includes("?")?"&":"?"}sessionId=${encodeURIComponent(this._sessionId)}`:n;e.includes(i)||e.push(i)};t(this._options.url);for(let n of this._options.fallbackUrls??[])t(n);return e}_connectOnce(e,t,n){return new Promise((s,i)=>{let o=!1,a=!1,c=null,u=new WebSocket(e);this._ws=u;let d=()=>this._ws!==u||t!==this._generation,l=f=>{a||(a=!0,c&&clearTimeout(c),this._cancelPendingDial===p&&(this._cancelPendingDial=null),i(f))},p=f=>{try{u.close()}catch{}l(f)};this._cancelPendingDial=p,c=setTimeout(()=>{try{u.close()}catch{}l(new Error("TransportSession: connect timed out"))},bf),u.onopen=()=>{if(!a){if(d()){try{u.close()}catch{}l(new Error("TransportSession: connect superseded during dial"));return}o=!0,c&&clearTimeout(c),this._connectedUrl=e,this._multiplexer=new _t(u),u.send(JSON.stringify(this._startMessage(n))),this._scheduleReconnectBudgetReset(),this._selfEpochAdoptUntil=Date.now()+Sf,this._setState("connected"),this._liveReached||this._setPhase("connecting"),this._emitter.emit("connected"),a=!0,this._cancelPendingDial===p&&(this._cancelPendingDial=null),s()}},u.onerror=()=>{o||l(new Error("WebSocket connection error"))},u.onclose=()=>{if(!o){l(new Error("WebSocket closed before connecting"));return}if(!d()&&(this._clearReconnectBudgetReset(),c&&clearTimeout(c),this._setState("disconnected"),!this._intentionalDisconnect)){if(this._pastDeadline()&&this._phase.name!=="paused"){this._setPhase("paused",{reason:"max_session_age"}),this._emitter.emit("disconnected");return}this._emitter.emit("disconnected"),!this._isParkedPhase()&&this._attemptReconnect(n)}},u.onmessage=f=>{if(!(this._ws!==u||t!==this._generation)&&typeof f.data=="string")try{this._handleMessage(JSON.parse(f.data)).catch(h=>{this._emitter.emit("error",h instanceof Error?h:new Error(String(h)))})}catch(h){this._emitter.emit("error",h instanceof Error?h:new Error(String(h)))}}})}_startMessage(e){let t={type:"start",version:Wi,video:e?.video??{width:854,height:480,frameRate:16}};return e?.prompt&&(t.prompt=e.prompt),e?.cameraControl&&(t.camera_control=e.cameraControl),e?.args&&(t.args=e.args),e?.app&&(t.app=e.app),e?.functionName&&(t.function=e.functionName),e?.role&&(t.role=e.role),this._options.orgId&&(t.orgId=this._options.orgId),this._options.jwt&&(t.jwt=this._options.jwt),this._options.authProvider&&(t.authProvider=this._options.authProvider),t}_cleanupSocket(){if(this._clearReconnectBudgetReset(),!this._ws)return;let e=this._ws;this._ws=null,e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{e.close()}catch{}}_replaceCurrentLegForReconnect(){this._cleanupSocket(),this._cancelPendingDial?.(new Error("TransportSession: reconnect replacing current dial")),this._cleanupMedia()}_scheduleReconnectBudgetReset(){this._clearReconnectBudgetReset(),this._reconnectAttempts!==0&&(this._stableResetTimer=setTimeout(()=>{this._stableResetTimer=null,this._reconnectAttempts=0},xf))}_clearReconnectBudgetReset(){this._stableResetTimer&&(clearTimeout(this._stableResetTimer),this._stableResetTimer=null)}_cleanupDataChannels(){for(let e of this._dataProducers.values())try{e.close()}catch{}this._dataProducers.clear(),this._dataProducerPromises.clear();for(let e of this._dataConsumers.values())try{e.close()}catch{}this._dataConsumers.clear();for(let e of this._pendingDataProduce.values())try{e.reject(new Error("TransportSession: disconnected"))}catch{}this._pendingDataProduce.clear()}_cleanupMedia(){this._stopMediaProbe(),this._stopStatsSampler(),this._resetJoinProbes();for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._audioProducer){try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){try{this._videoProducer.close()}catch{}this._videoProducer=null}if(this._clearRecvIceRestart(),this._clearSendIceRestart(),this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}if(this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce=null),this._device=null,this._tracks.clear(),this._tracksByName.clear(),this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null)}_send(e){return!this._ws||this._ws.readyState!==WebSocket.OPEN?!1:(this._ws.send(JSON.stringify(e)),!0)}_setState(e){this._state!==e&&(this._state=e,this._emitter.emit("stateChange",e))}_isParkedPhase(){return this._phase.name==="paused"?!0:this._phase.name!=="error"?!1:this._phase.error?.kind!=="transport-failed"}_setPhase(e,t){e==="live"?this._liveReached=!0:(e==="paused"||e==="error")&&(this._liveReached=!1);let n={name:e};t?.queue&&(n.queue=t.queue),t?.runtime&&(n.runtime=t.runtime),t?.reason&&(n.reason=t.reason),n.region=t?.region!==void 0?t.region:this._phase.region,nn(e)?(this._wakingSince??=Date.now(),n.wakingSince=this._wakingSince):this._wakingSince=void 0,this._requestId&&(n.requestId=this._requestId),this._sessionId&&(n.sessionId=this._sessionId),this._endsAt!==null&&(n.endsAt=this._endsAt),t?.error&&(n.error=t.error),!Af(this._phase,n)&&(this._phase=n,this._pausedIncarnation=e==="paused"?this._currentEpoch:null,this._isParkedPhase()&&(this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null)),this._emitter.emit("phase",n))}reportAdmission(e){e.requestId&&(this._requestId=e.requestId),this._lastServerStatus=e.status;let t=ad(e.status);if(t.unknown){this._reportUnknownServerStatus(e.status,e.reason,"admission",e.region);return}if(this._liveReached)return;let{runtime:n,queue:s}=e,i=e.decisionReason==="provisioning_refused"?e.refusalMessage??e.decisionReason:e.reason,o={runtime:n,queue:s,...i?{reason:i}:{},...e.region!==void 0?{region:e.region}:{}};if(Lf(e.status)){if(n?.state==="unavailable"){this._setPhase("unavailable",o);return}if(n?.state==="starting"){this._setPhase("provisioning",o);return}if(n?.state==="busy"||e.status==="queued"){this._setPhase("queued",o);return}this._setPhase("provisioning",o);return}this._setPhase(t.phase,t.phase==="paused"?{...o,region:o.region??null}:o)}_emitError(e,t){this._setPhase("error",{error:{reason:e.message,code:t,kind:"transport-failed"}}),this._emitter.emit("error",e)}reportAllocationFailure(e,t,n,s){n==="insufficient_credits"?this._setPhase("error",{error:{reason:e.message,code:n,kind:"insufficient-credits",httpStatus:t}}):this._setPhase("error",{error:{reason:e.message,code:n??"allocation-failed",kind:"create-failed",httpStatus:t,retryAfterSeconds:s}}),this._emitter.emit("error",e)}};function hd(r){return new Promise(e=>setTimeout(e,r))}function Mf(){return tr()}var vd=["packetsReceived","packetsLost","nackCount","pliCount","firCount","keyFramesDecoded","framesReceived","framesDropped","retransmittedPacketsReceived","retransmittedBytesReceived","jitterBufferDelay","jitterBufferEmittedCount","estimatedPlayoutTimestamp","jitterBufferTargetDelay","jitterBufferMinimumDelay","concealedSamples","insertedSamplesForDeceleration"],Of=new Set(["estimatedPlayoutTimestamp"]);function Uf(){return{total:0,framesDecoded:null,packetsReceived:null,packetsLost:null,nackCount:null,jitter:null,pliCount:null,firCount:null,keyFramesDecoded:null,framesReceived:null,framesDropped:null,retransmittedPacketsReceived:null,retransmittedBytesReceived:null,jitterBufferDelay:null,jitterBufferEmittedCount:null,estimatedPlayoutTimestamp:null,jitterBufferTargetDelay:null,jitterBufferMinimumDelay:null,concealedSamples:null,insertedSamplesForDeceleration:null}}function Nf(r){return Object.fromEntries(vd.map(e=>[e,r[e]]))}function fd(r,e){return r===null||e===null||e<r?null:e-r}function Ff(r,e){let t=r.packetsLost!==null&&e.packetsLost!==null?e.packetsLost-r.packetsLost:null,n=fd(r.packetsReceived,e.packetsReceived),s=fd(r.nackCount,e.nackCount),i=t===null?null:Math.max(0,t),o=i!==null&&n!==null?i+n:0;return{packetsLostWindow:t,packetsReceivedWindow:n,nackCountWindow:s,jitterSec:e.jitter,lossPct:o>0&&i!==null?i/o*100:null}}function wd(){return{localType:null,remoteType:null,protocol:null,remoteAddress:null,remotePort:null}}function Wf(r){let e=new Map;yd(r,a=>{let c=typeof a.id=="string"?a.id:null;c&&e.set(c,a)});let t=Array.from(e.values()).find(a=>a.type==="transport"),n=typeof t?.selectedCandidatePairId=="string"?t.selectedCandidatePairId:null,s=(n?e.get(n):void 0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.selected===!0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.nominated===!0);if(!s)return wd();let i=typeof s.localCandidateId=="string"?e.get(s.localCandidateId):void 0,o=typeof s.remoteCandidateId=="string"?e.get(s.remoteCandidateId):void 0;return{localType:typeof i?.candidateType=="string"?i.candidateType:null,remoteType:typeof o?.candidateType=="string"?o.candidateType:null,protocol:typeof i?.protocol=="string"?i.protocol:typeof o?.protocol=="string"?o.protocol:null,remoteAddress:typeof o?.address=="string"?o.address:typeof o?.ip=="string"?o.ip:null,remotePort:typeof o?.port=="number"?o.port:null}}function yd(r,e){let t=n=>{n&&typeof n=="object"&&e(n)};if(r instanceof Map)for(let[n,s]of r.entries()){if(!s||typeof s!="object")continue;let i=s;e(typeof i.id=="string"?i:{...i,id:n})}else(Array.isArray(r)||r&&typeof r.forEach=="function")&&r.forEach(t)}async function md(r){let e=Uf();if(typeof r.getStats!="function")return e;let t;try{t=await r.getStats()}catch{return e}return yd(t,s=>{if(s.type==="inbound-rtp"){let i=typeof s.bytesReceived=="number"?s.bytesReceived:0,o=typeof s.packetsReceived=="number"?s.packetsReceived:0;e.total+=i+o,typeof s.framesDecoded=="number"&&(e.framesDecoded=(e.framesDecoded??0)+s.framesDecoded),typeof s.jitter=="number"&&(e.jitter=e.jitter===null?s.jitter:Math.max(e.jitter,s.jitter));for(let a of vd)typeof s[a]=="number"&&(e[a]=Of.has(a)?e[a]===null?s[a]:Math.max(e[a],s[a]):(e[a]??0)+s[a])}}),e}function jf(r){if(!r||typeof r!="object")return;let e=r.epoch,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0}var Yr=Ke(require("yjs"));var bd=require("y-websocket"),qi=require("y-protocols/awareness"),qf=1;function cs(r){let e=new URL(r);return`${e.protocol}//${e.host}/doc`}var $f=2500,Bf=3e4,Hf=1e4,Vf=3;function Sd(r){let e=r.WebSocketPolyfill??globalThis.WebSocket;if(!e)throw new Error("[urun] no WebSocket implementation available for the yjs doc provider (browser global missing and no WebSocketPolyfill passed)");return(t,n,s)=>{let i=`${r.sessionId}/${t}`,o=typeof r.token=="function"?r.token:null,a=typeof r.token=="string"?r.token:void 0,c=r.maxBackoffTimeMs??$f,u=r.dialTimeoutMs??Bf,d=new bd.WebsocketProvider(r.serverUrl,i,n,{awareness:s,params:{dsv:String(qf),...a?{token:a}:{}},WebSocketPolyfill:e,disableBc:!0,maxBackoffTime:c,resyncInterval:Hf,connect:o===null}),l=!1,p=0,f=!1,h=U=>{f||(f=!0,console.error(`[urun] doc token refresh failed for room ${i} (redialing with previous token):`,U))},m=()=>{if(!o)return;let U=++p;try{let I=o();if(typeof I=="string"){d.params.token=I,f=!1;return}if(I&&typeof I.then=="function")return I.then(V=>{U===p&&typeof V=="string"&&(d.params.token=V,f=!1)},V=>{h(V)})}catch(I){h(I)}},g=r.resolveServerUrl,_=0,v=!1,y=U=>{if(typeof U!="string"||U==="")return;let I=U.replace(/\/+$/,"");I!==d.serverUrl&&(d.serverUrl=I,v=!1)},S=()=>{if(!g)return;let U=++_,I=V=>{v||(v=!0,console.error(`[urun] doc endpoint re-resolve failed for room ${i} (redialing previous host):`,V))};try{let V=g();if(V&&typeof V.then=="function")return V.then(M=>{U===_&&y(M)},I);y(V)}catch(V){I(V)}},w={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null},b=new Set,O=!1,j=()=>{let U={...w};for(let I of[...b])I(U)},F=null,$=()=>{F!==null&&(clearTimeout(F),F=null)},ue=()=>{$(),F=setTimeout(()=>{if(F=null,!l&&d.wsconnecting&&d.ws)try{d.ws.close()}catch{}},u)},te=null,me=()=>{te!==null&&(clearTimeout(te),te=null)},xe=()=>{me(),te=setTimeout(()=>{if(te=null,!l&&d.shouldConnect&&!d.wsconnected&&!d.wsconnecting&&d.ws===null)try{d.connect()}catch(U){O||(O=!0,console.error(`[urun] doc connection redial threw for room ${i} (still retrying):`,U)),xe()}},c+500)},je=({status:U})=>{if(U==="connecting"){me(),ue();return}if(U==="connected"){$(),me(),w={...w,connected:!0},j();return}w.connected&&(w={...w,connected:!1},j())},_r=U=>{U&&(O&&(console.info(`[urun] doc connection recovered for room ${i}`),O=!1),w.consecutiveFailures!==0&&(w={...w,consecutiveFailures:0},j()))},R=U=>{$(),w={connected:!1,consecutiveFailures:w.consecutiveFailures+1,lastCloseCode:U?U.code:null,lastCloseReason:U&&U.reason?U.reason:null},!O&&w.consecutiveFailures>=Vf&&(O=!0,console.error(`[urun] doc connection failing for room ${i}: ${w.consecutiveFailures} consecutive failures (last close ${w.lastCloseCode===null?"by provider liveness reap":`code ${w.lastCloseCode}`}${w.lastCloseReason?`, reason "${w.lastCloseReason}"`:""}). Still retrying \u2014 the doc provider never gives up.`)),j(),m(),S(),xe()};d.on("status",je),d.on("sync",_r),d.on("connection-close",R),d.wsconnecting?ue():d.wsconnected&&(w={...w,connected:!0});let L=!1,N=!1,Q=null;if(o!==null){let U=m();if(U){N=!0;let I=()=>{N&&(N=!1,Q!==null&&(clearTimeout(Q),Q=null),!l&&!L&&d.connect())};Q=setTimeout(I,u),U.then(I)}else d.connect()}return{get awareness(){return d.awareness},get synced(){return d.synced},onSync(U){let I=V=>U(V);return d.on("sync",I),()=>d.off("sync",I)},onConnectionState(U){return b.add(U),U({...w}),()=>b.delete(U)},ensureConnected(){L=!1,!d.wsconnected&&!N&&d.connect()},disconnect(){L=!0,d.disconnect()},destroy(){l=!0,Q!==null&&(clearTimeout(Q),Q=null),$(),me(),d.off("status",je),d.off("sync",_r),d.off("connection-close",R),b.clear(),d.destroy()}}}}var ji=class{constructor(e,t,n){this._name=e;this._doc=t;this.awareness=n}_name;_doc;awareness;_inner=null;_innerUnsub=null;_innerStateUnsub=null;_syncHandlers=new Set;_stateHandlers=new Set;_lastState={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};_destroyed=!1;_suspended=!1;get synced(){return this._inner?.synced??!1}get destroyed(){return this._destroyed}onSync(e){return this._syncHandlers.add(e),()=>this._syncHandlers.delete(e)}onConnectionState(e){return this._stateHandlers.add(e),e({...this._lastState}),()=>this._stateHandlers.delete(e)}attach(e){if(!this._destroyed){if(this._inner&&(this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner.destroy(),this._inner=null),this._inner=e(this._name,this._doc,this.awareness),this._innerUnsub=this._inner.onSync(t=>{for(let n of[...this._syncHandlers])n(t)}),this._inner.onConnectionState)this._innerStateUnsub=this._inner.onConnectionState(t=>{this._lastState=t;for(let n of[...this._stateHandlers])n(t)});else{this._innerStateUnsub=null,this._lastState={connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};for(let t of[...this._stateHandlers])t({...this._lastState})}if(this._suspended&&this._inner.disconnect?.(),this._inner.synced)for(let t of[...this._syncHandlers])t(!0)}}ensureConnected(){this._suspended=!1,this._inner?.ensureConnected?.()}get disconnect(){return this._inner?.disconnect?()=>{this._suspended=!0,this._inner.disconnect()}:void 0}destroy(){this._destroyed=!0,this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner?.destroy(),this._inner=null,this._syncHandlers.clear(),this._stateHandlers.clear()}},as=class{_target=null;_bridges=[];connect=(e,t,n)=>{let s=new ji(e,t,n);return this._bridges.push(s),this._target&&s.attach(this._target),s};get connected(){return this._target!==null}setTarget(e){if(this._target!==e){this._target=e,this._bridges=this._bridges.filter(t=>!t.destroyed);for(let t of this._bridges)t.attach(e)}}};function Qr(r){if(r===null||typeof r!="object"||Array.isArray(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null}var ds="$bytes";function zf(r){return r instanceof Uint8Array||r instanceof ArrayBuffer}function Gf(r){if(!Qr(r))return!1;let e=Object.keys(r);return e.length===1&&e[0]===ds&&typeof r[ds]=="string"}function Kf(r){return r instanceof ArrayBuffer?new Uint8Array(r):r}function Yf(r){if(typeof Buffer<"u")return Buffer.from(r).toString("base64");let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)}function Qf(r){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function $i(r){if(zf(r))return{[ds]:Yf(Kf(r))};if(Array.isArray(r))return r.map($i);if(Qr(r)){let e={};for(let[t,n]of Object.entries(r))e[t]=$i(n);return e}return r}function Kr(r){if(Gf(r))return Qf(r[ds]);if(Array.isArray(r))return r.map(Kr);if(Qr(r)){let e={};for(let[t,n]of Object.entries(r))e[t]=Kr(n);return e}return r}var kd=Symbol("urun:doc:path-absent");function Jf(r,e){let t=e.split("."),n=r;for(let s of t){if(n===null||typeof n!="object"||!(s in n))return kd;n=n[s]}return n}function Xf(r,e){return r===e?!0:JSON.stringify(r)===JSON.stringify(e)}function Bi(r,e){for(let[t,n]of Object.entries(e))if(Qr(n)){let s=r.get(t);if(!(s instanceof Yr.Map)){let i=s;s=new Yr.Map,r.set(t,s),Qr(i)&&Bi(s,i)}Bi(s,n)}else{if(Xf(r.get(t),n))continue;r.set(t,n)}}var Zf=Symbol("urun:doc:local"),us=class{_doc=new Yr.Doc;_root=this._doc.getMap("session");_awareness=new qi.Awareness(this._doc);_listeners=new Set;_key;_sessionId;_connection=null;_connUnsub=null;_synced;_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();constructor(e,t,n){this._key=e,this._sessionId=t,this._root.observeDeep(this._observer),n?(this._connection=n(e,this._doc,this._awareness),this._synced=this._connection.synced,this._connUnsub=this._connection.onSync(s=>{s&&this._markSynced()}),this._synced&&this._markSynced()):this._synced=!0}get awareness(){return this._awareness}setSessionId(e){this._sessionId=e}get synced(){return this._synced}ensureConnected(){this._connection?.ensureConnected?.()}reconnect(){this.ensureConnected()}disconnect(){let e=this._connection;if(!e?.disconnect)throw new Error(`[urun-sh/core] doc('${this._key}').disconnect(): no disconnect-capable connection to sever (a local-only doc, or a connector with no live socket) \u2014 there is nothing to disconnect`);e.disconnect()}onConnectionState(e){return this._connection?.onConnectionState?this._connection.onConnectionState(e):(e({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){e=$i(e),this.applyPatch(e)}get(e,t){let n=this.snapshot();if(!e)return Kr(n);let s=Jf(n,e);return s===kd?t:Kr(s)}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new Hi(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._connUnsub?.(),this._connUnsub=null,this._connection?.destroy(),this._connection=null,this._listeners.clear(),this._syncWaiters.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._awareness.destroy(),this._doc.destroy()}_markSynced(){let e=[...this._syncWaiters];this._synced=!0,this._syncWaiters.clear();for(let t of e)t()}applyPatch(e){this._doc.transact(()=>{Bi(this._root,e)},Zf)}snapshot(){return this._root.toJSON()}notify(){let e=Kr(this.snapshot());for(let t of this._listeners)t(e)}},Hi=class{constructor(e){this._ytext=e;this._observer=t=>{for(let n of t.delta)if(typeof n.insert=="string"&&n.insert.length>0){let s=n.insert;for(let i of this._delta)i(s)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};function Td(r){return{get clientId(){return r.clientID},set(e){r.setLocalState(e)},setField(e,t){r.setLocalStateField(e,t)},getLocal(){return r.getLocalState()??null},getStates(){return r.getStates()},on(e,t){let n=()=>t(r.getStates());return r.on("change",n),n(),()=>r.off("change",n)}}}var Rd=1e3,Cd=12e3;function ls(r,e,t={}){let n=null,s=0,i=0,o=null,a=-1,c=()=>{let g=r.get("desired.billing.generationSeconds");if(typeof g!="number"||!Number.isFinite(g)||g<=0)return null;let _=r.get("desired.billing.epoch"),v=r.get("desired.billing.updatedAtMs");return{seconds:g,epoch:typeof _=="number"&&Number.isFinite(_)?_:0,updatedAtMs:typeof v=="number"&&Number.isFinite(v)?v:null}},u=()=>{if(n===null)return null;let g=Math.min(Math.max(0,Date.now()-s),i);return n+g/1e3},d=()=>{let g=t.creditsPerSecond;if(typeof g=="number"&&Number.isFinite(g)&&g>0)return g;let _=r.get("desired.billing.creditsPerSecond");return typeof _=="number"&&Number.isFinite(_)&&_>0?_:null},l=()=>{let g=u();if(g===null)return;let _=Math.floor(g);if(_<=a)return;a=_;let v={seconds:_},y=d();y!==null&&(v.estimatedCredits=_*y),e(v)},p=g=>{s=Date.now();let _=g===null?0:Math.max(0,s-g);i=Math.max(0,12e3-_)},f=()=>{let g=c();if(g!==null){if(o!==null&&g.epoch!==o){o=g.epoch,n=g.seconds,a=-1,p(g.updatedAtMs),l();return}n!==null&&g.seconds<=n||(o=g.epoch,n=g.seconds,p(g.updatedAtMs),l())}};f();let h=r.on("change",f),m=setInterval(l,1e3);return m.unref?.(),()=>{clearInterval(m),h()}}var Vi="activity",zi="visibility",Ed=15e3,ps=["pointerdown","pointermove","keydown","wheel","touchstart"];function hs(r){let e=r.now??Date.now,t=r.mode==="explicit",n=t?null:r.windowTarget!==void 0?r.windowTarget:typeof window<"u"?window:null,s=t?null:r.documentTarget!==void 0?r.documentTarget:typeof document<"u"?document:null,i=!1,o,a=()=>{if(i)return;let p=e();if(!(o!==void 0&&p-o<15e3)){o=p;try{r.awareness.setLocalStateField(Vi,{at:p})}catch{}}},c=()=>{if(!(i||!s||s.visibilityState===void 0))try{r.awareness.setLocalStateField(zi,s.visibilityState)}catch{}},u=()=>a(),d=()=>{c(),(!s||s.visibilityState===void 0||s.visibilityState==="visible")&&a()};if(n)for(let p of ps)n.addEventListener(p,u,{passive:!0,capture:!0});s&&s.addEventListener("visibilitychange",d);let l=null;return!t&&r.isProducing&&(l=setInterval(()=>{if(!i)try{r.isProducing?.()&&a()}catch{}},15e3),l.unref?.()),a(),c(),{touch:a,dispose(){if(!i){if(i=!0,n)for(let p of ps)n.removeEventListener(p,u,{capture:!0});s&&s.removeEventListener("visibilitychange",d),l&&(clearInterval(l),l=null)}}}}var Gi="user_activity",Ki="focus",Dd=3e4;function Pd(r){switch(r){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var ir=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(e={}){this._awareness=e.awareness??null,this._now=e.now??Date.now,this._win=e.windowTarget!==void 0?e.windowTarget:typeof window<"u"?window:null;let t=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null;this._win&&t&&typeof t.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(t.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(e){return this._stateHandlers.add(e),()=>this._stateHandlers.delete(e)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(e){if(this._disposed)return()=>{};this._setState(Pd(e.state));let t=e.on("stateChange",s=>{this._setState(Pd(s))}),n=()=>{t(),this._transportUnsubs.delete(n)};return this._transportUnsubs.add(n),n}_setState(e){if(!(this._disposed||e===this._state)){this._state=e;for(let t of this._stateHandlers)try{t(e)}catch{}}}interaction(e,t=1){this._disposed||!Number.isFinite(t)||t<=0||e==="pointer"&&this._focus==="unfocused"||(this._counts[e]+=t,this._signal())}consumerRead(e=1){this._disposed||!Number.isFinite(e)||e<=0||(this._counts.consumer_reads+=e,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let e=!1;return()=>{e||this._disposed||(e=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(e){this._disposed||(this._visibility=e)}setFocus(e){if(!(this._disposed||e===this._focus)){this._focus=e;try{this._awareness?.setLocalStateField(Ki,e)}catch{}}}_signal(){this._lastSignalAt=this._now();let e=this._lastPublishedAt===void 0?1/0:this._lastSignalAt-this._lastPublishedAt;if(e>=3e4){this._publishNow();return}if(this._trailing)return;let t=Math.max(3e4-e,0);this._trailing=setTimeout(()=>{this._trailing=null,this._disposed||this._publishNow()},t),this._trailing.unref?.()}_publishNow(){this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._lastPublishedAt=this._now();let e={at:this._lastSignalAt??this._lastPublishedAt,counts:{...this._counts},inflight:this._inflight};this._visibility!==void 0&&(e.visibility=this._visibility),this._focus!==void 0&&(e.focus=this._focus);try{this._awareness?.setLocalStateField(Gi,e)}catch{}}dispose(){if(!this._disposed){for(let e of Array.from(this._transportUnsubs))e();this._transportUnsubs.clear(),this._win&&(this._onWindowFocus&&this._win.removeEventListener("focus",this._onWindowFocus),this._onWindowBlur&&this._win.removeEventListener("blur",this._onWindowBlur)),this._onWindowFocus=null,this._onWindowBlur=null,this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._state="idle",this._stateHandlers.clear(),this._disposed=!0}}};var xd=250;function fs(r){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let n=Date.now();n-e<250||(e=n,r())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function ms(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=n=>{n.persisted||e||(e=!0,r())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function gs(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{r()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var Id="video/mp4";function _s(r,e={}){let t=e.timesliceMs??1e3,n=null,s=null,i=!1,o=(a,c,u)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let l=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(Id)?Id:void 0),p=new MediaStream([a]),f=new d(p,l?{mimeType:l}:void 0);n=f;let h=Promise.resolve();f.ondataavailable=m=>{let g=m.data;i||!g||g.size===0||(h=h.then(async()=>{let _=new Uint8Array(await g.arrayBuffer());i||c(_)}))},f.onstop=()=>{h.then(()=>{i||u()})},f.onerror=()=>{h.then(()=>{i||u()})},f.start(t)};return{start(a,c){if(n||i)return;let u=r.track();if(u){o(u,a,c);return}s=r.onTrack(d=>{!d||n||i||(s?.(),s=null,o(d,a,c))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function em(r){let e=r;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=r.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Ad(r,e){let t=null,n=!1,s=!1,i=new ReadableStream({pull(o){n||(n=!0,t=r(e),t.start(a=>{if(!s)try{o.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{o.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return em(i)}var vs=require("@msgpack/msgpack"),Qi=65536;function ws(r){let e=(0,vs.encode)(r),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var or=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(n>Qi)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+n)break;let s=this.buf.subarray(4,4+n);this.buf=this.buf.subarray(4+n),t.push((0,vs.decode)(s))}return t}},de=12,Yi=1,tm=0,ys=1,Ld=2;function ar(r){let e=r.getUint8(8);return{groupId:r.getUint32(0,!0),frameSeq:r.getUint32(4,!0),keyframe:(e&Yi)===Yi,fragIndex:r.getUint8(9),fragCount:r.getUint8(10),lane:r.getUint8(11)}}function bs(r){let e=new Uint8Array(de),t=new DataView(e.buffer);return t.setUint32(0,r.groupId,!0),t.setUint32(4,r.frameSeq,!0),t.setUint8(8,r.keyframe?Yi:0),t.setUint8(9,r.fragIndex),t.setUint8(10,r.fragCount),t.setUint8(11,r.lane??tm),e}var rm=100,Md=100,cr=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??rm}cb;pending=new Map;newestGroupSeen=-1;newestFrameDelivered=-1;needKeyframe=!0;kfRequestedAt=-1/0;now;debounceMs;bytesInWindow=0;framesDelivered=0;framesAbandoned=0;push(e){if(e.byteLength<de)return;let t=ar(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.isSourceRestart(t.groupId,t.frameSeq))this.resync(t.groupId);else if(t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let n=this.pending.get(t.frameSeq);if(n||(n={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n)),!n.chunks[t.fragIndex]){n.chunks[t.fragIndex]=e.subarray(de),n.received++,n.received===n.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,n));for(let s of this.pending.keys())s<t.frameSeq-1&&(this.pending.delete(s),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-Md?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-Md}resync(e){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let n=t.chunks.reduce((o,a)=>o+a.byteLength,0),s=new Uint8Array(n),i=0;for(let o of t.chunks)s.set(o,i),i+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:s})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var nm=/^avc[13]\.[0-9a-fA-F]{6}$/;function sm(r){return nm.test(r)?null:`codec ${JSON.stringify(r)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function Ji(r,e){let t=sm(r);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var Xi=1,Jr=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}if(this.name===null){if(this.buf.byteLength<2)return[];let n=this.buf[0];if(n!==Xi)throw new Error(`[urun] wt data stream: unknown header version 0x${n.toString(16)} \u2014 rejecting stream`);let s=this.buf[1];if(s===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+s)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+s)),this.buf=this.buf.subarray(2+s)}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+n)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let s=is(this.buf.subarray(4,4+n));this.buf=this.buf.subarray(4+n),s===mt&&(this.ended=!0),t.push({name:this.name,payload:s})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function Ss(r,e){let t=r.getReader();for(;;){let{value:n,done:s}=await t.read();if(s)return;n&&im(n,e).catch(i=>{e.onLaneError(i instanceof Error?i:new Error(String(i)))})}}async function im(r,e){let t=r.getReader(),n=new Jr;try{for(;;){let{value:s,done:i}=await t.read();if(i)break;if(!(!s||s.byteLength===0))for(let{name:o,payload:a}of n.push(s))e.onData(o,a)}n.finish()}catch(s){try{await t.cancel?.(s)}catch{}throw s}}var Zi=40,to=48e3,om=64,am=100,eo=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<de)return;let t=ar(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-am)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let n=this.pending.get(t.frameSeq);if(!n)for(n={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n);this.pending.size>om;){let a=1/0;for(let c of this.pending.keys())c<a&&(a=c);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=n.fragCount||n.chunks[t.fragIndex]||(n.chunks[t.fragIndex]=e.subarray(de),n.received++,n.received<n.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let s=n.chunks.reduce((a,c)=>a+(c?.byteLength??0),0),i=new Uint8Array(s),o=0;for(let a of n.chunks)i.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:n.timestamp,data:i})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},cm=3,dm=1e4,ks=class{constructor(e,t){this.config=e;this.seam=t;let n=this.seam.jitterBufferTargetMs??Zi;Number.isFinite(n)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${n} is not finite \u2014 using default ${Zi}ms`),n=Zi),this.targetS=Math.max(0,n)/1e3}config;seam;decoder=null;decoderErrorsAt=[];ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;deadCb=null;assembler=new eo(e=>this.decodeFrame(e));start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function"||typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.dest=this.ctx.createMediaStreamDestination();try{this.initDecoder(e)}catch(n){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,n}}onDead(e){this.deadCb=e}stop(){if(!this.stopped){this.stopped=!0,this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){this.decoder=new e({output:t=>this.schedule(t),error:t=>this.onDecoderError(t)}),this.decoder.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels})}decodeFrame(e){let t=globalThis.EncodedAudioChunk;!this.decoder||typeof t!="function"||this.stopped||this.decoder.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/to)),data:e.data}))}schedule(e){let t=this.ctx,n=this.dest;if(!t||!n||this.stopped){e.close();return}if(!this.trackSurfaced){this.trackSurfaced=!0,t.resume?.().catch(()=>{});let d=n.stream.getAudioTracks()[0];d&&this.seam.onTrack(d)}let s=e.numberOfFrames,i=Math.max(1,e.numberOfChannels),o=t.createBuffer(i,s,e.sampleRate);for(let d=0;d<i;d++){let l=new Float32Array(s);e.copyTo(l,{planeIndex:d,format:"f32-planar"}),o.copyToChannel(l,d)}let a=s/e.sampleRate;e.close();let c=t.createBufferSource();c.buffer=o,c.connect(n);let u=Math.max(this.playhead,t.currentTime+this.targetS);c.start(u),this.playhead=u+a}onDecoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(s=>t-s<dm),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=cm){let s=`audio decoder: ${e.message}`;console.warn(`[urun] WT audio lane dead (${s}) \u2014 audio reverts to the WebRTC track`),this.stop(),this.deadCb?.(s);return}console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let n=globalThis.AudioDecoder;typeof n=="function"&&this.initDecoder(n)}};var Xr=1200,um=3,lm=1e4;function pm(r){return Math.round(r*(to/1e6))%2**32>>>0}function ro(r,e,t,n,s){let i=n-de;if(i<=0)return null;let o=Math.max(1,Math.ceil(t.byteLength/i));if(o>255)return null;let a=[];for(let c=0;c<o;c++){let u=t.subarray(c*i,Math.min((c+1)*i,t.byteLength)),d=bs({groupId:e>>>0,frameSeq:r>>>0,keyframe:s?.keyframe??!0,fragIndex:c,fragCount:o,lane:s?.lane??ys}),l=new Uint8Array(de+u.byteLength);l.set(d,0),l.set(u,de),a.push(l)}return a}var Ts=class{constructor(e){this.sink=e}sink;encoder=null;encoderConfig=null;encoderErrorsAt=[];frameSeq=0;stopped=!1;deadCb=null;generation=0;cancelCapture=null;captureTrack=null;nodeBridge=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.captureTrack&&this.captureTrack.readyState==="live"||(this.teardownCapture(),e===null))return;let n=globalThis.MediaStreamTrackProcessor;if(typeof n!="function"){this.die("MediaStreamTrackProcessor is not available");return}let s;if(hm(e)){let c=e,u=c.context.createMediaStreamDestination();c.connect(u),this.nodeBridge={node:c,dest:u};let d=u.stream.getAudioTracks()[0];if(!d){this.die("AudioNode bridge produced no audio track");return}s=d}else s=e;let i=++this.generation,o=new n({track:s}).readable.getReader();this.captureTrack=s;let a=!1;this.cancelCapture=()=>{a=!0,o.cancel().catch(()=>{})},(async()=>{for(;!a&&!this.stopped&&i===this.generation;){let{value:c,done:u}=await o.read();if(u)break;if(c){if(a||this.stopped||i!==this.generation){c.close();break}this.encodeAudioData(c)}}!a&&!this.stopped&&i===this.generation&&(this.captureTrack=null)})().catch(c=>{!a&&!this.stopped&&i===this.generation&&this.die(`capture: ${c instanceof Error?c.message:String(c)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){if(this.cancelCapture?.(),this.cancelCapture=null,this.captureTrack=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}this.generation++}encodeAudioData(e){if(!this.encoder){let n=globalThis.AudioEncoder;if(typeof n!="function"){e.close(),this.die("AudioEncoder is not available");return}this.encoderConfig={sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels};try{this.initEncoder(n)}catch(s){e.close(),this.encoder=null,this.die(`encoder configure: ${s instanceof Error?s.message:String(s)}`);return}}let t=this.encoder;if(!t){e.close();return}try{t.encode(e)}catch(n){this.onEncoderError(n instanceof Error?n:new Error(String(n)))}e.close()}initEncoder(e){let t=this.encoderConfig;this.encoder=new e({output:n=>this.sendFrame(n),error:n=>this.onEncoderError(n)}),this.encoder.configure({codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3})}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let n=ro(this.frameSeq,pm(e.timestamp),t,this.sink.maxDatagramSize()||Xr);if(n===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let s of n)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(s=>t-s<lm),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=um){this.die(`audio encoder: ${e.message}`);return}console.warn("[urun] WT mic uplink encoder error \u2014 re-initializing the encoder:",e.message);try{this.encoder?.close()}catch{}this.encoder=null;let n=globalThis.AudioEncoder;if(!(typeof n!="function"||!this.encoderConfig))try{this.initEncoder(n)}catch(s){this.die(`encoder re-init: ${s instanceof Error?s.message:String(s)}`)}}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function hm(r){let e=r;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var fm=9e4,mm="avc1.42E01F",gm=60,_m=3,vm=1e4;function wm(r){return Math.round(r*(fm/1e6))%2**32>>>0}var Rs=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let n=globalThis.MediaStreamTrackProcessor;if(typeof n!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let s=++this.generation,i=new n({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,i.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&s===this.generation;){let{value:a,done:c}=await i.read();if(c)break;if(a){if(o||this.stopped||s!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&s===this.generation&&this.die(`capture: ${a instanceof Error?a.message:String(a)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(e){let t={width:e.codedWidth,height:e.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==t.width||this.encoderDims.height!==t.height){let i=globalThis.VideoEncoder;if(typeof i!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new i({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:mm,avc:{format:"annexb"},width:t.width,height:t.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(o){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${o instanceof Error?o.message:String(o)}`);return}}let s=this.keyframeWanted||this.framesSinceKeyframe>=gm;this.keyframeWanted=!1,this.framesSinceKeyframe=s?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:s})}catch(i){this.onEncoderError(i instanceof Error?i:new Error(String(i)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let n=ro(this.frameSeq,wm(e.timestamp),t,this.sink.maxDatagramSize()||Xr,{lane:Ld,keyframe:e.type==="key"});if(n===null){console.warn(`[urun] WT video uplink: AU of ${t.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let s of n)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(n=>t-n<vm),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=_m){this.die(`video encoder: ${e.message}`);return}console.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",e.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(e){this.stopped||(console.warn(`[urun] WT video uplink lane dead (${e}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function ym(r){return r.byteLength>=2&&r[0]===1&&r[1]===3}var Cs=class{constructor(e){this.transport=e}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(e){this.deadCb=e}send(e,t){let n=new TextEncoder().encode(e);if(n.byteLength===0||n.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${n.byteLength})`));let s=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let i=this.streams.get(e);if(!i){let a=await this.transport.openUniStream(),c=new Uint8Array(2+n.byteLength);c[0]=1,c[1]=n.byteLength,c.set(n,2),await a.write(c),i={writer:a},this.streams.set(e,i)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await i.writer.write(o),ym(t)&&(this.streams.delete(e),await i.writer.close().catch(()=>{}))}catch(i){throw this.die(i instanceof Error?i.message:String(i)),i}});return this.chain=s.catch(()=>{}),s}stop(e="stopped"){if(this.dead===null){this.dead=e;for(let t of this.streams.values())t.writer.close().catch(()=>{});this.streams.clear()}}die(e){this.dead===null&&(console.warn(`[urun] WT data uplink lane dead (${e})`),this.stop(e),this.deadCb?.(e))}};var no=250,bm=3,Sm=1e4,so=2500,km=25,Tm=2e3,dr=class{constructor(e,t,n,s,i,o,a){this.offer=e;this.sessionId=t;this.canvas=n;this.audioLane=s;this.audioUplink=i;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((c,u)=>{this.firstFrameResolve=c,this.firstFrameReject=u}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;reassembler=new cr({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;videoArrivedEver=!1;videoArrivalsInWindow=0;frameOutputEver=!1;frameOutputsInWindow=0;decodeStalledMs=0;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,n=t!==void 0&&t!=="";this.hasVideoLane=n,n&&Ji(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(d=>({algorithm:"sha-256",value:Uint8Array.from(atob(d),l=>l.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let s=await this.wt.createBidirectionalStream();this.writer=s.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let i=s.readable.getReader(),o=new or,a=[],c=await this.readControl(i,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");if(n&&(Ji(c.codec,"hello-ack"),this.initDecoder(c.codec,c.width,c.height)),this.offer.audio&&this.audioLane){let d=new ks(this.offer.audio,this.audioLane);d.onDead(()=>{this.audioPlayout=null});try{d.start(),this.audioPlayout=d}catch(l){console.warn(`[urun] WT audio lane failed to start (${l instanceof Error?l.message:String(l)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),d.stop()}}let u=()=>{this.datagramWriter();let d=0;return{send:l=>this.uplinkSend(l,()=>{d++}),delivered:()=>d,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??Xr}};if(this.offer.audioUp===!0&&this.audioUplink)try{let d=new Ts(u());d.onDead(l=>{this.audioUplinkLane=null,this.audioUplink.onUplinkLost(l)}),this.audioUplinkLane=d,this.audioUplink.onUplink(d)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT mic uplink failed to engage (${l}) \u2014 keeping the WT session; the mic stays on the WebRTC produce path`),this.audioUplink.onUplinkLost(l)}if(this.offer.videoUp===!0&&this.videoUplink)try{let d=new Rs(u());d.onDead(l=>{this.videoUplinkLane=null,this.videoUplink.onUplinkLost(l)}),this.videoUplinkLane=d,this.videoUplink.onUplink(d)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT video uplink failed to engage (${l}) \u2014 keeping the WT session; the camera stays on the WebRTC produce path`),this.videoUplink.onUplinkLost(l)}if(this.offer.dataUp===!0&&this.dataUplink)try{let d=this.wt.createUnidirectionalStream?.bind(this.wt);if(!d)throw new Error("WebTransport uni streams are not creatable in this environment");let l=new Cs({openUniStream:async()=>(await d()).getWriter()});l.onDead(p=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(p)}),this.dataUplinkSender=l,this.dataUplink.onUplink(l)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT data uplink failed to engage (${l}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(l)}this.controlLoop(i,o,a).catch(d=>this.die(`control loop: ${d}`)),this.datagramLoop().catch(d=>this.die(`datagram loop: ${d}`)),this.feedbackLoop(),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(d=>{this.closedReason=`connection error: ${d}`,this.die(`connection error: ${d}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${no}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let t=this.dataUplinkSender;t&&(this.dataUplinkSender=null,t.stop(e),this.dataUplink?.onUplinkLost(e))}dropDatagramUplinks(e){let t=this.audioUplinkLane;t&&(this.audioUplinkLane=null,t.stop(),this.audioUplink?.onUplinkLost(e));let n=this.videoUplinkLane;n&&(this.videoUplinkLane=null,n.stop(),this.videoUplink?.onUplinkLost(e))}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");this.dataLaneSink=e,Ss(this.wt.incomingUnidirectionalStreams,e).catch(t=>{this.die(`data lane: ${t instanceof Error?t.message:String(t)}`)})}initDecoder(e,t,n){let s=globalThis.VideoDecoder;if(typeof s!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:n},this.decoder=new s({output:o=>{this.frameOutputEver=!0,this.frameOutputsInWindow++,this.canvas.width=o.displayWidth,this.canvas.height=o.displayHeight,i.drawImage(o,0,0),o.close()},error:o=>this.onDecoderError(o)}),this.decoder.configure({codec:e,...t>0&&n>0?{codedWidth:t,codedHeight:n}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"})}onDecoderError(e){if(this.stopped||this.deadFired)return;let t=performance.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(s=>t-s<Sm),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=bm){this.die(`decoder: ${e.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let n=this.decoderConfig;if(!n){this.die(`decoder: ${e.message} (no config to re-init from)`);return}try{this.initDecoder(n.codec,n.width,n.height)}catch(s){this.die(`decoder re-init: ${s instanceof Error?s.message:String(s)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}evaluateDecodeLiveness(e,t){if(!this.videoArrivedEver)return!1;if(t>0)return this.decodeStalledMs=0,!1;if(e>0||!this.frameOutputEver)this.decodeStalledMs+=no;else return this.decodeStalledMs=0,!1;return this.decodeStalledMs<so?!1:(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${so}ms \u2014 broken WT media leg; failing over LOUDLY`),this.die(`decode-stall: datagrams flowing but nothing decoded within ${so}ms`),!0)}uplinkSend(e,t){if(this.stopped||this.deadFired)return;this.datagramWriter().write(e).then(t,s=>this.onUplinkSendError(s))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let t=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,console.error(`[urun] WT uplink datagram send FAILED (${t}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let n=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(s=>n-s<Tm),this.uplinkSendErrorsAt.push(n),!(this.uplinkSendErrorsAt.length<km)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:n}=await e.read();if(n)break;if(!t)continue;if(t.byteLength>=de&&t[11]===ys){this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;this.videoArrivedEver=!0,this.videoArrivalsInWindow++;let s=performance.now();if(this.lastArrivalTs>0){let i=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,n){let s=globalThis.EncodedVideoChunk;!this.decoder||typeof s!="function"||(this.decoder.decode(new s({type:t?"key":"delta",timestamp:e*(1e6/24),data:n})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}async sendControl(e){try{await this.writer.write(ws(e)),this.controlWritesAccepted++}catch(t){let n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),t}}async readControl(e,t,n=[]){for(;;){let s=n.shift();if(s)return s;let{value:i,done:o}=await e.read();if(o)return null;i&&n.push(...t.push(i))}}async controlLoop(e,t,n){for(;!this.stopped;){let s=await this.readControl(e,t,n);if(!s)break;s.t==="ping"&&(this.gatewayPings++,this.sendControl({t:"pong",ts:s.ts}).catch(()=>{})),s.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),n=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),i=this.videoArrivalsInWindow,o=this.frameOutputsInWindow;if(this.videoArrivalsInWindow=0,this.frameOutputsInWindow=0,this.evaluateDecodeLiveness(i,o))return;let a=s.delivered+s.abandoned;this.lastStats={recvBps:n>0?s.bytes*8/n:0,lossPct:a>0?100*s.abandoned/a:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},no)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var Od=2500,Ud=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Rm=1e4,ur=class{constructor(e,t,n){this.signaling=e;this.sessionId=t;this.opts=n}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",n=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,i={webtransport:t&&n&&s,webcodecs:n,codecs:Ud,wtData:t&&n&&s&&this.opts.dataLane!==void 0,wtAudio:t&&n&&s&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&n&&s&&this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtVideoUp:t&&n&&s&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&n&&s&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i});let o=i.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(c||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),i.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let u=null;try{return u=this.createWebTransportSession(),await io(u.start(),this.opts.quicDeadlineMs??Od,"quic connect deadline"),this.engageQuicDataLane(u,i.wtData===!0),this.session=u,c&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(d){if(u?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let l=String(d instanceof Error?d.message:d);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${l}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(l),d}console.warn("[urun] webtransport failed, falling back to webrtc:",d),this.proceedWebRtcDial(`wt failed: ${String(d instanceof Error?d.message:d)}`),this.notifyEstablished("webrtc",String(d instanceof Error?d.message:d))}}if(this.opts.allowWebRtcFallback===!1){let u=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${u} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(u),new Error(`[urun] WT required but unavailable: ${u}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let n=this.session,s=this.opts.dataLane!==void 0,i=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",o=this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",c=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:Ud,wtData:s,wtAudio:i,wtAudioUp:o,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;let u=this.createWebTransportSession();try{await io(u.start(),this.opts.quicDeadlineMs??Od,"quic connect deadline")}catch(d){throw u.stop().catch(()=>{}),d}if(this.session!==n)return u.stop().catch(()=>{}),null;try{this.engageQuicDataLane(u,s)}catch(d){throw u.stop().catch(()=>{}),d}this.session=u;{let d=this.offer.webtransport;d&&(this.opts.audioLane===void 0||d.audio!==void 0)&&(this.opts.audioUplink===void 0||d.audioUp===!0)&&(this.opts.videoUplink===void 0||d.videoUp===!0)&&(this.opts.dataLane===void 0||d.data===!0)&&(this.opts.dataUplink===void 0||d.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),n?.stop().catch(()=>{}),u}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let n=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(s,i)=>n.onData(s,i),onLaneError:s=>n.onLaneError(s)}),n.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new dr(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; retrying WT`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.opts.onWtRequiredOutage?.(t);return}let n=this.wtOnlyLeg;n&&this.proceedWebRtcDial(`failover: ${t}`),console.warn(n?"[urun] quic died mid-session on a WT-only leg (no RTCPeerConnection) \u2014 attempting a late WebRTC dial from scratch:":"[urun] quic died mid-session, failing over to webrtc:",t),this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),(async()=>{let s=this.createWebRtc();try{let i=await io(this.startWebRtcOn(s),this.opts.webRtcFailoverDeadlineMs??Rm,"webrtc failover produced no media transport");if(this.session!==e){i.stop().catch(()=>{});return}this.session=i,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(i){if(s.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=i instanceof Error?i.message:String(i),a=n?`media transport lost \u2014 the WebTransport connection dropped (${t}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;console.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function io(r,e,t){return new Promise((n,s)=>{let i=setTimeout(()=>s(new Error(t)),e);r.then(o=>{clearTimeout(i),n(o)},o=>{clearTimeout(i),s(o)})})}var Cm=1e4,lr=class{constructor(e,t=Cm){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let n=tr();return new Promise((s,i)=>{let o=setTimeout(()=>{a(),i(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==n)return;if(clearTimeout(o),a(),c.error){i(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:u,requestId:d,...l}=c;s(l)});this.carrier.sendSignal({type:e,requestId:n,...t})||(clearTimeout(o),a(),i(new Error(`[urun] signaling request not sent: ${e} \u2014 the signaling socket is not open`)))})}notify(e,t){this.carrier.sendSignal({type:e,...t})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${e} \u2014 the signaling socket is not open`,detail:{method:e}})}on(e,t){return this.carrier.onSignal(n=>{n.type===e&&t(n)})}};var Em="video",pr=class{constructor(e,t=Em){this.transport=e;this.streamName=t;this.firstMedia=new Promise((n,s)=>{this.firstMediaResolve=n,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let n=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(n(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(n)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};function Nd(r){let e=r;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var Pm="video";function Fd(r,e,t){let n=globalThis,s=n.document;if(!(typeof s?.createElement=="function"&&typeof n.WebTransport=="function"&&typeof n.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=r.holdWebRtcDial?.(),a=s.createElement("canvas"),c=!1,u=null,d=!1,l=()=>{if(u){for(let b of u.getVideoTracks())try{b.stop()}catch{}u=null}d&&(d=!1,t.onOverrideTrack(null))},p=new ur(new lr(r),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new pr(r,t.streamName??Pm)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(b,O)=>r.dispatchQuicStreamData(b,O),onQuicLane:()=>r.markStreamDataLaneQuic(),onQuicLaneLost:b=>r.quicStreamDataLaneLost(b),onLaneError:b=>r.raiseQuicStreamDataError(b)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:b=>{c||t.onOverrideAudioTrack(b)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>y(),onMediaTransportLost:b=>{c||(l(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(b),y())},onTransportChange:(b,O)=>{c||(b==="webrtc"&&(l(),y()),t.onTransportChange?.(b,O))}}),f=null,h=()=>{f!==null&&(clearInterval(f),f=null)},m=t.wtRetryBaseMs??2e3,g=t.wtRetryCapMs??3e4,_=null,v=0,y=()=>{if(c||_!==null||p.activeTransport==="webtransport")return;let b=Math.min(m*2**v,g);_=setTimeout(()=>{_=null,v+=1,p.retryWebTransport().then(O=>{if(c){O&&p.disconnect().catch(()=>{});return}if(O)return console.debug(`[urun] webtransport upgraded in background (retry ${v})`),v=0,w(O);y()}).catch(O=>{c||(console.debug(`[urun] webtransport background retry ${v} failed:`,O),y())})},b)},S=()=>{_!==null&&(clearTimeout(_),_=null)},w=async b=>{if(c||b.kind!=="webtransport")return;let O=t.pathHealthProbeMs??1e4;h();let j=!1;f=setInterval(()=>{if(c||p.activeTransport!=="webtransport")return;let $=Nd(b);if(!$){console.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),h();return}let ue=$.pathLiveness();if(!ue.alive){let te=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${ue.evidence}`+(te?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),h(),$.fail(`path health: ${ue.evidence}`);return}if(!j){if(j=!0,p.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${O}ms \u2014 the QUIC PATH IS HEALTHY (${ue.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}console.warn(`[urun] webtransport established but no QUIC media after ${O}ms \u2014 no media datagrams reached this client (path healthy: ${ue.evidence}); webrtc track remains authoritative`)}},O);try{await b.firstMedia}catch($){h(),console.debug("[urun] webtransport ended before any media flowed:",$);return}if(h(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;u=a.captureStream();let F=u.getVideoTracks()[0];F&&(d=!0,t.onOverrideTrack(F))};return(async()=>{let b=await p.connect();if(c){p.disconnect().catch(()=>{});return}await w(b)})().catch(b=>{if(h(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",b);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",b),y();return}o?.proceed(`negotiation unavailable: ${b instanceof Error?b.message:String(b)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",b),y()}),{activeTransport:()=>p.activeTransport,dispose(){c=!0,h(),S(),l(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var Dm=new Set;function co(r){if(r.functionsUrl)return{functionsUrl:r.functionsUrl,orgId:r.orgId,apiKey:r.apiKey,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}var xm="rpc",uo=3e4,Wd=3e4,Im="rpc-resp";function Am(r){return`${Im}:${r}`}function oo(){return tr()}function Lm(r){if(r&&typeof r=="object"){let e=r.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof r=="string"?r:JSON.stringify(r)}}function Mm(r,e,t,n,s,i,o,a,c,u){let d=[],l=null,p=!1,f=null,h=!1,m,g,_=new Promise((M,Ie)=>{m=M,g=Ie});_.catch(()=>{});let v=o(),y=null,S=null,w=null,b=null,O=null,j=null,F=!0,$=()=>{w&&(clearTimeout(w),w=null),b&&(b(),b=null)},ue=()=>{O&&(clearTimeout(O),O=null),j&&(j(),j=null)},te=!1,me=()=>{te||!h||(te=!0,r.set({rpc:{[e]:null}}))},xe=()=>{F=!1,$(),ue(),y?.(),y=null,S?.(),S=null,a?.removeEventListener("abort",N),v.dispose(),me()},je=()=>{if(l){if(d.length>0){let M=l;l=null,M.resolve({value:d.shift(),done:!1})}else if(f!==null){let M=l;l=null,M.reject(f)}else if(p){let M=l;l=null,M.resolve({value:void 0,done:!0})}}},_r=M=>{p||(d.push(M),je())},R=M=>{p||(f=M,p=!0,g(M),xe(),je())},L=M=>{p||(p=!0,m(M),xe(),je())},N=()=>{let M=a?.reason;R(M instanceof ke?M:new rt(e))},Q=M=>{if(!(p||!M||typeof M!="object"))switch(ue(),me(),M.t){case"delta":typeof M.delta=="string"&&_r(M.delta);break;case"response":L(M.body);break;case"error":{let{message:Ie,code:Ge}=Lm(M.body);R(new ke(Ie,{requestId:e,code:M.code??Ge}));break}}},U=()=>{let M=v.messages()[Symbol.asyncIterator]();y=()=>{M.return?.(void 0)};let Ie=()=>{F&&M.next().then(Ge=>{if(F){if(Ge.done){p||L(void 0);return}Q(Ge.value),Ie()}},Ge=>{F&&R(Ge)})};Ie()},I=()=>{if(!h){if(h=!0,a){if(a.aborted){R(new rt(e));return}a.addEventListener("abort",N,{once:!0})}S=c?.(M=>R(M))??null,U(),r.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:s,stream:i}}}),u&&u>0&&!r.synced&&(w=setTimeout(()=>{w=null,!p&&!r.synced&&R(new yt(u,e))},u),b=r.onSynced(()=>$())),j=r.onSynced(()=>{j=null,!(p||te||O)&&(O=setTimeout(()=>{O=null,!(p||te)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(Wd/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},Wd))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(I(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(f!==null){let M=f;return f=null,Promise.reject(M)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((M,Ie)=>{l={resolve:M,reject:Ie}})},return(){return p||(p=!0,m(void 0),xe()),Promise.resolve({value:void 0,done:!0})},throw(M){return p||(p=!0,g(M),xe()),Promise.reject(M)}}}},body:_,start:I}}function jd(r){if(r&&typeof r=="object"){let{epoch:e,by:t}=r,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function Om(r,e){let n=r.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:s,rt:i,br:o}=n,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=jd(i);c&&(a.rt=c);let u=jd(o);return u&&(a.br=u),a}var ao=class{constructor(e,t,n,s,i){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=s;this._onActivity=i;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],n=null,s=!1,i=null,o={push(c){if(!s)if(n){let u=n;n=null,u.resolve({value:c,done:!1})}else t.push(c)},end(){if(s=!0,n){let c=n;n=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{s=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||s)&&(i=e._streamConsumeUnavailableError(c),a(),n)){let u=n;n=null,u.reject(i)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):i?Promise.reject(i):s?Promise.resolve({value:void 0,done:!0}):new Promise((c,u)=>{n={resolve:c,reject:u}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,n=this._handlers.get("track");if(n)for(let s of n)s(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=Om(t,this._name),s=n?.br;if(s?.by==="runtime")throw new bt(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};n?.rt&&(i.rt=n.rt);let o=n?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??_s;return Ad(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let n of t)n(e)}},hr=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new as;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,n,s,i,o){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=Zc(n),this._wireControlDocIncarnation(),this._lifecycleUnsub=fs(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=hs({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new ir({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this._activation=new Rt({onPhase:a=>this.onPhase(a),hint:()=>this.doc(on).get(an)??this.doc("control").get(cn),onData:(a,c)=>this._streamData.onData(a,c)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let n=await Vo({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new vt,o=new sr({url:n.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new r(e,i,o,co(t),Rr({...t,baseUrl:n.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),o.setEndsAt(n.endsAt),et()&&await er();let c=t.getAccessToken,u=c?async()=>await c()??s:s;return a.setDocTransport({wsUrl:n.wsUrl,token:u}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return sn(this,e)}on(e,t){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(t),this._generationTickStop||(this._generationTickStop=ls(this.doc("control"),n=>{for(let s of Array.from(this._generationTickHandlers))try{s(n)}catch(i){console.warn("[urun] generationTick handler failed:",i)}})),()=>{this._generationTickHandlers.delete(t),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new ot(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,s)=>t.retain(n,s),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new Qe(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new Qe(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let n of this._docs.values())n.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new ao(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new us(e,this._sessionId,Dm.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Td(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}_autoTouch(){this._activityMode!=="explicit"&&this._activity?.touch()}activity(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=cs(e.wsUrl),n=typeof e.token=="function"?"<token-supplier>":e.token??"",s=`${t}\0${n}\0${this._sessionId}`;s!==this._docEndpointKey&&(this._docEndpointKey=s,this.connectDocs(Sd({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let n=oo(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let c=t.timeout;i=setTimeout(()=>s.abort(new wt(c,n)),c)}let o=this._consumeResponse(n,e,!1,s.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{i&&clearTimeout(i),a?.()})}_consumeResponse(e,t,n,s,i){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(xm),a=Am(e);return Mm(o,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??uo)}requestStream(e,t={}){let n=oo();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=oo(),s=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=Fd(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.detach(e.status==="paused"?e.reason:void 0),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new Ae)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Ae);let e=this._cancelHandler().then(t=>(this.disconnect(),t));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let t=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let s of t)try{s()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let n=Array.from(this._activeRequests);this._activeRequests.clear();for(let s of n)try{s(new kt)}catch{}for(let s of this._docs.values())s.dispose();this._docs.clear();for(let s of this._streams.values())s.dispose();this._streams.clear(),this._transport.disconnect(e)}};function qd(r){return`urun:session:v2:${r.orgId}:${r.app}:${r.functionName}`}function lo(){try{return globalThis.sessionStorage??null}catch{return null}}function po(r){let e=lo();if(!e)return null;try{let t=e.getItem(r);if(!t)return null;let n=JSON.parse(t);return typeof n?.sessionId!="string"||n.sessionId.length===0?null:{sessionId:n.sessionId}}catch{return null}}function $d(r,e){let t=lo();if(t)try{t.setItem(r,JSON.stringify({sessionId:e.sessionId}))}catch{}}function Es(r){let e=lo();if(e)try{e.removeItem(r)}catch{}}var Bd=new Set(["paused","acquiring","live"]),Um=new Set(["24h","keep"]);function Hd(r){if(typeof r!="string"||r.length===0)return null;let e=new Date(r);return Number.isFinite(e.getTime())?e:null}function Nm(r){if(typeof r?.id!="string"||r.id.length===0)throw new ge("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof r.state!="string"||!Bd.has(r.state))throw new ge(`[urun] session ${r.id} reported an unrecognized state ${JSON.stringify(r.state)} \u2014 this @urun-sh/core build knows only ${[...Bd].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});return{id:r.id,label:typeof r.label=="string"&&r.label.length>0?r.label:null,state:r.state,app:typeof r.app=="string"?r.app:"",functionName:typeof r.function=="string"?r.function:"",createdAt:Hd(r.created_at),lastActiveAt:Hd(r.last_active_at),archived:r.archived===!0,preview:typeof r.preview=="string"&&r.preview.length>0?r.preview:null,recordingsExpired:r.recordings_expired===!0,retention:Um.has(r.retention)?r.retention:(r.retention!==void 0&&console.warn(`[urun] session ${r.id} reported an unrecognized retention ${JSON.stringify(r.retention)} \u2014 defaulting to '24h'`),"24h")}}var fr=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:n}=await Bo({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(Nm),nextCursor:n}}async end(e){await Ho({...this._request,sessionId:e})}async archive(e){await Us({...this._request,sessionId:e,archived:!0})}async unarchive(e){await Us({...this._request,sessionId:e,archived:!1})}};var Fm=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function Vd(r,e){return new fr(r,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function zd(r,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,n){if(!(Fm.has(n)||typeof n!="string"))return(s,i)=>{let o=s??{},a=qd({orgId:e.orgId,app:r,functionName:n}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,u,d=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,l=d(),p=e.jwt,f=e.getAccessToken?async R=>{let L=await e.getAccessToken(R);return L&&(p=L),L}:void 0,h={...e,getAccessToken:f},m=new vt,g=new sr({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:l,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),_=new hr(l,m,g,co(h),Rr(h),{activity:i?.activity}),v,y=!1,S=!1,w,b,O=new Promise(R=>{b=R}),j,F=R=>{let L=R.sessionId?"session":"ticket";w&&!(w==="teardown"&&j==="ticket"&&L==="session")||(w="teardown",j=L,Sr({baseUrl:R.baseUrl,requestId:R.requestId,...R.sessionId?{sessionId:R.sessionId}:{},orgId:e.orgId,jwt:p,authProvider:e.authProvider}))},$=R=>{w||(w="abandon",Sr({baseUrl:R.baseUrl,requestId:R.requestId,...R.sessionId?{sessionId:R.sessionId}:{},orgId:e.orgId,jwt:p,authProvider:e.authProvider,...R.sessionId?{}:{reason:"client_abandoned"}}))},ue=R=>{let L=R.sessionId||!u?R:{...R,sessionId:u};v=L,b({status:"ready",handle:L}),(S||w==="teardown")&&F(L)};_.setEndHandler(async()=>{let R=v?{status:"ready",handle:v}:await O;if(R.status==="unavailable")throw new Ae("[urun] session allocation failed before a releasable request was created",{cause:R.cause});let L=v??R.handle;return Es(a),w==="teardown"?L.sessionId?{status:"paused",sessionId:L.sessionId,reason:"client_ended"}:{status:"canceled",requestId:L.requestId}:(w="end",L.sessionId?Ms({baseUrl:L.baseUrl,sessionId:L.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):Ls({baseUrl:L.baseUrl,requestId:L.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),_.setCancelHandler(async()=>{let R=v?{status:"ready",handle:v}:await O;if(R.status==="unavailable")throw new Ae("[urun] session allocation failed before a cancellable request was created",{cause:R.cause});let L=v??R.handle;if(L.sessionId)throw new re(`[urun] cancel() is for a queued admission request, but this call already has session ${L.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:L.sessionId,code:"cancel_on_live_session"});w="end";try{let N=await Ls({baseUrl:L.baseUrl,requestId:L.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return Es(a),N}catch(N){throw w==="end"&&(w=void 0),N}});let te=async R=>{let L=i?.sessionId??e.sessionKey??u,N=L===void 0&&!c?po(a)?.sessionId:void 0,Q=L??N,U=(M,Ie)=>$o({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,idempotencyKey:M,sessionKey:Ie,label:i?.label,priority:e.priority,onAdmission:Ge=>g.reportAdmission(Ge),onRequest:ue}),I;try{I=await U(R,Q)}catch(M){if(N===void 0||!(M instanceof z)||M.code!=="session_name_not_yours")throw M;po(a)?.sessionId===N&&Es(a),I=await U(d(),void 0)}let V=f?await f()??void 0:e.jwt;return u=I.sessionId,v&&v.sessionId!==I.sessionId&&ue({...v,sessionId:I.sessionId}),y||(e.sessionKey||$d(a,{sessionId:I.sessionId}),_.setSessionId(I.sessionId),_.setArtifactsAuth(Rr({...h,baseUrl:I.baseUrl})),g.setEndsAt(I.endsAt),g.seedRegion(Ns(I.response))),{url:I.wsUrl,sessionId:I.sessionId,jwt:V,iceServers:I.response.ice_servers,endsAt:I.endsAt}},me,xe=f?async()=>await f()??me:()=>me,je=()=>{let R=g.connectedUrl;return R?cs(R):void 0};if(g.setConnectionResolver(async()=>{let R=await te(d());return me=R.jwt,R}),g.on("connected",()=>{g.multiplexer&&m.setTarget(g.multiplexer);let R=g.connectedUrl;R&&_.setDocTransport({wsUrl:R,token:xe,resolveServerUrl:je})}),(async R=>{let L;try{L=await te(R)}catch(N){if(y){b({status:"unavailable",cause:N});return}console.error(`[urun] Failed to create session for ${n}:`,N),v&&$(v);let Q=N instanceof Error?N:new Error(String(N)),U=N instanceof z?N.httpStatus:void 0,I=N instanceof z?N.code:void 0,V=N instanceof z?N.retryAfterSeconds:void 0;g.reportAllocationFailure(Q,U,I,V),b({status:"unavailable",cause:N});return}y||(g.setAuth({jwt:L.jwt,authProvider:e.authProvider,orgId:e.orgId}),g.setConnection({url:L.url,sessionId:L.sessionId,iceServers:L.iceServers}),et()&&await er(),me=L.jwt,_.setDocTransport({wsUrl:L.url,token:xe,resolveServerUrl:je}),await g.connect({app:r,functionName:n,args:o}),_.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(l).catch(R=>{console.error(`[urun] Failed to connect session for ${n}:`,R)}),e.releaseOnLeave!==!1){let R=ms(()=>{if(y=!0,g.leaveLeg())return;if(g.connectedUrl!==null){g.disconnect();return}g.disconnect();let I=v;I?F(I):S=!0});_.onDisconnect(R);let L,N,Q=!1,U=()=>{Q||(Q=!0,L?.(),N?.())};O.then(I=>{I.status!=="ready"||Q||(L=gs(()=>v!==void 0))}),N=_.onPhase(I=>{let V=I?.name;(V==="paused"||V==="error")&&U()}),Q&&N(),_.onDisconnect(U)}return _}}})}var ho="https://api.urun.sh",fo="URUN_DEV";function Wm(){if(typeof process>"u")return!1;let r=process.env?.[fo];if(typeof r!="string")return!1;let e=r.trim().toLowerCase();return e==="1"||e==="true"}var tt=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Gd(r,e={}){if(!r)throw new tt("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,n=K(e.baseUrl??ho),s={};e.expiresIn!==void 0&&(s.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(s.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(s.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(s.max_session_s=e.maxSessionS),e.subject!==void 0&&(s.subject=e.subject),e.metadata!==void 0&&(s.metadata=e.metadata),(e.dev??Wm())&&(s.dev=!0);let i;try{i=await t(`${n}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(s)})}catch(p){throw new tt(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let o={};try{o=await i.json()}catch{}if(!i.ok){let p=typeof o.message=="string"?o.message:`HTTP ${i.status}`;throw new tt(`[urun] client token mint failed: ${p}`,i.status)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",u=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,d=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new tt("[urun] client token mint returned no token (control-plane contract violation)",i.status);let l=Number.isFinite(u)?new Date(u):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:l,orgId:c}}var Kd=3e4,Yd="stream:",mo=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",n=>{let s;try{s=JSON.parse(typeof n.data=="string"?n.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.resolve(s.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let n=`${Yd}${e}`;return this._multiplexer.on(n,s=>{t(s)})}emit(e,t){let n=`${Yd}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(n,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((n,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${Kd}ms`)))},Kd);this._pendingRpc.set(i,{resolve:n,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function Qd(r){let n=`${r.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(r.orgId)}`,s=new WebSocket(n);(r.jwt||r.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:r.orgId,jwt:r.jwt,authProvider:r.authProvider,apiKey:r.apiKey}))});let i=new _t(s);return new mo(s,i)}var jm='video/mp4; codecs="avc1.42E01E"';function Jd(r,e){let t=e?.codec??jm,n=document.createElement("video");n.muted=!0,n.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);n.src=i,s.addEventListener("sourceopen",()=>{let p;try{p=s.addSourceBuffer(t)}catch(g){throw g instanceof DOMException&&g.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):g}let f=r.getReader();function h(){return p.updating?new Promise(g=>{p.addEventListener("updateend",()=>g(),{once:!0})}):Promise.resolve()}async function m(){try{for(;;){let{done:g,value:_}=await f.read();if(g){await h(),s.readyState==="open"&&s.endOfStream();return}await h();try{p.appendBuffer(_)}catch(v){if(v instanceof DOMException&&v.name==="QuotaExceededError"){let y=p.buffered;if(y.length>0){let S=y.start(y.length-1);p.remove(0,S),await h(),p.appendBuffer(_)}else throw v}else throw v}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}m()}),n.play().catch(()=>{});let o=n,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(n),u=c.getTracks(),d=0,l=u.length;if(l===0)n.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{d++,d>=l&&URL.revokeObjectURL(i)});return c}function Xd(r){return r.status.startsWith("pending_")}var gt=class extends Error{status;code;constructor(e,t){super(e),this.name="CreditsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},mr=class extends gt{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function qm(r,e,t){let n=t||e||`HTTP ${r}`;return r===401?new mr(n,e??"unauthorized"):new gt(n,{status:r,code:e??`http_${r}`})}var Zr=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let e=await this._request("GET","/balance");if(!e||typeof e!="object"||typeof e.org_id!="string")throw new gt("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let n=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(n)?n:[]}async _request(e,t,n={}){let s=this._buildUrl(t,n.params),i=await this._resolveToken(),o=await this._fetch(s,e,i);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw qm(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(n+=`?${s}`),n}_fetch(e,t,n){let s={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:s})}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new mr("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:s,message:i}=n;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function Zd(r){return new Zr(r)}var en=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function eu(r){let e=[];return r.audio&&e.push("audio"),r.video&&e.push("video"),e.join("+")}function $m(r,e){return e==="audio"?r.getAudioTracks():r.getVideoTracks()}function Bm(r,e){let t=r.getTracks();if(t.length===1&&t[0]===e)return r;try{return new MediaStream([e])}catch{return r}}function go(r,e){for(let t of[...r.lostListeners])try{t(e)}catch{}}var tn=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let n=this.claims.get(e);n&&(this.claims.delete(e),n.released=!0,n.track=null,n.stream=null,go(n,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new en;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),n={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await t(n)}catch(o){let a=`one-capture getUserMedia(${eu(n)}) failed`,c=o instanceof Error?o.message:String(o);for(let u of[...this.claims.values()])if(this.claims.delete(u.kind),u.released=!0,u!==e){let d=new Error(`${a} \u2014 ${u.kind} capture lost: ${c||o}`);d.cause=o,go(u,d)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=$m(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${eu(n)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw c;go(o,c);continue}if(o.track=a,o.stream=Bm(s,a),o!==e)for(let c of[...o.trackListeners])try{c(a,o.stream)}catch{}}}createState(e,t){let n=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(i){return n.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=i,await n.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,n.claims.get(e)===s&&n.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(i){return s.trackListeners.add(i),()=>s.trackListeners.delete(i)},onLost(i){return s.lostListeners.add(i),()=>s.lostListeners.delete(i)}}};return s}},Hm=null;function tu(){return Hm??=new tn}var _o="input",ru=30;function nu(r){let e=r.now??Date.now,t=r.field??_o,n=1e3/Math.max(r.hz??30,.001),s=new Set,i=0,o=0,a=0,c=0,u,d=null,l=!1,p=()=>{if(l)return;u=e(),c+=1;let h={keys:[...s],buttons:i,pointer:{x:o,y:a},seq:c,at:u};try{r.awareness.setLocalStateField(t,h)}catch{}},f=()=>{if(l)return;let h=e();if(u===void 0||h-u>=n){d&&(clearTimeout(d),d=null),p();return}if(d)return;let m=Math.max(n-(h-u),0);d=setTimeout(()=>{d=null,p()},m),d.unref?.()};return{keyDown(h){let m=String(h).toLowerCase();s.has(m)||(s.add(m),f())},keyUp(h){let m=String(h).toLowerCase();s.delete(m)&&f()},setButtons(h){let m=Number.isFinite(h)?Number(h):0;m!==i&&(i=m,f())},movePointer(h,m){let g=Number.isFinite(h)?Number(h):0,_=Number.isFinite(m)?Number(m):0;g===0&&_===0||(o+=g,a+=_,f())},heldKeys(){return[...s]},clear(){l||(s.clear(),i=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(l)return;let h=s.size>0||i!==0;s.clear(),i=0,d&&(clearTimeout(d),d=null),h&&p(),l=!0}}}var ou=1024,au=.92,cu=262144,du=256e3,vo=[.9,.8,.7,.6,.5],su=.8,Vm=8;function Ps(r,e,t){if(!(r>0)||!(e>0))throw new Error(`reference image has no pixels (${r}x${e})`);let n=Math.min(1,t/Math.max(r,e));return{width:Math.max(1,Math.round(r*n)),height:Math.max(1,Math.round(e*n))}}async function zm(r){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(r,{imageOrientation:"from-image"})}async function uu(r,e,t){let n=await new Promise(s=>{r.toBlob(s,e,e==="image/jpeg"?t:void 0)});if(!n)throw new Error(`could not encode the reference image as ${e}`);return n}function iu(r,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${r} -> ${e} bytes`)}async function wo(r,e,t,n,s){let i=document.createElement("canvas");i.width=e,i.height=t;let o=i.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return n==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(r,0,0,e,t),await uu(i,n,s)}async function Gm(r,e,t,n){let{width:s,height:i}=e,o=await wo(r,s,i,t,n);if(o.size<=256e3)return{blob:o,width:s,height:i};if(t==="image/jpeg"){for(let c of vo)if(!(c>=n)&&(o=await wo(r,s,i,t,c),o.size<=256e3))return iu(`quality ${n} -> ${c}`,o.size),{blob:o,width:s,height:i}}let a=t==="image/jpeg"?vo[vo.length-1]:n;for(let c=0;c<Vm;c++)if(s=Math.max(16,Math.round(s*su)),i=Math.max(16,Math.round(i*su)),o=await wo(r,s,i,t,a),o.size<=256e3)return iu(`downscaled to ${s}x${i} @ q${a}`,o.size),{blob:o,width:s,height:i};throw new Error(`this image cannot be sent: even at ${s}x${i} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function lu(r,e){let{maxSize:t=1024,type:n="image/jpeg",quality:s=.92,source:i}=e,o=await zm(r);try{let a=Ps(o.width,o.height,t),c=await Gm(o,a,n,s);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:n,width:c.width,height:c.height,source:i}}finally{o.close()}}function pu(r){let e=r instanceof Error?r.name:"",t=r instanceof Error?r.message:String(r);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function hu(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function fu(r,e){let t=r.videoWidth,n=r.videoHeight;if(!(t>0)||!(n>0))throw new Error("the camera has not shown a frame yet");let{maxSize:s=1024,type:i="image/jpeg",quality:o=.92}=e??{},a=Ps(t,n,s),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let u=c.getContext("2d");if(!u)throw new Error("could not prepare the reference image (no 2d canvas context)");i==="image/jpeg"&&(u.fillStyle="#fff",u.fillRect(0,0,a.width,a.height)),u.drawImage(r,0,0,a.width,a.height);let d=await uu(c,i,o);return{bytes:new Uint8Array(await d.arrayBuffer()),type:i,width:a.width,height:a.height,source:"camera"}}var Km=new Set(["w","a","s","d"]),gr=(r,e)=>Math.min(e,Math.max(-e,r));function mu(r={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:n=.18,decayTauMs:s=900,frameRelax:i=.06,maxPan:o=.12,maxLogZoom:a=.22}=r,c=0,u=0,d=0,l=null,p=new Set;return{pointerDelta(f,h){c=gr(c-f*e,o),u=gr(u-h*e,o)},keyDown(f){let h=f.toLowerCase();Km.has(h)&&p.add(h)},keyUp(f){p.delete(f.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let f=1-i;c*=f,u*=f,d*=f},tick(f){if(l===null){l=f;return}let h=Math.max(0,Math.min(100,f-l))/1e3;l=f,p.has("w")&&(d=gr(d+t*h,a)),p.has("s")&&(d=gr(d-t*h,a)),p.has("a")&&(c=gr(c+n*h,o)),p.has("d")&&(c=gr(c-n*h,o));let m=Math.exp(-h*1e3/s);c*=m,u*=m,d*=m},transform(){return{translateX:c,translateY:u,scale:Math.exp(d)}},isIdentity(f=5e-4){return Math.abs(c)<f&&Math.abs(u)<f&&Math.abs(d)<f},reset(){c=0,u=0,d=0,p.clear()}}}0&&(module.exports={ACTIVATION_COLD_BOOT_AFTER_MS,ACTIVATION_DEGRADED_AFTER_MS,ACTIVATION_HINT_PATH,ACTIVATION_STILL_AFTER_MS,ACTIVITY_DOM_EVENTS,ACTIVITY_FIELD,ACTIVITY_STAMP_MIN_INTERVAL_MS,ActivationMonitor,App,BACKOFF_BASE_MS,BACKOFF_MAX_ATTEMPTS,BACKOFF_MAX_MS,CaptureController,CaptureUnavailableError,ClientTokenError,CreditsClient,CreditsError,CreditsUnauthorizedError,DATA_CHANNEL_MESSAGE_CEILING,DEFAULT_DOC_SYNC_TIMEOUT_MS,DEFAULT_GATEWAY_URL,DEFAULT_PRODUCE_ACK_TIMEOUT_MS,DEFAULT_REFERENCE_JPEG_QUALITY,DEFAULT_REFERENCE_MAX_SIZE,DEFAULT_WHEN_LIVE_TIMEOUT_MS,DERIVED_LEG_SEP,DGRAM_HEADER_BYTES,FOCUS_FIELD,FOREGROUND_COALESCE_MS,FrameReassembler,GENERATION_TICK_EMIT_INTERVAL_MS,GENERATION_TICK_MAX_EXTRAPOLATION_MS,INPUT_PRESENCE_DEFAULT_HZ,INPUT_PRESENCE_FIELD,InvalidDurationError,LEGACY_ACTIVATION_HINT_PATH,PLATFORM_DOC_NAME,PermanentLockedError,PinRequiresActiveTempError,PresenceTracker,ProduceAckTimeoutError,RecordingNotFoundError,RecordingsClient,RecordingsError,RecordingsUnauthorizedError,RequestAbortError,RequestCancelledError,RequestDocSyncError,RequestError,RequestTimeoutError,RetainNotTempError,RuntimeArtifactNotFoundError,RuntimeArtifactsClient,RuntimeArtifactsError,RuntimeArtifactsUnauthorizedError,SIGNALING_PROTOCOL_VERSION,STREAM_END,Session,SessionAllocationError,SessionDirectory,SessionDirectoryError,SessionEndError,SessionEndUnavailableError,SessionFailedError,StreamDirectionConflict,TransportNegotiator,TransportSessionMismatchError,TransportSessionSignaling,URUN_DEV_ENV,USER_ACTIVITY_FIELD,USER_ACTIVITY_MIN_INTERVAL_MS,VISIBILITY_FIELD,WIRE_MESSAGE_BUDGET,WT_CONTROL_FRAME_MAX,WT_DATA_STREAM_VERSION,WebRtcSession,WebTransportSession,WtControlDecoder,WtDataStreamParser,activationHintFrom,cameraCaptureAvailable,captureStillFromVideo,computeBackoffDelay,consumeWtDataStreams,createActivityTracker,createCameraWarp,createClientToken,createCreditsClient,createInputPresencePublisher,createRecordingsClient,createRuntimeArtifactsClient,createStore,decodeStreamEnvelope,derivedLegName,derivedLegRole,describeSessionFailure,describeSessionPhase,encodeStreamEnvelope,encodeWtControlFrame,fitWithin,isDurationString,isPausedPhase,isPendingRecording,isRetryableSessionError,isWakingPhase,mediaRecorderChunkSource,normalizeReferenceImage,normalizeRetention,observeLeaveConfirm,observePageLifecycle,observePageTeardown,parseDgramHeader,prewake,referenceImageErrorMessage,releaseSessionBeacon,sessionDirectory,sessionFailureFromMediaError,sharedCaptureController,videoStream,watchGenerationTick,whenLive,writeDgramHeader});
|
|
7
|
+
`}});var Ve=D(Fe=>{"use strict";var pt=ec(),Gp=rc(),Kp=Ln();Fe.grammar=Kp;Fe.write=Gp;Fe.parse=pt.parse;Fe.parseParams=pt.parseParams;Fe.parseFmtpConfig=pt.parseFmtpConfig;Fe.parsePayloads=pt.parsePayloads;Fe.parseRemoteCandidates=pt.parseRemoteCandidates;Fe.parseImageAttributes=pt.parseImageAttributes;Fe.parseSimulcastStreamList=pt.parseSimulcastStreamList});var ht=D(hi=>{"use strict";Object.defineProperty(hi,"__esModule",{value:!0});hi.parse=Qp;var Yp=new RegExp("^[LS]([1-9]\\d{0,1})T([1-9]\\d{0,1})");function Qp(r){let e=Yp.exec(r??"");return e?{spatialLayers:Number(e[1]),temporalLayers:Number(e[2])}:{spatialLayers:1,temporalLayers:1}}});var ic=D(Ze=>{"use strict";Object.defineProperty(Ze,"__esModule",{value:!0});Ze.OfferMediaSection=Ze.AnswerMediaSection=Ze.MediaSection=void 0;var Jp=Ve(),nc=dt(),Or=class{_mediaObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n}){if(this._mediaObject={type:"",port:0,protocol:"",payloads:"",rtp:[],fmtp:[]},e&&this.setIceParameters(e),t){this._mediaObject.candidates=[];for(let s of t){let i={foundation:s.foundation,component:1,ip:s.address??s.ip,port:s.port,priority:s.priority,transport:s.protocol,type:s.type};s.tcpType&&(i.tcptype=s.tcpType),this._mediaObject.candidates.push(i)}this._mediaObject.endOfCandidates="end-of-candidates",this._mediaObject.iceOptions="renomination"}n&&this.setDtlsRole(n.role)}get mid(){return String(this._mediaObject.mid)}get closed(){return this._mediaObject.port===0}getObject(){return this._mediaObject}setIceParameters(e){this._mediaObject.iceUfrag=e.usernameFragment,this._mediaObject.icePwd=e.password}pause(){this._mediaObject.direction="inactive"}disable(){this.pause()}close(){this.disable(),this._mediaObject.port=0,delete this._mediaObject.candidates,delete this._mediaObject.endOfCandidates,delete this._mediaObject.iceUfrag,delete this._mediaObject.icePwd,delete this._mediaObject.iceOptions,this._mediaObject.rtp=[],this._mediaObject.fmtp=[],delete this._mediaObject.rtcp,delete this._mediaObject.rtcpFb,delete this._mediaObject.ssrcs,delete this._mediaObject.ssrcGroups,delete this._mediaObject.simulcast,delete this._mediaObject.simulcast_03,delete this._mediaObject.rids,delete this._mediaObject.extmapAllowMixed}};Ze.MediaSection=Or;var fi=class extends Or{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n,sctpParameters:s,plainRtpParameters:i,offerMediaObject:o,offerRtpParameters:a,answerRtpParameters:c,codecOptions:u}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:n}),this._mediaObject.mid=String(o.mid),this._mediaObject.type=o.type,this._mediaObject.protocol=o.protocol,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},this._mediaObject.port=7),o.type){case"audio":case"video":{this._mediaObject.direction="recvonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[];for(let d of c.codecs){let l={payload:d.payloadType,codec:sc(d),rate:d.clockRate};d.channels>1&&(l.encoding=d.channels),this._mediaObject.rtp.push(l);let p=nc.clone(d.parameters)??{},f=nc.clone(d.rtcpFeedback)??[];if(u){let{opusStereo:m,opusFec:g,opusDtx:_,opusMaxPlaybackRate:v,opusMaxAverageBitrate:y,opusPtime:S,opusNack:w,videoGoogleStartBitrate:b,videoGoogleMaxBitrate:L,videoGoogleMinBitrate:q}=u,W=a.codecs.find(B=>B.payloadType===d.payloadType);switch(d.mimeType.toLowerCase()){case"audio/opus":case"audio/multiopus":{m!==void 0&&(W.parameters["sprop-stereo"]=m?1:0,p.stereo=m?1:0),g!==void 0&&(W.parameters.useinbandfec=g?1:0,p.useinbandfec=g?1:0),_!==void 0&&(W.parameters.usedtx=_?1:0,p.usedtx=_?1:0),v!==void 0&&(p.maxplaybackrate=v),y!==void 0&&(p.maxaveragebitrate=y),S!==void 0&&(W.parameters.ptime=S,p.ptime=S),w||(W.rtcpFeedback=W.rtcpFeedback.filter(B=>B.type!=="nack"||B.parameter),f=f.filter(B=>B.type!=="nack"||B.parameter));break}case"video/vp8":case"video/vp9":case"video/h264":case"video/h265":case"video/av1":{b!==void 0&&(p["x-google-start-bitrate"]=b),L!==void 0&&(p["x-google-max-bitrate"]=L),q!==void 0&&(p["x-google-min-bitrate"]=q);break}}}let h={payload:d.payloadType,config:""};for(let m of Object.keys(p))h.config&&(h.config+=";"),h.config+=`${m}=${p[m]}`;h.config&&this._mediaObject.fmtp.push(h);for(let m of f)this._mediaObject.rtcpFb.push({payload:d.payloadType,type:m.type,subtype:m.parameter})}this._mediaObject.payloads=c.codecs.map(d=>d.payloadType).join(" "),this._mediaObject.ext=[];for(let d of c.headerExtensions)(o.ext??[]).some(p=>p.uri===d.uri)&&this._mediaObject.ext.push({uri:d.uri,value:d.id});if(o.extmapAllowMixed==="extmap-allow-mixed"&&(this._mediaObject.extmapAllowMixed="extmap-allow-mixed"),o.simulcast){this._mediaObject.simulcast={dir1:"recv",list1:o.simulcast.list1},this._mediaObject.rids=[];for(let d of o.rids??[])d.direction==="send"&&this._mediaObject.rids.push({id:d.id,direction:"recv"})}else if(o.simulcast_03){this._mediaObject.simulcast_03={value:o.simulcast_03.value.replace(/send/g,"recv")},this._mediaObject.rids=[];for(let d of o.rids??[])d.direction==="send"&&this._mediaObject.rids.push({id:d.id,direction:"recv"})}this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";break}case"application":{typeof o.sctpPort=="number"?(this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=s.port,this._mediaObject.maxMessageSize=s.maxMessageSize):o.sctpmap&&(this._mediaObject.payloads=String(s.port),this._mediaObject.sctpmap={app:"webrtc-datachannel",sctpmapNumber:s.port,maxMessageSize:s.maxMessageSize});break}}}setDtlsRole(e){switch(e){case"client":{this._mediaObject.setup="active";break}case"server":{this._mediaObject.setup="passive";break}case"auto":{this._mediaObject.setup="actpass";break}}}resume(){this._mediaObject.direction="recvonly"}muxSimulcastStreams(e){if(!this._mediaObject.simulcast?.list1)return;let t={};for(let i of e)i.rid&&(t[i.rid]=i);let n=this._mediaObject.simulcast.list1,s=Jp.parseSimulcastStreamList(n);for(let i of s)for(let o of i)o.paused=!t[o.scid]?.active;this._mediaObject.simulcast.list1=s.map(i=>i.map(o=>`${o.paused?"~":""}${o.scid}`).join(",")).join(";")}};Ze.AnswerMediaSection=fi;var mi=class extends Or{constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n,sctpParameters:s,plainRtpParameters:i,mid:o,kind:a,offerRtpParameters:c,streamId:u,trackId:d}){switch(super({iceParameters:e,iceCandidates:t,dtlsParameters:n}),this._mediaObject.mid=String(o),this._mediaObject.type=a,i?(this._mediaObject.connection={ip:i.ip,version:i.ipVersion},this._mediaObject.protocol="RTP/AVP",this._mediaObject.port=i.port):(this._mediaObject.connection={ip:"127.0.0.1",version:4},s?this._mediaObject.protocol="UDP/DTLS/SCTP":this._mediaObject.protocol="UDP/TLS/RTP/SAVPF",this._mediaObject.port=7),this._mediaObject.extmapAllowMixed="extmap-allow-mixed",a){case"audio":case"video":{this._mediaObject.direction="sendonly",this._mediaObject.rtp=[],this._mediaObject.rtcpFb=[],this._mediaObject.fmtp=[],this._mediaObject.msid=[{id:u,appdata:d}];for(let h of c.codecs){let m={payload:h.payloadType,codec:sc(h),rate:h.clockRate};h.channels>1&&(m.encoding=h.channels),this._mediaObject.rtp.push(m);let g={payload:h.payloadType,config:""};for(let _ of Object.keys(h.parameters??{}))g.config&&(g.config+=";"),g.config+=`${_}=${h.parameters[_]}`;g.config&&this._mediaObject.fmtp.push(g);for(let _ of h.rtcpFeedback)this._mediaObject.rtcpFb.push({payload:h.payloadType,type:_.type,subtype:_.parameter})}this._mediaObject.payloads=c.codecs.map(h=>h.payloadType).join(" "),this._mediaObject.ext=[];for(let h of c.headerExtensions)this._mediaObject.ext.push({uri:h.uri,value:h.id});this._mediaObject.rtcpMux="rtcp-mux",this._mediaObject.rtcpRsize="rtcp-rsize";let l=c.encodings[0],p=l.ssrc,f=l.rtx?.ssrc;this._mediaObject.ssrcs=[],this._mediaObject.ssrcGroups=[],p&&c.rtcp.cname&&this._mediaObject.ssrcs.push({id:p,attribute:"cname",value:c.rtcp.cname}),f&&(c.rtcp.cname&&this._mediaObject.ssrcs.push({id:f,attribute:"cname",value:c.rtcp.cname}),p&&this._mediaObject.ssrcGroups.push({semantics:"FID",ssrcs:`${p} ${f}`}));break}case"application":{this._mediaObject.payloads="webrtc-datachannel",this._mediaObject.sctpPort=s.port,this._mediaObject.maxMessageSize=s.maxMessageSize;break}}}setDtlsRole(e){this._mediaObject.setup="actpass"}resume(){this._mediaObject.direction="sendonly"}};Ze.OfferMediaSection=mi;function sc(r){let t=new RegExp("^(audio|video)/(.+)","i").exec(r.mimeType);if(!t)throw new TypeError("invalid codec.mimeType");return t[2]}});var Kt=D(Un=>{"use strict";Object.defineProperty(Un,"__esModule",{value:!0});Un.RemoteSdp=void 0;var Xp=Ve(),Zp=ie(),Mn=ic(),eh=_i(),th=["av1","h264"],On=new Zp.Logger("RemoteSdp"),gi=class{_iceParameters;_iceCandidates;_dtlsParameters;_sctpParameters;_plainRtpParameters;_mediaSections=[];_midToIndex=new Map;_firstMid;_sdpObject;constructor({iceParameters:e,iceCandidates:t,dtlsParameters:n,sctpParameters:s,plainRtpParameters:i}){if(this._iceParameters=e,this._iceCandidates=t,this._dtlsParameters=n,this._sctpParameters=s,this._plainRtpParameters=i,this._sdpObject={version:0,origin:{address:"0.0.0.0",ipVer:4,netType:"IN",sessionId:"10000",sessionVersion:0,username:`media-client-v${eh.version}`},name:"-",timing:{start:0,stop:0},media:[]},this._sdpObject.iceOptions="ice2",e?.iceLite&&(this._sdpObject.icelite="ice-lite"),n){this._sdpObject.msidSemantic={semantic:"WMS",token:"*"};let o=this._dtlsParameters.fingerprints.length;this._sdpObject.fingerprint={type:n.fingerprints[o-1].algorithm,hash:n.fingerprints[o-1].value},this._sdpObject.groups=[{type:"BUNDLE",mids:""}]}i&&(this._sdpObject.origin.address=i.ip,this._sdpObject.origin.ipVer=i.ipVersion)}updateIceParameters(e){On.debug("updateIceParameters() [iceParameters:%o]",e),this._iceParameters=e,this._sdpObject.icelite=e.iceLite?"ice-lite":void 0;for(let t of this._mediaSections)t.setIceParameters(e)}updateDtlsRole(e){On.debug("updateDtlsRole() [role:%s]",e),this._dtlsParameters.role=e;for(let t of this._mediaSections)t.setDtlsRole(e)}setSessionExtmapAllowMixed(){On.debug("setSessionExtmapAllowMixed()"),this._sdpObject.extmapAllowMixed="extmap-allow-mixed"}getNextMediaSectionIdx(){for(let e=0;e<this._mediaSections.length;++e){let t=this._mediaSections[e];if(t.closed)return{idx:e,reuseMid:t.mid}}return{idx:this._mediaSections.length}}send({offerMediaObject:e,reuseMid:t,offerRtpParameters:n,answerRtpParameters:s,codecOptions:i}){let o=new Mn.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e,offerRtpParameters:n,answerRtpParameters:s,codecOptions:i}),a=o.getObject();a.rtp.find(u=>th.includes(u.codec.toLowerCase()))||(a.ext=a.ext?.filter(u=>u.uri!=="https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension")),t?this.replaceMediaSection(o,t):this._midToIndex.has(o.mid)?this.replaceMediaSection(o):this.addMediaSection(o)}receive({mid:e,kind:t,offerRtpParameters:n,streamId:s,trackId:i}){this.setSessionExtmapAllowMixed();let o=new Mn.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,plainRtpParameters:this._plainRtpParameters,mid:e,kind:t,offerRtpParameters:n,streamId:s,trackId:i}),a=this._mediaSections.find(c=>c.closed&&c.getObject().type===t);a?this.replaceMediaSection(o,a.mid):this.addMediaSection(o)}pauseMediaSection(e){this.findMediaSection(e).pause()}resumeSendingMediaSection(e){this.findMediaSection(e).resume()}resumeReceivingMediaSection(e){this.findMediaSection(e).resume()}disableMediaSection(e){this.findMediaSection(e).disable()}closeMediaSection(e){let t=this.findMediaSection(e);return e===this._firstMid?(On.debug("closeMediaSection() | cannot close first media section, disabling it instead [mid:%s]",e),this.disableMediaSection(e),!1):(t.close(),this.regenerateBundleMids(),!0)}muxMediaSectionSimulcast(e,t){let n=this.findMediaSection(e);n.muxSimulcastStreams(t),this.replaceMediaSection(n)}sendSctpAssociation({offerMediaObject:e}){let t=new Mn.AnswerMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,offerMediaObject:e});this.addMediaSection(t)}receiveSctpAssociation(){let e=new Mn.OfferMediaSection({iceParameters:this._iceParameters,iceCandidates:this._iceCandidates,dtlsParameters:this._dtlsParameters,sctpParameters:this._sctpParameters,plainRtpParameters:this._plainRtpParameters,mid:"datachannel",kind:"application"});this.addMediaSection(e)}getSdp(){return this._sdpObject.origin.sessionVersion++,Xp.write(this._sdpObject)}addMediaSection(e){this._firstMid||(this._firstMid=e.mid),this._mediaSections.push(e),this._midToIndex.set(e.mid,this._mediaSections.length-1),this._sdpObject.media.push(e.getObject()),this.regenerateBundleMids()}replaceMediaSection(e,t){if(typeof t=="string"){let n=this._midToIndex.get(t);if(n===void 0)throw new Error(`no media section found for reuseMid '${t}'`);let s=this._mediaSections[n];this._mediaSections[n]=e,this._midToIndex.delete(s.mid),this._midToIndex.set(e.mid,n),this._sdpObject.media[n]=e.getObject(),this.regenerateBundleMids()}else{let n=this._midToIndex.get(e.mid);if(n===void 0)throw new Error(`no media section found with mid '${e.mid}'`);this._mediaSections[n]=e,this._sdpObject.media[n]=e.getObject()}}findMediaSection(e){let t=this._midToIndex.get(e);if(t===void 0)throw new Error(`no media section found with mid '${e}'`);return this._mediaSections[t]}regenerateBundleMids(){this._dtlsParameters&&(this._sdpObject.groups[0].mids=this._mediaSections.filter(e=>!e.closed).map(e=>e.mid).join(" "))}};Un.RemoteSdp=gi});var Yt=D(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.extractRtpCapabilities=rh;ft.extractDtlsParameters=nh;ft.getCname=sh;ft.applyCodecParameters=ih;ft.addHeaderExtension=oh;var oc=Ve();function rh({sdpObject:r}){let e=new Map,t=new Map;for(let s of r.media){let i=s.type;switch(i){case"audio":case"video":break;default:continue}for(let o of s.rtp){let a={kind:i,mimeType:`${i}/${o.codec}`,preferredPayloadType:o.payload,clockRate:o.rate,channels:o.encoding,parameters:{},rtcpFeedback:[]};e.set(a.preferredPayloadType,a)}for(let o of s.fmtp??[]){let a=oc.parseParams(o.config),c=e.get(o.payload);c&&(a?.hasOwnProperty("profile-level-id")&&(a["profile-level-id"]=String(a["profile-level-id"])),c.parameters=a)}for(let o of s.rtcpFb??[]){let a={type:o.type,parameter:o.subtype};if(a.parameter||delete a.parameter,o.payload!=="*"){let c=e.get(Number(o.payload));if(!c)continue;c.rtcpFeedback.push(a)}else for(let c of e.values())c.kind===i&&!/.+\/rtx$/i.test(c.mimeType)&&c.rtcpFeedback.push(a)}for(let o of s.ext??[]){if(o["encrypt-uri"])continue;let a={kind:i,uri:o.uri,preferredId:o.value};t.set(a.preferredId,a)}}return{codecs:Array.from(e.values()),headerExtensions:Array.from(t.values())}}function nh({sdpObject:r}){let e=r.setup,t=r.fingerprint;if(!e||!t){let i=(r.media??[]).find(o=>o.port!==0);i&&(e=e??i.setup,t=t??i.fingerprint)}if(e){if(!t)throw new Error("no a=fingerprint found at SDP session or media level")}else throw new Error("no a=setup found at SDP session or media level");let n;switch(e){case"active":{n="client";break}case"passive":{n="server";break}case"actpass":{n="auto";break}}return{role:n,fingerprints:[{algorithm:t.type,value:t.hash}]}}function sh({offerMediaObject:r}){let e=(r.ssrcs??[]).find(t=>t.attribute==="cname");return e?e.value:""}function ih({offerRtpParameters:r,answerMediaObject:e}){for(let t of r.codecs){let n=t.mimeType.toLowerCase();if(n!=="audio/opus"||!(e.rtp??[]).find(a=>a.payload===t.payloadType))continue;e.fmtp=e.fmtp??[];let i=e.fmtp.find(a=>a.payload===t.payloadType);i||(i={payload:t.payloadType,config:""},e.fmtp.push(i));let o=oc.parseParams(i.config);if(n==="audio/opus"){let a=t.parameters?.["sprop-stereo"];a!==void 0&&(o.stereo=Number(a)?1:0)}i.config="";for(let a of Object.keys(o))i.config&&(i.config+=";"),i.config+=`${a}=${o[a]}`}}function oh({offerMediaObject:r,headerExtensionUri:e,headerExtensionId:t}){r.ext||(r.ext=[]),r.ext.push({uri:e,value:t})}});var Qt=D(Nn=>{"use strict";Object.defineProperty(Nn,"__esModule",{value:!0});Nn.getRtpEncodings=ah;Nn.addLegacySimulcast=ch;function ah({offerMediaObject:r,codecs:e}){let t=new Set;for(let i of r.ssrcs??[]){let o=i.id;o&&t.add(o)}if(t.size===0)throw new Error("no a=ssrc lines found");let n=new Map;for(let i of r.ssrcGroups??[]){if(i.semantics!=="FID")continue;let o=i.ssrcs.split(/\s+/),a=Number(o[0]),c=Number(o[1]);t.has(a)&&(t.delete(a),t.delete(c),n.set(a,c))}for(let i of t)n.set(i,void 0);let s=[];for(let[i,o]of n){let a={ssrc:i};o&&e.length>1&&(a.rtx={ssrc:o}),s.push(a)}return s}function ch({offerMediaObject:r,numStreams:e}){if(e<=1)throw new TypeError("numStreams must be greater than 1");let t=(r.ssrcs??[]).find(l=>l.attribute==="msid");if(!t)throw new Error("a=ssrc line with msid information not found");let[n,s]=t.value.split(" "),i=Number(t.id),o;(r.ssrcGroups??[]).some(l=>{if(l.semantics!=="FID")return!1;let p=l.ssrcs.split(/\s+/);return Number(p[0])===i?(o=Number(p[1]),!0):!1});let a=(r.ssrcs??[]).find(l=>l.attribute==="cname");if(!a)throw new Error("a=ssrc line with cname information not found");let c=a.value,u=[],d=[];for(let l=0;l<e;++l)u.push(i+l),o&&d.push(o+l);r.ssrcGroups=[],r.ssrcs=[],r.ssrcGroups.push({semantics:"SIM",ssrcs:u.join(" ")});for(let l of u)r.ssrcs.push({id:l,attribute:"cname",value:c}),r.ssrcs.push({id:l,attribute:"msid",value:`${n} ${s}`});for(let l=0;l<d.length;++l){let p=u[l],f=d[l];r.ssrcs.push({id:f,attribute:"cname",value:c}),r.ssrcs.push({id:f,attribute:"msid",value:`${n} ${s}`}),r.ssrcGroups.push({semantics:"FID",ssrcs:`${p} ${f}`})}}});var Jt=D(Ur=>{"use strict";Object.defineProperty(Ur,"__esModule",{value:!0});Ur.addNackSupportForOpus=dh;Ur.addHeaderExtensionSupport=uh;Ur.getMsidStreamIdAndTrackId=lh;function dh(r){for(let e of r.codecs??[])(e.mimeType.toLowerCase()==="audio/opus"||e.mimeType.toLowerCase()==="audio/multiopus")&&!e.rtcpFeedback?.some(t=>t.type==="nack"&&!t.parameter)&&(e.rtcpFeedback||(e.rtcpFeedback=[]),e.rtcpFeedback.push({type:"nack"}))}function uh(r,e){let t,n=r.headerExtensions?.find(i=>i.uri===e.uri);if(n){if(n.kind===e.kind)return;t=n.preferredId}if(r.headerExtensions||(r.headerExtensions=[]),t===void 0){t=1;let i=new Set(r.headerExtensions.map(o=>o.preferredId));for(;i.has(t);)++t}let s={kind:e.kind,uri:e.uri,preferredId:t,preferredEncrypt:!1,direction:e.direction};r.headerExtensions.push(s)}function lh(r){if(!r||typeof r!="string")return{msidStreamId:void 0,msidTrackId:void 0};let[e,t]=r.trim().split(/\s+/);return e?{msidStreamId:e,msidTrackId:t}:{msidStreamId:void 0,msidTrackId:void 0}}});var uc=D(Fn=>{"use strict";Object.defineProperty(Fn,"__esModule",{value:!0});Fn.Chrome111=void 0;var We=Ve(),ph=he(),hh=ie(),Nr=Oe(),fh=ye(),mh=ht(),gh=Kt(),Fr=Yt(),ac=Qt(),vi=Jt(),I=new hh.Logger("Chrome111"),cc="Chrome111",dc={OS:65535,MIS:65535},wi=class r extends ph.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:cc,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{I.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e,sendEncodings:[{scalabilityMode:"L3T3"}]});let n=await t.createOffer();try{t.close()}catch{}t=void 0;let s=We.parse(n.sdp);return r.getLocalRtpCapabilities(s)}catch(n){try{t?.close()}catch{}throw t=void 0,n}},getNativeSctpCapabilities:async()=>(I.debug("getNativeSctpCapabilities()"),{numStreams:dc})}}static getLocalRtpCapabilities(e,t=[]){let n=Fr.extractRtpCapabilities({sdpObject:e});Nr.validateAndNormalizeRtpCapabilities(n),vi.addNackSupportForOpus(n);for(let s of t)vi.addHeaderExtensionSupport(n,s);return n}constructor({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:u}){super(),I.debug("constructor()"),this._direction=e,this._remoteSdp=new gh.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=u,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(I.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return cc}close(){if(I.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),I.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),I.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});I.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let n={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();I.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:n,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){if(this.assertNotClosed(),this.assertSendDirection(),I.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),n&&n.length>1){let S=1;for(let w of n){let b=w.scalabilityMode?(0,mh.parse)(w.scalabilityMode).temporalLayers:3;b>S&&(S=b)}n.forEach((w,b)=>{w.rid=`r${b}`,w.scalabilityMode=`L1T${S}`})}let c=this._remoteSdp.getNextMediaSectionIdx(),u=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:n});a&&a(u.sender);let d=await this._pc.createOffer(),l=We.parse(d.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=r.getLocalRtpCapabilities(l,p),h=this._getSendExtendedRtpCapabilities(f),m=Nr.getSendingRtpParameters(e.kind,h);m.codecs=Nr.reduceCodecs(m.codecs,o);let g=Nr.getSendingRemoteRtpParameters(e.kind,h);if(g.codecs=Nr.reduceCodecs(g.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l}),i?.absCaptureTime){let S=l.media[c.idx];Fr.addHeaderExtension({offerMediaObject:S,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(w=>w.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:We.write(l)}}I.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let _=u.mid;m.mid=_,l=We.parse(this._pc.localDescription.sdp);let v=l.media[c.idx];if(m.rtcp.cname=Fr.getCname({offerMediaObject:v}),m.msid=`${t??this._sendStream.id} ${e.id}`,!n)m.encodings=ac.getRtpEncodings({offerMediaObject:v,codecs:m.codecs});else if(n.length===1){let S=ac.getRtpEncodings({offerMediaObject:v,codecs:m.codecs});Object.assign(S[0],n[0]),m.encodings=S}else m.encodings=n;this._remoteSdp.send({offerMediaObject:v,reuseMid:c.reuseMid,offerRtpParameters:m,answerRtpParameters:g,codecOptions:s});let y={type:"answer",sdp:this._remoteSdp.getSdp()};return I.debug("send() | calling pc.setRemoteDescription() [answer:%o]",y),await this._pc.setRemoteDescription(y),this._mapMidTransceiver.set(_,u),{localId:_,rtpParameters:m,rtpSender:u.sender}}async stopSending(e){if(this.assertSendDirection(),I.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();I.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),I.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let n=await this._pc.createOffer();I.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),I.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let n=await this._pc.createOffer();I.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?I.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):I.debug("replaceTrack() [localId:%s, no track]",e);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),I.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();I.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),I.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();I.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};I.debug("sendDataChannel() [options:%o]",t);let n=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%dc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=We.parse(i.sdp),a=o.media.find(u=>u.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),I.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};I.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:n,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],n=new Map;for(let a of e){let{trackId:c,kind:u,rtpParameters:d,streamId:l}=a;I.debug("receive() [trackId:%s, kind:%s]",c,u);let p=d.mid??String(this._mapMidTransceiver.size);n.set(c,p);let{msidStreamId:f}=vi.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:u,offerRtpParameters:d,streamId:l??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:u}=a;if(u){let d=n.get(c),l=this._pc.getTransceivers().find(p=>p.mid===d);if(!l)throw new Error("transceiver not found");u(l.receiver)}}let i=await this._pc.createAnswer(),o=We.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:u}=a,d=n.get(c),l=o.media.find(p=>String(p.mid)===d);Fr.applyCodecParameters({offerRtpParameters:u,answerMediaObject:l})}i={type:"answer",sdp:We.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),I.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,u=n.get(c),d=this._pc.getTransceivers().find(l=>l.mid===u);if(d)this._mapMidTransceiver.set(u,d),t.push({localId:u,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){I.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();I.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){I.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();I.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){I.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();I.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:n,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};I.debug("receiveDataChannel() [options:%o]",u);let d=this._pc.createDataChannel(n,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};I.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let p=await this._pc.createAnswer(),f=We.parse(p.sdp),h=f.media.find(m=>m.type==="application");h.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:We.write(f)},I.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=We.parse(this._pc.localDescription.sdp));let n=Fr.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:n},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new fh.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};Fn.Chrome111=wi});var hc=D(Wn=>{"use strict";Object.defineProperty(Wn,"__esModule",{value:!0});Wn.Chrome74=void 0;var be=Ve(),_h=ie(),vh=he(),Wr=Oe(),wh=ye(),yh=ht(),bh=Kt(),jr=Yt(),yi=Qt(),bi=Jt(),E=new _h.Logger("Chrome74"),lc="Chrome74",pc={OS:1024,MIS:1024},Si=class r extends vh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:lc,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{E.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let n=await t.createOffer();try{t.close()}catch{}t=void 0;let s=be.parse(n.sdp);return r.getLocalRtpCapabilities(s)}catch(n){try{t?.close()}catch{}throw t=void 0,n}},getNativeSctpCapabilities:async()=>(E.debug("getNativeSctpCapabilities()"),{numStreams:pc})}}static getLocalRtpCapabilities(e,t=[]){let n=jr.extractRtpCapabilities({sdpObject:e});Wr.validateAndNormalizeRtpCapabilities(n),bi.addNackSupportForOpus(n);for(let s of t)bi.addHeaderExtensionSupport(n,s);return n}constructor({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:u}){super(),E.debug("constructor()"),this._direction=e,this._remoteSdp=new bh.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=u,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(E.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return lc}close(){if(E.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),E.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),E.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});E.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let n={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();E.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:n,codecOptions:s,headerExtensionOptions:i,codec:o}){this.assertNotClosed(),this.assertSendDirection(),E.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),n&&n.length>1&&n.forEach((w,b)=>{w.rid=`r${b}`});let a=this._remoteSdp.getNextMediaSectionIdx(),c=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:n}),u=await this._pc.createOffer(),d=be.parse(u.sdp);d.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let l=[];l.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let p=r.getLocalRtpCapabilities(d,l),f=this._getSendExtendedRtpCapabilities(p),h=Wr.getSendingRtpParameters(e.kind,f);h.codecs=Wr.reduceCodecs(h.codecs,o);let m=Wr.getSendingRemoteRtpParameters(e.kind,f);m.codecs=Wr.reduceCodecs(m.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:d});let g=!1,_=(0,yh.parse)((n??[{}])[0].scalabilityMode),v;n?.length===1&&_.spatialLayers>1&&h.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(E.debug("send() | enabling legacy simulcast for VP9 SVC"),g=!0,d=be.parse(u.sdp),v=d.media[a.idx],yi.addLegacySimulcast({offerMediaObject:v,numStreams:_.spatialLayers}),u={type:"offer",sdp:be.write(d)}),E.debug("send() | calling pc.setLocalDescription() [offer:%o]",u),i?.absCaptureTime&&(v=d.media[a.idx],jr.addHeaderExtension({offerMediaObject:v,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:m.headerExtensions.find(w=>w.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),u={type:"offer",sdp:be.write(d)}),await this._pc.setLocalDescription(u);let y=c.mid;if(h.mid=y,d=be.parse(this._pc.localDescription.sdp),v=d.media[a.idx],h.rtcp.cname=jr.getCname({offerMediaObject:v}),h.msid=`${t??this._sendStream.id} ${e.id}`,!n)h.encodings=yi.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});else if(n.length===1){let w=yi.getRtpEncodings({offerMediaObject:v,codecs:h.codecs});Object.assign(w[0],n[0]),g&&(w=[w[0]]),h.encodings=w}else h.encodings=n;if(h.encodings.length>1&&(h.codecs[0].mimeType.toLowerCase()==="video/vp8"||h.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let w of h.encodings)w.scalabilityMode?w.scalabilityMode=`L1T${_.temporalLayers}`:w.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:v,reuseMid:a.reuseMid,offerRtpParameters:h,answerRtpParameters:m,codecOptions:s});let S={type:"answer",sdp:this._remoteSdp.getSdp()};return E.debug("send() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.set(y,c),{localId:y,rtpParameters:h,rtpSender:c.sender}}async stopSending(e){if(this.assertSendDirection(),E.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();E.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),E.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let n=await this._pc.createOffer();E.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),E.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let n=await this._pc.createOffer();E.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?E.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):E.debug("replaceTrack() [localId:%s, no track]",e);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),E.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();E.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),E.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();E.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};E.debug("sendDataChannel() [options:%o]",t);let n=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%pc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=be.parse(i.sdp),a=o.media.find(u=>u.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),E.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};E.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:n,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],n=new Map;for(let a of e){let{trackId:c,kind:u,rtpParameters:d,streamId:l}=a;E.debug("receive() [trackId:%s, kind:%s]",c,u);let p=d.mid??String(this._mapMidTransceiver.size);n.set(c,p);let{msidStreamId:f}=bi.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:u,offerRtpParameters:d,streamId:l??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);let i=await this._pc.createAnswer(),o=be.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:u}=a,d=n.get(c),l=o.media.find(p=>String(p.mid)===d);jr.applyCodecParameters({offerRtpParameters:u,answerMediaObject:l})}i={type:"answer",sdp:be.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),E.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,u=n.get(c),d=this._pc.getTransceivers().find(l=>l.mid===u);if(d)this._mapMidTransceiver.set(u,d),t.push({localId:u,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){E.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();E.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){E.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();E.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){E.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();E.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:n,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};E.debug("receiveDataChannel() [options:%o]",u);let d=this._pc.createDataChannel(n,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};E.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let p=await this._pc.createAnswer(),f=be.parse(p.sdp),h=f.media.find(m=>m.type==="application");h.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:be.write(f)},E.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=be.parse(this._pc.localDescription.sdp));let n=jr.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:n},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new wh.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};Wn.Chrome74=Si});var vc=D(qn=>{"use strict";Object.defineProperty(qn,"__esModule",{value:!0});qn.Firefox120=void 0;var ze=Ve(),Sh=he(),kh=ie(),fc=ye(),qr=Oe(),Th=ht(),Rh=Kt(),jn=Yt(),mc=Qt(),Ch=Jt(),A=new kh.Logger("Firefox120"),gc="Firefox120",_c={OS:16,MIS:2048},ki=class r extends Sh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:gc,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{A.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"}),n=document.createElement("canvas");n.getContext("2d");let i=n.captureStream().getVideoTracks()[0];try{t.addTransceiver("audio",{direction:e}),t.addTransceiver(i,{direction:e,sendEncodings:[{rid:"r0",maxBitrate:1e5},{rid:"r1",maxBitrate:5e5}]});let o=await t.createOffer();try{n.remove()}catch{}try{i.stop()}catch{}try{t.close()}catch{}t=void 0;let a=ze.parse(o.sdp);return r.getLocalRtpCapabilities(a)}catch(o){try{n.remove()}catch{}try{i.stop()}catch{}try{t?.close()}catch{}throw t=void 0,o}},getNativeSctpCapabilities:async()=>(A.debug("getNativeSctpCapabilities()"),{numStreams:_c})}}static getLocalRtpCapabilities(e){let t=jn.extractRtpCapabilities({sdpObject:e});return qr.validateAndNormalizeRtpCapabilities(t),t}constructor({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:u}){super(),A.debug("constructor()"),this._direction=e,this._remoteSdp=new Rh.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=u,this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(A.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return gc}close(){if(A.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){throw this.assertNotClosed(),new fc.UnsupportedError("not supported")}async restartIce(e){if(this.assertNotClosed(),A.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});A.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let n={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();A.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:n,codecOptions:s,codec:i,onRtpSender:o}){this.assertNotClosed(),this.assertSendDirection(),A.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),n&&n.length>1&&n.forEach((v,y)=>{v.rid=`r${y}`});let a=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:n});o&&o(a.sender);let c=await this._pc.createOffer(),u=ze.parse(c.sdp);u.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let d=r.getLocalRtpCapabilities(u),l=this._getSendExtendedRtpCapabilities(d),p=qr.getSendingRtpParameters(e.kind,l);p.codecs=qr.reduceCodecs(p.codecs,i);let f=qr.getSendingRemoteRtpParameters(e.kind,l);f.codecs=qr.reduceCodecs(f.codecs,i),this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:u});let h=(0,Th.parse)((n??[{}])[0].scalabilityMode);A.debug("send() | calling pc.setLocalDescription() [offer:%o]",c),await this._pc.setLocalDescription(c);let m=a.mid;p.mid=m,u=ze.parse(this._pc.localDescription.sdp);let g=u.media[u.media.length-1];if(p.rtcp.cname=jn.getCname({offerMediaObject:g}),p.msid=`${t??this._sendStream.id} ${e.id}`,!n)p.encodings=mc.getRtpEncodings({offerMediaObject:g,codecs:p.codecs});else if(n.length===1){let v=mc.getRtpEncodings({offerMediaObject:g,codecs:p.codecs});Object.assign(v[0],n[0]),p.encodings=v}else p.encodings=n;if(p.encodings.length>1&&(p.codecs[0].mimeType.toLowerCase()==="video/vp8"||p.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let v of p.encodings)v.scalabilityMode?v.scalabilityMode=`L1T${h.temporalLayers}`:v.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:g,offerRtpParameters:p,answerRtpParameters:f,codecOptions:s});let _={type:"answer",sdp:this._remoteSdp.getSdp()};return A.debug("send() | calling pc.setRemoteDescription() [answer:%o]",_),await this._pc.setRemoteDescription(_),this._mapMidTransceiver.set(m,a),{localId:m,rtpParameters:p,rtpSender:a.sender}}async stopSending(e){if(this.assertSendDirection(),A.debug("stopSending() [localId:%s]",e),this._closed)return;let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated transceiver not found");t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.disableMediaSection(t.mid);let n=await this._pc.createOffer();A.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),A.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let n=await this._pc.createOffer();A.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),A.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let n=await this._pc.createOffer();A.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?A.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):A.debug("replaceTrack() [localId:%s, no track]",e);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),A.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated transceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();A.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),A.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();A.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};A.debug("sendDataChannel() [options:%o]",t);let n=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%_c.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=ze.parse(i.sdp),a=o.media.find(u=>u.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),A.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};A.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:n,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],n=new Map;for(let a of e){let{trackId:c,kind:u,rtpParameters:d,streamId:l}=a;A.debug("receive() [trackId:%s, kind:%s]",c,u);let p=d.mid??String(this._mapMidTransceiver.size);n.set(c,p);let{msidStreamId:f}=Ch.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:u,offerRtpParameters:d,streamId:l??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:u}=a;if(u){let d=n.get(c),l=this._pc.getTransceivers().find(p=>p.mid===d);if(!l)throw new Error("transceiver not found");u(l.receiver)}}let i=await this._pc.createAnswer(),o=ze.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:u}=a,d=n.get(c),l=o.media.find(p=>String(p.mid)===d);jn.applyCodecParameters({offerRtpParameters:u,answerMediaObject:l}),i={type:"answer",sdp:ze.write(o)}}this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:o}),A.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,u=n.get(c),d=this._pc.getTransceivers().find(l=>l.mid===u);if(!d)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(u,d),t.push({localId:u,track:d.receiver.track,rtpReceiver:d.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){A.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();A.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){A.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();A.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){A.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();A.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:n,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};A.debug("receiveDataChannel() [options:%o]",u);let d=this._pc.createDataChannel(n,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};A.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let p=await this._pc.createAnswer(),f=ze.parse(p.sdp),h=f.media.find(m=>m.type==="application");h.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:"client",localSdpObject:f}),p={type:"answer",sdp:ze.write(f)},A.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ze.parse(this._pc.localDescription.sdp));let n=jn.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:n},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new fc.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};qn.Firefox120=ki});var Sc=D($n=>{"use strict";Object.defineProperty($n,"__esModule",{value:!0});$n.Safari12=void 0;var Se=Ve(),Eh=he(),Ph=ie(),$r=Oe(),Dh=ye(),Ih=ht(),xh=Kt(),Br=Yt(),wc=Qt(),Ti=Jt(),P=new Ph.Logger("Safari12"),yc="Safari12",bc={OS:65535,MIS:65535},Ri=class r extends Eh.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:yc,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{P.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let n=await t.createOffer();try{t.close()}catch{}t=void 0;let s=Se.parse(n.sdp);return r.getLocalRtpCapabilities(s)}catch(n){try{t?.close()}catch{}throw t=void 0,n}},getNativeSctpCapabilities:async()=>(P.debug("getNativeSctpCapabilities()"),{numStreams:bc})}}static getLocalRtpCapabilities(e,t=[]){let n=Br.extractRtpCapabilities({sdpObject:e});$r.validateAndNormalizeRtpCapabilities(n),Ti.addNackSupportForOpus(n);for(let s of t)Ti.addHeaderExtensionSupport(n,s);return n}constructor({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:u}){super(),P.debug("constructor()"),this._direction=e,this._remoteSdp=new xh.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=u,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)}),this._pc.addEventListener("icecandidateerror",d=>{this.emit("@icecandidateerror",d)}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(P.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return yc}close(){if(P.debug("close()"),!this._closed){this._closed=!0;try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),P.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),P.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});P.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let n={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();P.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:n,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),P.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t);let c=this._remoteSdp.getNextMediaSectionIdx(),u=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream]});a&&a(u.sender);let d=await this._pc.createOffer(),l=Se.parse(d.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=r.getLocalRtpCapabilities(l,p),h=this._getSendExtendedRtpCapabilities(f),m=$r.getSendingRtpParameters(e.kind,h);m.codecs=$r.reduceCodecs(m.codecs,o);let g=$r.getSendingRemoteRtpParameters(e.kind,h);g.codecs=$r.reduceCodecs(g.codecs,o);let _;this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let v=(0,Ih.parse)((n??[{}])[0].scalabilityMode);n&&n.length>1&&(P.debug("send() | enabling legacy simulcast"),l=Se.parse(d.sdp),_=l.media[c.idx],wc.addLegacySimulcast({offerMediaObject:_,numStreams:n.length}),d={type:"offer",sdp:Se.write(l)}),i?.absCaptureTime&&(_=l.media[c.idx],Br.addHeaderExtension({offerMediaObject:_,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(w=>w.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:Se.write(l)}),P.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let y=u.mid;if(m.mid=y,l=Se.parse(this._pc.localDescription.sdp),_=l.media[c.idx],m.rtcp.cname=Br.getCname({offerMediaObject:_}),m.msid=`${t??this._sendStream.id} ${e.id}`,m.encodings=wc.getRtpEncodings({offerMediaObject:_,codecs:m.codecs}),n)for(let w=0;w<m.encodings.length;++w)n[w]&&Object.assign(m.encodings[w],n[w]);if(m.encodings.length>1&&(m.codecs[0].mimeType.toLowerCase()==="video/vp8"||m.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let w of m.encodings)w.scalabilityMode?w.scalabilityMode=`L1T${v.temporalLayers}`:w.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:_,reuseMid:c.reuseMid,offerRtpParameters:m,answerRtpParameters:g,codecOptions:s});let S={type:"answer",sdp:this._remoteSdp.getSdp()};return P.debug("send() | calling pc.setRemoteDescription() [answer:%o]",S),await this._pc.setRemoteDescription(S),this._mapMidTransceiver.set(y,u),{localId:y,rtpParameters:m,rtpSender:u.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;P.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();P.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),P.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let n=await this._pc.createOffer();P.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),P.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly",this._remoteSdp.resumeSendingMediaSection(e);let n=await this._pc.createOffer();P.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?P.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):P.debug("replaceTrack() [localId:%s, no track]",e);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),P.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();P.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),P.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();P.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};P.debug("sendDataChannel() [options:%o]",t);let n=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%bc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=Se.parse(i.sdp),a=o.media.find(u=>u.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),P.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};P.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:n,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],n=new Map;for(let a of e){let{trackId:c,kind:u,rtpParameters:d,streamId:l}=a;P.debug("receive() [trackId:%s, kind:%s]",c,u);let p=d.mid??String(this._mapMidTransceiver.size);n.set(c,p);let{msidStreamId:f}=Ti.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:u,offerRtpParameters:d,streamId:l??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:u}=a;if(u){let d=n.get(c),l=this._pc.getTransceivers().find(p=>p.mid===d);if(!l)throw new Error("transceiver not found");u(l.receiver)}}let i=await this._pc.createAnswer(),o=Se.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:u}=a,d=n.get(c),l=o.media.find(p=>String(p.mid)===d);Br.applyCodecParameters({offerRtpParameters:u,answerMediaObject:l})}i={type:"answer",sdp:Se.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),P.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,u=n.get(c),d=this._pc.getTransceivers().find(l=>l.mid===u);if(!d)throw new Error("new RTCRtpTransceiver not found");this._mapMidTransceiver.set(u,d),t.push({localId:u,track:d.receiver.track,rtpReceiver:d.receiver})}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){P.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();P.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){P.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();P.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){P.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();P.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:n,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};P.debug("receiveDataChannel() [options:%o]",u);let d=this._pc.createDataChannel(n,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};P.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let p=await this._pc.createAnswer(),f=Se.parse(p.sdp),h=f.media.find(m=>m.type==="application");h.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:Se.write(f)},P.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=Se.parse(this._pc.localDescription.sdp));let n=Br.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:n},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Dh.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};$n.Safari12=Ri});var Rc=D(Bn=>{"use strict";Object.defineProperty(Bn,"__esModule",{value:!0});Bn.ReactNative106=void 0;var ke=Ve(),Ah=he(),Lh=ie(),Hr=Oe(),Mh=ye(),Oh=ht(),Uh=Kt(),Vr=Yt(),Ci=Qt(),Ei=Jt(),C=new Lh.Logger("ReactNative106"),kc="ReactNative106",Tc={OS:65535,MIS:65535},Pi=class r extends Ah.EnhancedEventEmitter{_closed=!1;_direction;_remoteSdp;_getSendExtendedRtpCapabilities;_forcedLocalDtlsRole;_pc;_mapMidTransceiver=new Map;_sendStream=new MediaStream;_hasDataChannelMediaSection=!1;_nextSendSctpStreamId=0;_transportReady=!1;static createFactory(){return{name:kc,factory:e=>new r(e),getNativeRtpCapabilities:async({direction:e})=>{C.debug("getNativeRtpCapabilities() [direction:%o]",e);let t=new RTCPeerConnection({iceServers:[],iceTransportPolicy:"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require"});try{t.addTransceiver("audio",{direction:e}),t.addTransceiver("video",{direction:e});let n=await t.createOffer();try{t.close()}catch{}t=void 0;let s=ke.parse(n.sdp);return r.getLocalRtpCapabilities(s)}catch(n){try{t?.close()}catch{}throw t=void 0,n}},getNativeSctpCapabilities:async()=>(C.debug("getNativeSctpCapabilities()"),{numStreams:Tc})}}static getLocalRtpCapabilities(e,t=[]){let n=Vr.extractRtpCapabilities({sdpObject:e});Hr.validateAndNormalizeRtpCapabilities(n),Ei.addNackSupportForOpus(n);for(let s of t)Ei.addHeaderExtensionSupport(n,s);return n}constructor({direction:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,getSendExtendedRtpCapabilities:u}){super(),C.debug("constructor()"),this._direction=e,this._remoteSdp=new Uh.RemoteSdp({iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i}),this._getSendExtendedRtpCapabilities=u,s.role&&s.role!=="auto"&&(this._forcedLocalDtlsRole=s.role==="server"?"client":"server"),this._pc=new RTCPeerConnection({iceServers:o??[],iceTransportPolicy:a??"all",bundlePolicy:"max-bundle",rtcpMuxPolicy:"require",...c}),this._pc.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.addEventListener("icecandidateerror",this.onIceCandidateError),this._pc.connectionState?this._pc.addEventListener("connectionstatechange",this.onConnectionStateChange):(C.warn("run() | pc.connectionState not supported, using pc.iceConnectionState"),this._pc.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChange))}get name(){return kc}close(){if(C.debug("close()"),!this._closed){this._closed=!0,this._sendStream.release(!1);try{this._pc.close()}catch{}this._pc.removeEventListener("icegatheringstatechange",this.onIceGatheringStateChange),this._pc.removeEventListener("icecandidateerror",this.onIceCandidateError),this._pc.removeEventListener("connectionstatechange",this.onConnectionStateChange),this._pc.removeEventListener("iceconnectionstatechange",this.onIceConnectionStateChange),this.emit("@close"),super.close()}}async updateIceServers(e){this.assertNotClosed(),C.debug("updateIceServers()");let t=this._pc.getConfiguration();t.iceServers=e,this._pc.setConfiguration(t)}async restartIce(e){if(this.assertNotClosed(),C.debug("restartIce()"),this._remoteSdp.updateIceParameters(e),!!this._transportReady)if(this._direction==="send"){let t=await this._pc.createOffer({iceRestart:!0});C.debug("restartIce() | calling pc.setLocalDescription() [offer:%o]",t),await this._pc.setLocalDescription(t);let n={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("restartIce() | calling pc.setRemoteDescription() [answer:%o]",n),await this._pc.setRemoteDescription(n)}else{let t={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("restartIce() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();C.debug("restartIce() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}}async getTransportStats(){return this.assertNotClosed(),this._pc.getStats()}async send({track:e,streamId:t,encodings:n,codecOptions:s,headerExtensionOptions:i,codec:o,onRtpSender:a}){this.assertNotClosed(),this.assertSendDirection(),C.debug("send() [kind:%s, track.id:%s, streamId:%s]",e.kind,e.id,t),n&&n.length>1&&n.forEach((b,L)=>{b.rid=`r${L}`});let c=this._remoteSdp.getNextMediaSectionIdx(),u=this._pc.addTransceiver(e,{direction:"sendonly",streams:[this._sendStream],sendEncodings:n});a&&a(u.sender);let d=await this._pc.createOffer(),l=ke.parse(d.sdp);l.extmapAllowMixed&&this._remoteSdp.setSessionExtmapAllowMixed();let p=[];p.push({uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",kind:e.kind,direction:"sendonly"});let f=r.getLocalRtpCapabilities(l,p),h=this._getSendExtendedRtpCapabilities(f),m=Hr.getSendingRtpParameters(e.kind,h);m.codecs=Hr.reduceCodecs(m.codecs,o);let g=Hr.getSendingRemoteRtpParameters(e.kind,h);g.codecs=Hr.reduceCodecs(g.codecs,o),this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:l});let _=!1,v=(0,Oh.parse)((n??[{}])[0].scalabilityMode),y;n?.length===1&&v.spatialLayers>1&&m.codecs[0].mimeType.toLowerCase()==="video/vp9"&&(C.debug("send() | enabling legacy simulcast for VP9 SVC"),_=!0,l=ke.parse(d.sdp),y=l.media[c.idx],Ci.addLegacySimulcast({offerMediaObject:y,numStreams:v.spatialLayers}),d={type:"offer",sdp:ke.write(l)}),i?.absCaptureTime&&(y=l.media[c.idx],Vr.addHeaderExtension({offerMediaObject:y,headerExtensionUri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time",headerExtensionId:g.headerExtensions.find(b=>b.uri==="http://www.webrtc.org/experiments/rtp-hdrext/abs-capture-time").id}),d={type:"offer",sdp:ke.write(l)}),C.debug("send() | calling pc.setLocalDescription() [offer:%o]",d),await this._pc.setLocalDescription(d);let S=u.mid??void 0;if(S||C.warn("send() | missing transceiver.mid (bug in react-native-webrtc, using a workaround"),m.mid=S,l=ke.parse(this._pc.localDescription.sdp),y=l.media[c.idx],m.rtcp.cname=Vr.getCname({offerMediaObject:y}),m.msid=`${t??this._sendStream.id} ${e.id}`,!n)m.encodings=Ci.getRtpEncodings({offerMediaObject:y,codecs:m.codecs});else if(n.length===1){let b=Ci.getRtpEncodings({offerMediaObject:y,codecs:m.codecs});Object.assign(b[0],n[0]),_&&(b=[b[0]]),m.encodings=b}else m.encodings=n;if(m.encodings.length>1&&(m.codecs[0].mimeType.toLowerCase()==="video/vp8"||m.codecs[0].mimeType.toLowerCase()==="video/h264"))for(let b of m.encodings)b.scalabilityMode?b.scalabilityMode=`L1T${v.temporalLayers}`:b.scalabilityMode="L1T3";this._remoteSdp.send({offerMediaObject:y,reuseMid:c.reuseMid,offerRtpParameters:m,answerRtpParameters:g,codecOptions:s});let w={type:"answer",sdp:this._remoteSdp.getSdp()};return C.debug("send() | calling pc.setRemoteDescription() [answer:%o]",w),await this._pc.setRemoteDescription(w),S||(S=u.mid,m.mid=S),this._mapMidTransceiver.set(S,u),{localId:S,rtpParameters:m,rtpSender:u.sender}}async stopSending(e){if(this.assertSendDirection(),this._closed)return;C.debug("stopSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");if(t.sender.replaceTrack(null),this._pc.removeTrack(t.sender),this._remoteSdp.closeMediaSection(t.mid))try{t.stop()}catch{}let s=await this._pc.createOffer();C.debug("stopSending() | calling pc.setLocalDescription() [offer:%o]",s),await this._pc.setLocalDescription(s);let i={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("stopSending() | calling pc.setRemoteDescription() [answer:%o]",i),await this._pc.setRemoteDescription(i),this._mapMidTransceiver.delete(e)}async pauseSending(e){this.assertNotClosed(),this.assertSendDirection(),C.debug("pauseSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="inactive",this._remoteSdp.pauseMediaSection(e);let n=await this._pc.createOffer();C.debug("pauseSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("pauseSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async resumeSending(e){this.assertNotClosed(),this.assertSendDirection(),C.debug("resumeSending() [localId:%s]",e);let t=this._mapMidTransceiver.get(e);if(this._remoteSdp.resumeSendingMediaSection(e),!t)throw new Error("associated RTCRtpTransceiver not found");t.direction="sendonly";let n=await this._pc.createOffer();C.debug("resumeSending() | calling pc.setLocalDescription() [offer:%o]",n),await this._pc.setLocalDescription(n);let s={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("resumeSending() | calling pc.setRemoteDescription() [answer:%o]",s),await this._pc.setRemoteDescription(s)}async replaceTrack(e,t){this.assertNotClosed(),this.assertSendDirection(),t?C.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):C.debug("replaceTrack() [localId:%s, no track]",e);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");await n.sender.replaceTrack(t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),this.assertSendDirection(),C.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{c<=t?a.active=!0:a.active=!1}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();C.debug("setMaxSpatialLayer() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("setMaxSpatialLayer() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),this.assertSendDirection(),C.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t);let n=this._mapMidTransceiver.get(e);if(!n)throw new Error("associated RTCRtpTransceiver not found");let s=n.sender.getParameters();s.encodings.forEach((a,c)=>{s.encodings[c]={...a,...t}}),await n.sender.setParameters(s),this._remoteSdp.muxMediaSectionSimulcast(e,s.encodings);let i=await this._pc.createOffer();C.debug("setRtpEncodingParameters() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i);let o={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("setRtpEncodingParameters() | calling pc.setRemoteDescription() [answer:%o]",o),await this._pc.setRemoteDescription(o)}async getSenderStats(e){this.assertNotClosed(),this.assertSendDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.sender.getStats()}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this.assertSendDirection();let t={negotiated:!0,id:this._nextSendSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,protocol:e.protocol};C.debug("sendDataChannel() [options:%o]",t);let n=this._pc.createDataChannel(e.label,t);if(this._nextSendSctpStreamId=++this._nextSendSctpStreamId%Tc.MIS,!this._hasDataChannelMediaSection){let i=await this._pc.createOffer(),o=ke.parse(i.sdp),a=o.media.find(u=>u.type==="application");this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),C.debug("sendDataChannel() | calling pc.setLocalDescription() [offer:%o]",i),await this._pc.setLocalDescription(i),this._remoteSdp.sendSctpAssociation({offerMediaObject:a});let c={type:"answer",sdp:this._remoteSdp.getSdp()};C.debug("sendDataChannel() | calling pc.setRemoteDescription() [answer:%o]",c),await this._pc.setRemoteDescription(c),this._hasDataChannelMediaSection=!0}let s={streamId:t.id,ordered:t.ordered,maxPacketLifeTime:t.maxPacketLifeTime,maxRetransmits:t.maxRetransmits};return{dataChannel:n,sctpStreamParameters:s}}async receive(e){this.assertNotClosed(),this.assertRecvDirection();let t=[],n=new Map;for(let a of e){let{trackId:c,kind:u,rtpParameters:d,streamId:l}=a;C.debug("receive() [trackId:%s, kind:%s]",c,u);let p=d.mid??String(this._mapMidTransceiver.size);n.set(c,p);let{msidStreamId:f}=Ei.getMsidStreamIdAndTrackId(d.msid);this._remoteSdp.receive({mid:p,kind:u,offerRtpParameters:d,streamId:l??f??d.rtcp?.cname??"-",trackId:c})}let s={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("receive() | calling pc.setRemoteDescription() [offer:%o]",s),await this._pc.setRemoteDescription(s);for(let a of e){let{trackId:c,onRtpReceiver:u}=a;if(u){let d=n.get(c),l=this._pc.getTransceivers().find(p=>p.mid===d);if(!l)throw new Error("transceiver not found");u(l.receiver)}}let i=await this._pc.createAnswer(),o=ke.parse(i.sdp);for(let a of e){let{trackId:c,rtpParameters:u}=a,d=n.get(c),l=o.media.find(p=>String(p.mid)===d);Vr.applyCodecParameters({offerRtpParameters:u,answerMediaObject:l})}i={type:"answer",sdp:ke.write(o)},this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:o}),C.debug("receive() | calling pc.setLocalDescription() [answer:%o]",i),await this._pc.setLocalDescription(i);for(let a of e){let{trackId:c}=a,u=n.get(c),d=this._pc.getTransceivers().find(l=>l.mid===u);if(d)this._mapMidTransceiver.set(u,d),t.push({localId:u,track:d.receiver.track,rtpReceiver:d.receiver});else throw new Error("new RTCRtpTransceiver not found")}return t}async stopReceiving(e){if(this.assertRecvDirection(),this._closed)return;for(let s of e){C.debug("stopReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");this._remoteSdp.closeMediaSection(i.mid)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("stopReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();C.debug("stopReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n);for(let s of e)this._mapMidTransceiver.delete(s)}async pauseReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){C.debug("pauseReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="inactive",this._remoteSdp.pauseMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("pauseReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();C.debug("pauseReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async resumeReceiving(e){this.assertNotClosed(),this.assertRecvDirection();for(let s of e){C.debug("resumeReceiving() [localId:%s]",s);let i=this._mapMidTransceiver.get(s);if(!i)throw new Error("associated RTCRtpTransceiver not found");i.direction="recvonly",this._remoteSdp.resumeReceivingMediaSection(s)}let t={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("resumeReceiving() | calling pc.setRemoteDescription() [offer:%o]",t),await this._pc.setRemoteDescription(t);let n=await this._pc.createAnswer();C.debug("resumeReceiving() | calling pc.setLocalDescription() [answer:%o]",n),await this._pc.setLocalDescription(n)}async getReceiverStats(e){this.assertNotClosed(),this.assertRecvDirection();let t=this._mapMidTransceiver.get(e);if(!t)throw new Error("associated RTCRtpTransceiver not found");return t.receiver.getStats()}async receiveDataChannel({maxMessageSize:e,sctpStreamParameters:t,label:n,protocol:s}){this.assertNotClosed(),this.assertRecvDirection();let{streamId:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c}=t,u={negotiated:!0,id:i,ordered:o,maxPacketLifeTime:a,maxRetransmits:c,protocol:s};C.debug("receiveDataChannel() [options:%o]",u);let d=this._pc.createDataChannel(n,u);if(!this._hasDataChannelMediaSection){this._remoteSdp.receiveSctpAssociation();let l={type:"offer",sdp:this._remoteSdp.getSdp()};C.debug("receiveDataChannel() | calling pc.setRemoteDescription() [offer:%o]",l),await this._pc.setRemoteDescription(l);let p=await this._pc.createAnswer(),f=ke.parse(p.sdp),h=f.media.find(m=>m.type==="application");h.maxMessageSize=e,this._transportReady||await this.setupTransport({localDtlsRole:this._forcedLocalDtlsRole??"client",localSdpObject:f}),p={type:"answer",sdp:ke.write(f)},C.debug("receiveDataChannel() | calling pc.setLocalDescription() [answer:%o]",p),await this._pc.setLocalDescription(p),this._hasDataChannelMediaSection=!0}return{dataChannel:d}}getDataChannelMaxMessageSize(){return this._pc.sctp?.maxMessageSize}async setupTransport({localDtlsRole:e,localSdpObject:t}){t||(t=ke.parse(this._pc.localDescription.sdp));let n=Vr.extractDtlsParameters({sdpObject:t});n.role=e,this._remoteSdp.updateDtlsRole(e==="client"?"server":"client"),await new Promise((s,i)=>{this.safeEmit("@connect",{dtlsParameters:n},s,i)}),this._transportReady=!0}onIceGatheringStateChange=()=>{this.emit("@icegatheringstatechange",this._pc.iceGatheringState)};onIceCandidateError=e=>{this.emit("@icecandidateerror",e)};onConnectionStateChange=()=>{this.emit("@connectionstatechange",this._pc.connectionState)};onIceConnectionStateChange=()=>{switch(this._pc.iceConnectionState){case"checking":{this.emit("@connectionstatechange","connecting");break}case"connected":case"completed":{this.emit("@connectionstatechange","connected");break}case"failed":{this.emit("@connectionstatechange","failed");break}case"disconnected":{this.emit("@connectionstatechange","disconnected");break}case"closed":{this.emit("@connectionstatechange","closed");break}}};assertNotClosed(){if(this._closed)throw new Mh.InvalidStateError("method called in a closed handler")}assertSendDirection(){if(this._direction!=="send")throw new Error('method can just be called for handlers with "send" direction')}assertRecvDirection(){if(this._direction!=="recv")throw new Error('method can just be called for handlers with "recv" direction')}};Bn.ReactNative106=Pi});var Dc=D(Xt=>{"use strict";Object.defineProperty(Xt,"__esModule",{value:!0});Xt.Device=void 0;Xt.detectDevice=Cc;Xt.detectDeviceAsync=Ec;var Nh=ie(),Fh=he(),et=ye(),Hn=dt(),fe=Oe(),Wh=Ya(),jh=uc(),qh=hc(),$h=vc(),Bh=Sc(),Hh=Rc(),T=new Nh.Logger("Device");function Cc(r,e){return T.debug("detectDevice()"),!r&&typeof navigator=="object"&&(r=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),Pc(r,e)}async function Ec(r,e){return T.debug("detectDeviceAsync()"),!r&&typeof navigator=="object"&&(r=navigator.userAgent),!e&&typeof navigator=="object"&&(e=navigator.userAgentData),Pc(r,e)}var Di=class r{_handlerFactory;_handlerName;_loaded=!1;_getSendExtendedRtpCapabilities;_recvRtpCapabilities;_sendRtpCapabilities;_canProduceByKind={audio:!1,video:!1};_sctpCapabilities;_observer=new Fh.EnhancedEventEmitter;static async factory({handlerName:e,handlerFactory:t}={}){if(T.debug("factory()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(!e&&!t&&(e=await Ec(),!e))throw new et.UnsupportedError("device not supported");return new r({handlerName:e,handlerFactory:t})}constructor({handlerName:e,handlerFactory:t}={}){if(T.debug("constructor()"),e&&t)throw new TypeError("just one of handlerName or handlerInterface can be given");if(t)this._handlerFactory=t;else{if(e)T.debug("constructor() | handler given: %s",e);else if(e=Cc(),e)T.debug("constructor() | detected handler: %s",e);else throw new et.UnsupportedError("device not supported");switch(e){case"Chrome111":{this._handlerFactory=jh.Chrome111.createFactory();break}case"Chrome74":{this._handlerFactory=qh.Chrome74.createFactory();break}case"Firefox120":{this._handlerFactory=$h.Firefox120.createFactory();break}case"Safari12":{this._handlerFactory=Bh.Safari12.createFactory();break}case"ReactNative106":{this._handlerFactory=Hh.ReactNative106.createFactory();break}default:throw new TypeError(`unknown handlerName "${e}"`)}}this._handlerName=this._handlerFactory.name}get handlerName(){return this._handlerName}get loaded(){return this._loaded}get rtpCapabilities(){return this.recvRtpCapabilities}get recvRtpCapabilities(){if(!this._loaded)throw new et.InvalidStateError("not loaded");return this._recvRtpCapabilities}get sendRtpCapabilities(){if(!this._loaded)throw new et.InvalidStateError("not loaded");return this._sendRtpCapabilities}get sctpCapabilities(){if(!this._loaded)throw new et.InvalidStateError("not loaded");return this._sctpCapabilities}get observer(){return this._observer}async load({routerRtpCapabilities:e,preferLocalCodecsOrder:t=!1}){if(T.debug("load() [routerRtpCapabilities:%o]",e),this._loaded)throw new et.InvalidStateError("already loaded");let n=Hn.clone(e);fe.validateAndNormalizeRtpCapabilities(n);let{getNativeRtpCapabilities:s,getNativeSctpCapabilities:i}=this._handlerFactory,o=Hn.clone(await s({direction:"recvonly"}));T.debug("load() | got native receiving RTP capabilities:%o",o),fe.validateAndNormalizeRtpCapabilities(o);let a=Hn.clone(await s({direction:"sendonly"}));T.debug("load() | got native sending RTP capabilities:%o",a),fe.validateAndNormalizeRtpCapabilities(a),this._getSendExtendedRtpCapabilities=d=>Hn.clone(fe.getExtendedRtpCapabilities(d,n,t));let c=fe.getExtendedRtpCapabilities(o,n,!1);this._recvRtpCapabilities=fe.getRecvRtpCapabilities(c),T.debug("load() | got receiving RTP capabilities:%o",this._recvRtpCapabilities),fe.validateAndNormalizeRtpCapabilities(this._recvRtpCapabilities);let u=fe.getExtendedRtpCapabilities(a,n,t);this._sendRtpCapabilities=fe.getSendRtpCapabilities(u),T.debug("load() | got sending RTP capabilities:%o",this._sendRtpCapabilities),fe.validateAndNormalizeRtpCapabilities(this._sendRtpCapabilities),this._canProduceByKind.audio=fe.canSend("audio",this._sendRtpCapabilities),this._canProduceByKind.video=fe.canSend("video",this._sendRtpCapabilities),this._sctpCapabilities=await i(),fe.validateSctpCapabilities(this._sctpCapabilities),T.debug("load() | got native SCTP capabilities:%o",this._sctpCapabilities),T.debug("load() succeeded"),this._loaded=!0}canProduce(e){if(this._loaded){if(e!=="audio"&&e!=="video")throw new TypeError(`invalid kind "${e}"`)}else throw new et.InvalidStateError("not loaded");return this._canProduceByKind[e]}createSendTransport({id:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:u}){return T.debug("createSendTransport()"),this.createTransport({direction:"send",id:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:u})}createRecvTransport({id:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:u}){return T.debug("createRecvTransport()"),this.createTransport({direction:"recv",id:e,iceParameters:t,iceCandidates:n,dtlsParameters:s,sctpParameters:i,iceServers:o,iceTransportPolicy:a,additionalSettings:c,appData:u})}createTransport({direction:e,id:t,iceParameters:n,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:u,appData:d}){if(this._loaded){if(typeof t!="string")throw new TypeError("missing id");if(typeof n!="object")throw new TypeError("missing iceParameters");if(Array.isArray(s)){if(typeof i!="object")throw new TypeError("missing dtlsParameters");if(o&&typeof o!="object")throw new TypeError("wrong sctpParameters");if(d&&typeof d!="object")throw new TypeError("if given, appData must be an object")}else throw new TypeError("missing iceCandidates")}else throw new et.InvalidStateError("not loaded");let l=new Wh.Transport({direction:e,id:t,iceParameters:n,iceCandidates:s,dtlsParameters:i,sctpParameters:o,iceServers:a,iceTransportPolicy:c,additionalSettings:u,appData:d,handlerFactory:this._handlerFactory,getSendExtendedRtpCapabilities:this._getSendExtendedRtpCapabilities,recvRtpCapabilities:this._recvRtpCapabilities,canProduceByKind:this._canProduceByKind});return this._observer.safeEmit("newtransport",l),l}};Xt.Device=Di;function Pc(r,e){T.debug('detectDeviceImpl() [userAgent:"%s", userAgentData:%o]',r,e);let t=Vh(r,e);if(t){if(t>=111)return T.debug("detectDeviceImpl() | using Chrome111 handler"),"Chrome111";if(t>=74)return T.debug("detectDeviceImpl() | using Chrome74 handler"),"Chrome74";T.warn("detectDeviceImpl() | unsupported Chromium based browser/version");return}let n=zh(r);if(n){if(n>=120)return T.debug("detectDeviceImpl() | using Firefox120 handler"),"Firefox120";T.warn("detectDeviceImpl() | unsupported Firefox browser/version");return}let s=Gh(r);if(s){if(s>=605)return T.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";T.warn("detectDeviceImpl() | unsupported desktop Safari browser/version");return}let i=Kh(r);if(i){if(i>=605)return T.debug("detectDeviceImpl() | using Safari12 handler"),"Safari12";T.warn("detectDeviceImpl() | unsupported iOS Safari based browser/version");return}if(zr()){if(typeof RTCPeerConnection<"u"&&typeof RTCRtpTransceiver<"u")return T.debug("detectDeviceImpl() | using ReactNative106 handler"),"ReactNative106";T.warn("detectDeviceImpl() | unsupported react-native-webrtc version without RTCPeerConnection or RTCRtpTransceiver, forgot to call registerGlobals() on it?");return}T.warn('detectDeviceImpl() | device not supported [userAgent:"%s", userAgentData:%o]',r,e)}function Vh(r,e){if(T.debug("getChromiumMajorVersion()"),Vn(r,e)){T.debug("getChromiumMajorVersion() | this is iOS => undefined");return}if(zr()){T.debug("getChromiumMajorVersion() | this is React-Native => undefined");return}if(e){let s=(Array.isArray(e.brands)?e.brands:[]).find(i=>i.brand==="Chromium");if(s){let i=Number(s.version);return T.debug(`getChromiumMajorVersion() | Chromium major version based on NavigatorUAData => ${i}`),i}}let t=r?.match(/\b(?:Chrome|Chromium)\/(\w+)/i);if(t?.[1]){let n=Number(t[1]);return T.debug(`getChromiumMajorVersion() | Chromium major version based on User-Agent => ${n}`),n}T.debug("getChromiumMajorVersion() | this is not Chromium => undefined")}function zh(r){if(T.debug("getFirefoxMajorVersion()"),Vn(r)){T.debug("getFirefoxMajorVersion() | this is iOS => undefined");return}if(zr()){T.debug("getFirefoxMajorVersion() | this is React-Native => undefined");return}let e=r?.match(/\bFirefox\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return T.debug(`getFirefoxMajorVersion() | Firefox major version based on User-Agent => ${t}`),t}T.debug("getFirefoxMajorVersion() | this is not Firefox => undefined")}function Gh(r){if(T.debug("getMacOSWebKitMajorVersion()"),Vn(r)){T.debug("getMacOSWebKitMajorVersion() | this is iOS => undefined");return}if(zr()){T.debug("getMacOSWebKitMajorVersion() | this is React-Native => undefined");return}if(!(r&&/\bSafari\b/i.test(r)&&!/\bChrome\b/i.test(r)&&!/\bChromium\b/i.test(r)&&!/\bFirefox\b/i.test(r))){T.debug("getMacOSWebKitMajorVersion() | this is not Safari => undefined");return}let t=r.match(/AppleWebKit\/(\w+)/i);if(t?.[1]){let n=Number(t[1]);return T.debug(`getMacOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${n}`),n}T.debug("getMacOSWebKitMajorVersion() | this is not WebKit => undefined")}function Kh(r){if(T.debug("getIOSWebKitMajorVersion()"),!Vn(r)){T.debug("getIOSWebKitMajorVersion() | this is not iOS => undefined");return}if(zr()){T.debug("getIOSWebKitMajorVersion() | this is React-Native => undefined");return}let e=r?.match(/AppleWebKit\/(\w+)/i);if(e?.[1]){let t=Number(e[1]);return T.debug(`getIOSWebKitMajorVersion() | WebKit major version based on User-Agent => ${t}`),t}T.debug("getIOSWebKitMajorVersion() | this is not WebKit => undefined")}function Vn(r,e){return T.debug("isIOS()"),e?.platform==="iOS"?(T.debug("isIOS() | this is iOS based on NavigatorUAData.platform => true"),!0):e?.platform?(T.debug("isIOS() | this is not iOS based on NavigatorUAData.platform => false"),!1):r&&/iPad|iPhone|iPod/.test(r)?(T.debug("isIOS() | this is iOS based on User-Agent => true"),!0):typeof navigator=="object"&&navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1?(T.debug("isIOS() | this is iPadOS 13+ based on User-Agent => true"),!0):(T.debug("isIOS() | this is not iOS => false"),!1)}function zr(){return T.debug("isReactNative()"),typeof navigator=="object"&&navigator.product==="ReactNative"?(T.debug("isReactNative() | this is React-Native based on navigator.product"),!0):(T.debug("isReactNative() | this is not React-Native => false"),!1)}});var xc=D(Ic=>{"use strict";var mt=256,Gn=[],zn;for(;mt--;)Gn[mt]=(mt+256).toString(16).substring(1);function Yh(){var r=0,e,t="";if(!zn||mt+16>256){for(zn=Array(r=256);r--;)zn[r]=256*Math.random()|0;r=mt=0}for(;r<16;r++)e=zn[mt+r],r==6?t+=Gn[e&15|64]:r==8?t+=Gn[e&63|128]:t+=Gn[e],r&1&&r>1&&r<11&&(t+="-");return mt++,t}Ic.v4=Yh});var Ac=D(Kn=>{"use strict";Object.defineProperty(Kn,"__esModule",{value:!0});Kn.FakeEventTarget=void 0;var Ii=class{listeners={};addEventListener(e,t,n){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof n=="object"&&n.once===!0}))}removeEventListener(e,t,n){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(s=>s.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let n of[...t]){try{n.callback.call(this,e)}catch(s){setTimeout(()=>{throw s},0)}n.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}};Kn.FakeEventTarget=Ii});var Lc=D(Yn=>{"use strict";Object.defineProperty(Yn,"__esModule",{value:!0});Yn.FakeEvent=void 0;var xi=class{NONE=0;CAPTURING_PHASE=1;AT_TARGET=2;BUBBLING_PHASE=3;type;bubbles;cancelable;defaultPrevented=!1;composed=!1;currentTarget=null;eventPhase=this.NONE;isTrusted=!0;target=null;timeStamp=0;cancelBubble=!1;returnValue=!0;srcElement=null;constructor(e,t={}){this.type=e,this.bubbles=t.bubbles??!1,this.cancelable=t.cancelable??!1}preventDefault(){this.cancelable&&(this.defaultPrevented=!0)}stopPropagation(){}stopImmediatePropagation(){}composedPath(){return[]}initEvent(e,t,n){}};Yn.FakeEvent=xi});var Mc=D(Ai=>{"use strict";Object.defineProperty(Ai,"__esModule",{value:!0});Ai.clone=Qh;function Qh(r){if(r!==void 0)return Number.isNaN(r)?NaN:typeof structuredClone=="function"?structuredClone(r):JSON.parse(JSON.stringify(r))}});var Uc=D(Jn=>{"use strict";Object.defineProperty(Jn,"__esModule",{value:!0});Jn.FakeMediaStreamTrack=void 0;var Oc=xc(),Jh=Ac(),Zt=Lc(),Qn=Mc(),Li=class r extends Jh.FakeEventTarget{#m;#l;#p;#e;#r;#t;#n;#h;#s;#f;#i;#o=null;#a=null;#c=null;#d=null;#u=null;constructor({kind:e,id:t,label:n,contentHint:s,enabled:i,muted:o,readyState:a,capabilities:c,constraints:u,settings:d,data:l}){super(),this.#m=t??(0,Oc.v4)(),this.#l=e,this.#p=n??"",this.#n=s??"",this.#r=i??!0,this.#t=o??!1,this.#e=a??"live",this.#h=c??{},this.#s=u??{},this.#f=d??{},this.#i=l??{}}get id(){return this.#m}get kind(){return this.#l}get label(){return this.#p}get contentHint(){return this.#n}set contentHint(e){this.#n=e}get enabled(){return this.#r}set enabled(e){let t=this.#r!==e;this.#r=e,t&&this.dispatchEvent(new Zt.FakeEvent("enabledchange"))}get muted(){return this.#t}get readyState(){return this.#e}get data(){return this.#i}set data(e){this.#i=e}get onmute(){return this.#o}set onmute(e){this.#o&&this.removeEventListener("mute",this.#o),this.#o=e,e&&this.addEventListener("mute",e)}get onunmute(){return this.#a}set onunmute(e){this.#a&&this.removeEventListener("unmute",this.#a),this.#a=e,e&&this.addEventListener("unmute",e)}get onended(){return this.#c}set onended(e){this.#c&&this.removeEventListener("ended",this.#c),this.#c=e,e&&this.addEventListener("ended",e)}get onenabledchange(){return this.#d}set onenabledchange(e){this.#d&&this.removeEventListener("enabledchange",this.#d),this.#d=e,e&&this.addEventListener("enabledchange",e)}get onstopped(){return this.#u}set onstopped(e){this.#u&&this.removeEventListener("stopped",this.#u),this.#u=e,e&&this.addEventListener("stopped",e)}addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}stop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new Zt.FakeEvent("stopped")))}clone({id:e,data:t}={}){return new r({id:e??(0,Oc.v4)(),kind:this.#l,label:this.#p,contentHint:this.#n,enabled:this.#r,muted:this.#t,readyState:this.#e,capabilities:(0,Qn.clone)(this.#h),constraints:(0,Qn.clone)(this.#s),settings:(0,Qn.clone)(this.#f),data:t??(0,Qn.clone)(this.#i)})}getCapabilities(){return this.#h}getConstraints(){return this.#s}async applyConstraints(e={}){return this.#s=e,Promise.resolve()}getSettings(){return this.#f}remoteStop(){this.#e!=="ended"&&(this.#e="ended",this.dispatchEvent(new Zt.FakeEvent("stopped")),this.dispatchEvent(new Zt.FakeEvent("ended")))}remoteMute(){this.#t||(this.#t=!0,this.dispatchEvent(new Zt.FakeEvent("mute")))}remoteUnmute(){this.#t&&(this.#t=!1,this.dispatchEvent(new Zt.FakeEvent("unmute")))}};Jn.FakeMediaStreamTrack=Li});var Nc=D(Xn=>{"use strict";Object.defineProperty(Xn,"__esModule",{value:!0});Xn.FakeEventTarget=void 0;var Mi=class{listeners={};addEventListener(e,t,n){t&&(this.listeners[e]=this.listeners[e]??[],this.listeners[e].push({callback:typeof t=="function"?t:t.handleEvent,once:typeof n=="object"&&n.once===!0}))}removeEventListener(e,t,n){this.listeners[e]&&t&&(this.listeners[e]=this.listeners[e].filter(s=>s.callback!==(typeof t=="function"?t:t.handleEvent)))}dispatchEvent(e){if(!e||typeof e.type!="string")throw new Error("invalid event object");let t=this.listeners[e.type];if(!t)return!0;for(let n of[...t]){try{n.callback.call(this,e)}catch(s){setTimeout(()=>{throw s},0)}n.once&&this.removeEventListener(e.type,n.callback)}return!e.defaultPrevented}};Xn.FakeEventTarget=Mi});var jc=D(es=>{"use strict";Object.defineProperty(es,"__esModule",{value:!0});es.FakeHandler=void 0;var Xh=Uc(),Zh=he(),ef=ie(),er=dt(),Oi=Oe(),Wc=ye(),tf=Nc(),Z=new ef.Logger("FakeHandler"),Fc="FakeHandler",Ui=class r extends Zh.EnhancedEventEmitter{_closed=!1;_fakeParameters;_getSendExtendedRtpCapabilities;_cname=`CNAME-${er.generateRandomNumber()}`;_defaultSendStreamId=`${er.generateRandomNumber()}`;_transportReady=!1;_nextLocalId=1;_tracks=new Map;_nextSctpStreamId=0;static createFactory(e){return{name:Fc,factory:t=>new r(t,e),getNativeRtpCapabilities:async({direction:t})=>(Z.debug("getNativeRtpCapabilities() [direction:%o]",t),r.getLocalRtpCapabilities(e)),getNativeSctpCapabilities:async()=>(Z.debug("getNativeSctpCapabilities()"),e.generateNativeSctpCapabilities())}}static getLocalRtpCapabilities(e){let t=e.generateNativeRtpCapabilities();return Oi.validateAndNormalizeRtpCapabilities(t),t}constructor({getSendExtendedRtpCapabilities:e},t){super(),Z.debug("constructor()"),this._getSendExtendedRtpCapabilities=e,this._fakeParameters=t}get name(){return Fc}close(){Z.debug("close()"),!this._closed&&(this._closed=!0,super.close())}setIceGatheringState(e){this.emit("@icegatheringstatechange",e)}setConnectionState(e){this.emit("@connectionstatechange",e)}async updateIceServers(e){this.assertNotClosed(),Z.debug("updateIceServers()")}async restartIce(e){this.assertNotClosed(),Z.debug("restartIce()")}async getTransportStats(){return this.assertNotClosed(),new Map}async send({track:e,streamId:t,encodings:n,codecOptions:s,codec:i}){this.assertNotClosed(),Z.debug("send() [kind:%s, track.id:%s]",e.kind,e.id),this._transportReady||await this.setupTransport({localDtlsRole:"server"});let o=r.getLocalRtpCapabilities(this._fakeParameters),a=this._getSendExtendedRtpCapabilities(o),c=Oi.getSendingRtpParameters(e.kind,a);c.codecs=Oi.reduceCodecs(c.codecs,i);let u=c.codecs.some(l=>/.+\/rtx$/i.test(l.mimeType));c.mid=`mid-${er.generateRandomNumber()}`,c.msid=`${t??"-"} ${e.id}`,n||(n=[{}]);for(let l of n)l.ssrc=er.generateRandomNumber(),u&&(l.rtx={ssrc:er.generateRandomNumber()});c.encodings=n,c.rtcp={cname:this._cname,reducedSize:!0,mux:!0},c.msid=`${t??this._defaultSendStreamId} ${e.id}`;let d=this._nextLocalId++;return this._tracks.set(d,e),{localId:String(d),rtpParameters:c}}async stopSending(e){if(Z.debug("stopSending() [localId:%s]",e),!this._closed){if(!this._tracks.has(Number(e)))throw new Error("local track not found");this._tracks.delete(Number(e))}}async pauseSending(e){this.assertNotClosed()}async resumeSending(e){this.assertNotClosed()}async replaceTrack(e,t){this.assertNotClosed(),t?Z.debug("replaceTrack() [localId:%s, track.id:%s]",e,t.id):Z.debug("replaceTrack() [localId:%s, no track]",e),this._tracks.delete(Number(e)),this._tracks.set(Number(e),t)}async setMaxSpatialLayer(e,t){this.assertNotClosed(),Z.debug("setMaxSpatialLayer() [localId:%s, spatialLayer:%s]",e,t)}async setRtpEncodingParameters(e,t){this.assertNotClosed(),Z.debug("setRtpEncodingParameters() [localId:%s, params:%o]",e,t)}async getSenderStats(e){return this.assertNotClosed(),new Map}async sendDataChannel({sctpStreamParameters:e}){this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"server"}),Z.debug("sendDataChannel()");let t=new Zn({id:this._nextSctpStreamId++,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:e.label,protocol:e.protocol}),n={streamId:this._nextSctpStreamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits};return{dataChannel:t,sctpStreamParameters:n}}async receive(e){this.assertNotClosed();let t=[];for(let n of e){let{trackId:s,kind:i}=n;this._transportReady||await this.setupTransport({localDtlsRole:"client"}),Z.debug("receive() [trackId:%s, kind:%s]",s,i);let o=this._nextLocalId++,a=new Xh.FakeMediaStreamTrack({kind:i});this._tracks.set(o,a),t.push({localId:String(o),track:a})}return t}async stopReceiving(e){if(!this._closed)for(let t of e)Z.debug("stopReceiving() [localId:%s]",t),this._tracks.delete(Number(t))}async pauseReceiving(e){this.assertNotClosed()}async resumeReceiving(e){this.assertNotClosed()}async getReceiverStats(e){return this.assertNotClosed(),new Map}async receiveDataChannel({sctpStreamParameters:e,label:t,protocol:n}){return this.assertNotClosed(),this._transportReady||await this.setupTransport({localDtlsRole:"client"}),Z.debug("receiveDataChannel()"),{dataChannel:new Zn({id:e.streamId,ordered:e.ordered,maxPacketLifeTime:e.maxPacketLifeTime,maxRetransmits:e.maxRetransmits,label:t,protocol:n})}}getDataChannelMaxMessageSize(){return 5e5}async setupTransport({localDtlsRole:e,localSdpObject:t}){let n=er.clone(this._fakeParameters.generateLocalDtlsParameters());e&&(n.role=e),this.emit("@connectionstatechange","connecting"),await new Promise((s,i)=>this.emit("@connect",{dtlsParameters:n},s,i)),this._transportReady=!0}assertNotClosed(){if(this._closed)throw new Wc.InvalidStateError("method called in a closed handler")}};es.FakeHandler=Ui;var Zn=class extends tf.FakeEventTarget{_id;_negotiated=!0;_ordered;_maxPacketLifeTime;_maxRetransmits;_label;_protocol;_readyState="connecting";_bufferedAmount=0;_bufferedAmountLowThreshold=0;_binaryType="arraybuffer";_onopen=null;_onclosing=null;_onclose=null;_onmessage=null;_onbufferedamountlow=null;_onerror=null;constructor({id:e,ordered:t=!0,maxPacketLifeTime:n=null,maxRetransmits:s=null,label:i="",protocol:o=""}){super(),Z.debug(`constructor() [id:${e}, ordered:${t}, maxPacketLifeTime:${n}, maxRetransmits:${s}, label:${i}, protocol:${o}`),this._id=e,this._ordered=t,this._maxPacketLifeTime=n,this._maxRetransmits=s,this._label=i,this._protocol=o}get id(){return this._id}get negotiated(){return this._negotiated}get ordered(){return this._ordered}get maxPacketLifeTime(){return this._maxPacketLifeTime}get maxRetransmits(){return this._maxRetransmits}get label(){return this._label}get protocol(){return this._protocol}get readyState(){return this._readyState}get bufferedAmount(){return this._bufferedAmount}get bufferedAmountLowThreshold(){return this._bufferedAmountLowThreshold}set bufferedAmountLowThreshold(e){this._bufferedAmountLowThreshold=e}get binaryType(){return this._binaryType}set binaryType(e){this._binaryType=e}get onopen(){return this._onopen}set onopen(e){this._onopen&&this.removeEventListener("open",this._onopen),this._onopen=e,e&&this.addEventListener("open",e)}get onclosing(){return this._onclosing}set onclosing(e){this._onclosing&&this.removeEventListener("closing",this._onclosing),this._onclosing=e,e&&this.addEventListener("closing",e)}get onclose(){return this._onclose}set onclose(e){this._onclose&&this.removeEventListener("close",this._onclose),this._onclose=e,e&&this.addEventListener("close",e)}get onmessage(){return this._onmessage}set onmessage(e){this._onmessage&&this.removeEventListener("message",this._onmessage),this._onmessage=e,e&&this.addEventListener("message",e)}get onbufferedamountlow(){return this._onbufferedamountlow}set onbufferedamountlow(e){this._onbufferedamountlow&&this.removeEventListener("bufferedamountlow",this._onbufferedamountlow),this._onbufferedamountlow=e,e&&this.addEventListener("bufferedamountlow",e)}get onerror(){return this._onerror}set onerror(e){this._onerror&&this.removeEventListener("error",this._onerror),this._onerror=e,e&&this.addEventListener("error",e)}addEventListener(e,t,n){super.addEventListener(e,t,n)}removeEventListener(e,t,n){super.removeEventListener(e,t,n)}close(){["closing","closed"].includes(this._readyState)||(this._readyState="closed")}send(e){if(this._readyState!=="open")throw new Wc.InvalidStateError("not open")}}});var qc=D(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.generateRouterRtpCapabilities=rf;Ie.generateNativeRtpCapabilities=nf;Ie.generateNativeSctpCapabilities=sf;Ie.generateLocalDtlsParameters=of;Ie.generateTransportRemoteParameters=af;Ie.generateProducerRemoteParameters=cf;Ie.generateConsumerRemoteParameters=df;Ie.generateDataProducerRemoteParameters=uf;Ie.generateDataConsumerRemoteParameters=lf;var ae=dt();function me(){return String(ae.generateRandomNumber())}function rf(){return ae.deepFreeze({codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}},{mimeType:"video/H264",kind:"video",preferredPayloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:105,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"profile-id":0,"x-google-start-bitrate":1500}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:106,clockRate:9e4,rtcpFeedback:[],parameters:{apt:105}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:rtp-stream-id",preferredId:2,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:repaired-rtp-stream-id",preferredId:3,preferredEncrypt:!1,direction:"recvonly"},{kind:"audio",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:4,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"recvonly"},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5,preferredEncrypt:!1,direction:"sendrecv"},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:11,preferredEncrypt:!1,direction:"sendrecv"},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:12,preferredEncrypt:!1,direction:"sendrecv"}]})}function nf(){return{codecs:[{mimeType:"audio/opus",kind:"audio",preferredPayloadType:111,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{minptime:10,useinbandfec:1}},{mimeType:"audio/ISAC",kind:"audio",preferredPayloadType:103,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/CN",kind:"audio",preferredPayloadType:106,clockRate:32e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}},{mimeType:"audio/foo",kind:"audio",preferredPayloadType:107,clockRate:9e4,channels:4,rtcpFeedback:[{type:"foo-qwe-qwe"}],parameters:{foo:"lalala"}},{mimeType:"video/BAZCODEC",kind:"video",preferredPayloadType:100,clockRate:9e4,rtcpFeedback:[{type:"foo"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:101,clockRate:9e4,rtcpFeedback:[],parameters:{apt:100}},{mimeType:"video/VP8",kind:"video",preferredPayloadType:96,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{baz:"1234abcd"}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:97,clockRate:9e4,rtcpFeedback:[],parameters:{apt:96}},{mimeType:"video/VP9",kind:"video",preferredPayloadType:98,clockRate:9e4,rtcpFeedback:[{type:"goog-remb"},{type:"transport-cc"},{type:"ccm",parameter:"fir"},{type:"nack"},{type:"nack",parameter:"pli"}],parameters:{"profile-id":0}},{mimeType:"video/rtx",kind:"video",preferredPayloadType:99,clockRate:9e4,rtcpFeedback:[],parameters:{apt:98}}],headerExtensions:[{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:sdes:mid",preferredId:1},{kind:"video",uri:"urn:ietf:params:rtp-hdrext:toffset",preferredId:2},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",preferredId:3},{kind:"video",uri:"urn:3gpp:video-orientation",preferredId:4},{kind:"video",uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",preferredId:5},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/playout-delay",preferredId:6},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-content-type",preferredId:7},{kind:"video",uri:"http://www.webrtc.org/experiments/rtp-hdrext/video-timing",preferredId:8},{kind:"audio",uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",preferredId:10}]}}function sf(){return ae.deepFreeze({numStreams:{OS:2048,MIS:2048}})}function of(){return ae.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"82:5A:68:3D:36:C3:0A:DE:AF:E7:32:43:D2:88:83:57:AC:2D:65:E5:80:C4:B6:FB:AF:1A:A0:21:9F:6D:0C:AD"}],role:"auto"})}function af(){return{id:me(),iceParameters:ae.deepFreeze({iceLite:!0,password:"yku5ej8nvfaor28lvtrabcx0wkrpkztz",usernameFragment:"h3hk1iz6qqlnqlne"}),iceCandidates:ae.deepFreeze([{foundation:"udpcandidate",address:"9.9.9.9",ip:"9.9.9.9",port:40533,priority:1078862079,protocol:"udp",type:"host",tcpType:"passive"},{foundation:"udpcandidate",address:"9.9.9.9",ip:"9:9:9:9:9:9",port:41333,priority:1078862089,protocol:"udp",type:"host",tcpType:"passive"}]),dtlsParameters:ae.deepFreeze({fingerprints:[{algorithm:"sha-256",value:"A9:F4:E0:D2:74:D3:0F:D9:CA:A5:2F:9F:7F:47:FA:F0:C4:72:DD:73:49:D0:3B:14:90:20:51:30:1B:90:8E:71"},{algorithm:"sha-384",value:"03:D9:0B:87:13:98:F6:6D:BC:FC:92:2E:39:D4:E1:97:32:61:30:56:84:70:81:6E:D1:82:97:EA:D9:C1:21:0F:6B:C5:E7:7F:E1:97:0C:17:97:6E:CF:B3:EF:2E:74:B0"},{algorithm:"sha-512",value:"84:27:A4:28:A4:73:AF:43:02:2A:44:68:FF:2F:29:5C:3B:11:9A:60:F4:A8:F0:F5:AC:A0:E3:49:3E:B1:34:53:A9:85:CE:51:9B:ED:87:5E:B8:F4:8E:3D:FA:20:51:B8:96:EE:DA:56:DC:2F:5C:62:79:15:23:E0:21:82:2B:2C"}],role:"auto"}),sctpParameters:ae.deepFreeze({port:5e3,OS:2048,MIS:2048,maxMessageSize:2e6})}}function cf(){return ae.deepFreeze({id:me()})}function df({id:r,codecMimeType:e}={}){switch(e){case"audio/opus":return{id:r??me(),producerId:me(),kind:"audio",rtpParameters:ae.deepFreeze({codecs:[{mimeType:"audio/opus",payloadType:100,clockRate:48e3,channels:2,rtcpFeedback:[{type:"transport-cc"}],parameters:{useinbandfec:1,foo:"bar"}}],encodings:[{ssrc:46687003}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:ietf:params:rtp-hdrext:ssrc-audio-level",id:10}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"audio/ISAC":return{id:r??me(),producerId:me(),kind:"audio",rtpParameters:ae.deepFreeze({codecs:[{mimeType:"audio/ISAC",payloadType:111,clockRate:16e3,channels:1,rtcpFeedback:[{type:"transport-cc"}],parameters:{}}],encodings:[{ssrc:46687004}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/VP8":return{id:r??me(),producerId:me(),kind:"video",rtpParameters:ae.deepFreeze({codecs:[{mimeType:"video/VP8",payloadType:101,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"x-google-start-bitrate":1500}},{mimeType:"video/rtx",payloadType:102,clockRate:9e4,rtcpFeedback:[],parameters:{apt:101}}],encodings:[{ssrc:99991111,rtx:{ssrc:99991112}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};case"video/H264":return{id:r??me(),producerId:me(),kind:"video",rtpParameters:ae.deepFreeze({codecs:[{mimeType:"video/H264",payloadType:103,clockRate:9e4,rtcpFeedback:[{type:"nack"},{type:"nack",parameter:"pli"},{type:"ccm",parameter:"fir"},{type:"goog-remb"},{type:"transport-cc"}],parameters:{"level-asymmetry-allowed":1,"packetization-mode":1,"profile-level-id":"42e01f"}},{mimeType:"video/rtx",payloadType:104,clockRate:9e4,rtcpFeedback:[],parameters:{apt:103}}],encodings:[{ssrc:99991113,rtx:{ssrc:99991114}}],headerExtensions:[{uri:"urn:ietf:params:rtp-hdrext:sdes:mid",id:1},{uri:"http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",id:4},{uri:"http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",id:5},{uri:"urn:3gpp:video-orientation",id:11},{uri:"urn:ietf:params:rtp-hdrext:toffset",id:12}],rtcp:{cname:"wB4Ql4lrsxYLjzuN",reducedSize:!0,mux:!0}})};default:throw new TypeError(`unknown codecMimeType '${e}'`)}}function uf(){return ae.deepFreeze({id:me()})}function lf({id:r}={}){return{id:r??me(),dataProducerId:me(),sctpStreamParameters:ae.deepFreeze({streamId:666,maxPacketLifeTime:5e3,maxRetransmits:void 0})}}});var _i=D(z=>{"use strict";Object.defineProperty(z,"__esModule",{value:!0});z.debug=z.testFakeParameters=z.FakeHandler=z.enhancedEvents=z.ortc=z.parseScalabilityMode=z.detectDeviceAsync=z.detectDevice=z.Device=z.version=z.types=void 0;var pf=xr();z.debug=pf.default;z.types=pa();z.version="3.20.0";var Ni=Dc();Object.defineProperty(z,"Device",{enumerable:!0,get:function(){return Ni.Device}});Object.defineProperty(z,"detectDevice",{enumerable:!0,get:function(){return Ni.detectDevice}});Object.defineProperty(z,"detectDeviceAsync",{enumerable:!0,get:function(){return Ni.detectDeviceAsync}});var hf=ht();Object.defineProperty(z,"parseScalabilityMode",{enumerable:!0,get:function(){return hf.parse}});z.ortc=Oe();z.enhancedEvents=he();var ff=jc();Object.defineProperty(z,"FakeHandler",{enumerable:!0,get:function(){return ff.FakeHandler}});z.testFakeParameters=qc()});var Bc=D((n_,Fi)=>{"use strict";var mf=Object.prototype.hasOwnProperty,ce="~";function Gr(){}Object.create&&(Gr.prototype=Object.create(null),new Gr().__proto__||(ce=!1));function gf(r,e,t){this.fn=r,this.context=e,this.once=t||!1}function $c(r,e,t,n,s){if(typeof t!="function")throw new TypeError("The listener must be a function");var i=new gf(t,n||r,s),o=ce?ce+e:e;return r._events[o]?r._events[o].fn?r._events[o]=[r._events[o],i]:r._events[o].push(i):(r._events[o]=i,r._eventsCount++),r}function ts(r,e){--r._eventsCount===0?r._events=new Gr:delete r._events[e]}function te(){this._events=new Gr,this._eventsCount=0}te.prototype.eventNames=function(){var e=[],t,n;if(this._eventsCount===0)return e;for(n in t=this._events)mf.call(t,n)&&e.push(ce?n.slice(1):n);return Object.getOwnPropertySymbols?e.concat(Object.getOwnPropertySymbols(t)):e};te.prototype.listeners=function(e){var t=ce?ce+e:e,n=this._events[t];if(!n)return[];if(n.fn)return[n.fn];for(var s=0,i=n.length,o=new Array(i);s<i;s++)o[s]=n[s].fn;return o};te.prototype.listenerCount=function(e){var t=ce?ce+e:e,n=this._events[t];return n?n.fn?1:n.length:0};te.prototype.emit=function(e,t,n,s,i,o){var a=ce?ce+e:e;if(!this._events[a])return!1;var c=this._events[a],u=arguments.length,d,l;if(c.fn){switch(c.once&&this.removeListener(e,c.fn,void 0,!0),u){case 1:return c.fn.call(c.context),!0;case 2:return c.fn.call(c.context,t),!0;case 3:return c.fn.call(c.context,t,n),!0;case 4:return c.fn.call(c.context,t,n,s),!0;case 5:return c.fn.call(c.context,t,n,s,i),!0;case 6:return c.fn.call(c.context,t,n,s,i,o),!0}for(l=1,d=new Array(u-1);l<u;l++)d[l-1]=arguments[l];c.fn.apply(c.context,d)}else{var p=c.length,f;for(l=0;l<p;l++)switch(c[l].once&&this.removeListener(e,c[l].fn,void 0,!0),u){case 1:c[l].fn.call(c[l].context);break;case 2:c[l].fn.call(c[l].context,t);break;case 3:c[l].fn.call(c[l].context,t,n);break;case 4:c[l].fn.call(c[l].context,t,n,s);break;default:if(!d)for(f=1,d=new Array(u-1);f<u;f++)d[f-1]=arguments[f];c[l].fn.apply(c[l].context,d)}}return!0};te.prototype.on=function(e,t,n){return $c(this,e,t,n,!1)};te.prototype.once=function(e,t,n){return $c(this,e,t,n,!0)};te.prototype.removeListener=function(e,t,n,s){var i=ce?ce+e:e;if(!this._events[i])return this;if(!t)return ts(this,i),this;var o=this._events[i];if(o.fn)o.fn===t&&(!s||o.once)&&(!n||o.context===n)&&ts(this,i);else{for(var a=0,c=[],u=o.length;a<u;a++)(o[a].fn!==t||s&&!o[a].once||n&&o[a].context!==n)&&c.push(o[a]);c.length?this._events[i]=c.length===1?c[0]:c:ts(this,i)}return this};te.prototype.removeAllListeners=function(e){var t;return e?(t=ce?ce+e:e,this._events[t]&&ts(this,t)):(this._events=new Gr,this._eventsCount=0),this};te.prototype.off=te.prototype.removeListener;te.prototype.addListener=te.prototype.on;te.prefixed=ce;te.EventEmitter=te;typeof Fi<"u"&&(Fi.exports=te)});var Qm={};ko(Qm,{ACTIVATION_COLD_BOOT_AFTER_MS:()=>Lo,ACTIVATION_DEGRADED_AFTER_MS:()=>Mo,ACTIVATION_HINT_PATH:()=>cn,ACTIVATION_STILL_AFTER_MS:()=>Ao,ACTIVITY_DOM_EVENTS:()=>hs,ACTIVITY_FIELD:()=>Gi,ACTIVITY_STAMP_MIN_INTERVAL_MS:()=>Dd,ActivationMonitor:()=>Ct,App:()=>Gd,BACKOFF_BASE_MS:()=>yr,BACKOFF_MAX_ATTEMPTS:()=>Qe,BACKOFF_MAX_MS:()=>Et,CaptureController:()=>rn,CaptureUnavailableError:()=>tn,ClientTokenError:()=>rt,CreditsClient:()=>en,CreditsError:()=>_t,CreditsUnauthorizedError:()=>gr,DATA_CHANNEL_MESSAGE_CEILING:()=>du,DEFAULT_DOC_SYNC_TIMEOUT_MS:()=>po,DEFAULT_GATEWAY_URL:()=>go,DEFAULT_PRODUCE_ACK_TIMEOUT_MS:()=>Rt,DEFAULT_REFERENCE_JPEG_QUALITY:()=>cu,DEFAULT_REFERENCE_MAX_SIZE:()=>au,DEFAULT_WHEN_LIVE_TIMEOUT_MS:()=>Is,DERIVED_LEG_SEP:()=>sr,DGRAM_HEADER_BYTES:()=>ue,FOCUS_FIELD:()=>Qi,FOREGROUND_COALESCE_MS:()=>Ad,FrameReassembler:()=>dr,GENERATION_TICK_EMIT_INTERVAL_MS:()=>Ed,GENERATION_TICK_MAX_EXTRAPOLATION_MS:()=>Pd,INPUT_PRESENCE_DEFAULT_HZ:()=>nu,INPUT_PRESENCE_FIELD:()=>yo,InvalidDurationError:()=>ot,LEGACY_ACTIVATION_HINT_PATH:()=>dn,PLATFORM_DOC_NAME:()=>an,PermanentLockedError:()=>Ir,PinRequiresActiveTempError:()=>Dr,PresenceTracker:()=>or,ProduceAckTimeoutError:()=>kt,RecordingNotFoundError:()=>Er,RecordingsClient:()=>at,RecordingsError:()=>ve,RecordingsUnauthorizedError:()=>xt,RequestAbortError:()=>nt,RequestCancelledError:()=>Tt,RequestDocSyncError:()=>bt,RequestError:()=>Te,RequestTimeoutError:()=>yt,RetainNotTempError:()=>Pr,RuntimeArtifactNotFoundError:()=>Rr,RuntimeArtifactsClient:()=>Je,RuntimeArtifactsError:()=>se,RuntimeArtifactsUnauthorizedError:()=>Tr,SIGNALING_PROTOCOL_VERSION:()=>qi,STREAM_END:()=>gt,Session:()=>fr,SessionAllocationError:()=>H,SessionDirectory:()=>mr,SessionDirectoryError:()=>_e,SessionEndError:()=>ne,SessionEndUnavailableError:()=>Ae,SessionFailedError:()=>Le,StreamDirectionConflict:()=>St,TransportNegotiator:()=>lr,TransportSessionMismatchError:()=>st,TransportSessionSignaling:()=>pr,URUN_DEV_ENV:()=>_o,USER_ACTIVITY_FIELD:()=>Yi,USER_ACTIVITY_MIN_INTERVAL_MS:()=>xd,VISIBILITY_FIELD:()=>Ki,WIRE_MESSAGE_BUDGET:()=>uu,WT_CONTROL_FRAME_MAX:()=>Xi,WT_DATA_STREAM_VERSION:()=>eo,WebRtcSession:()=>hr,WebTransportSession:()=>ur,WtControlDecoder:()=>ar,WtDataStreamParser:()=>Xr,activationHintFrom:()=>xs,cameraCaptureAvailable:()=>fu,captureStillFromVideo:()=>mu,computeBackoffDelay:()=>Pt,consumeWtDataStreams:()=>ks,createActivityTracker:()=>fs,createCameraWarp:()=>gu,createClientToken:()=>Kd,createCreditsClient:()=>eu,createInputPresencePublisher:()=>su,createRecordingsClient:()=>ta,createRuntimeArtifactsClient:()=>Zo,createStore:()=>Jd,decodeStreamEnvelope:()=>os,derivedLegName:()=>wd,derivedLegRole:()=>as,describeSessionFailure:()=>wr,describeSessionPhase:()=>xo,encodeStreamEnvelope:()=>Kr,encodeWtControlFrame:()=>ys,fitWithin:()=>Ds,isDurationString:()=>fn,isPausedPhase:()=>Io,isPendingRecording:()=>Zd,isRetryableSessionError:()=>br,isWakingPhase:()=>sn,mediaRecorderChunkSource:()=>vs,normalizeReferenceImage:()=>pu,normalizeRetention:()=>ea,observeLeaveConfirm:()=>_s,observePageLifecycle:()=>ms,observePageTeardown:()=>gs,parseDgramHeader:()=>cr,prewake:()=>Ko,referenceImageErrorMessage:()=>hu,releaseSessionBeacon:()=>kr,sessionDirectory:()=>zd,sessionFailureFromMediaError:()=>Po,sharedCaptureController:()=>ru,videoStream:()=>Xd,watchGenerationTick:()=>ps,whenLive:()=>on,writeDgramHeader:()=>Ss});module.exports=Ro(Qm);var vt=class{_handlers=new Map;_ws;_onMessage;_onOpen;_listeningForOpen=!1;_pendingSends=[];_disposed=!1;constructor(e){this._ws=e,this._onMessage=t=>{if(typeof t.data!="string")return;let n;try{n=JSON.parse(t.data)}catch{console.warn("[ChannelMultiplexer] Failed to parse WebSocket message as JSON");return}if(!n.channel)return;let s=this._handlers.get(n.channel);if(s)for(let i of s)i(n)},this._ws.addEventListener("message",this._onMessage),this._onOpen=()=>{this.flushPendingSends()}}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n.delete(t),n.size===0&&this._handlers.delete(e)}}emit(e,t){if(this._disposed)return;let n=JSON.stringify({channel:e,...t});if(this._ws.readyState===WebSocket.OPEN){this._ws.send(n);return}this._ws.readyState===WebSocket.CONNECTING&&(this._pendingSends.push(n),this.listenForOpen())}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this._ws.removeEventListener("message",this._onMessage),this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1}flushPendingSends(){if(this._disposed||this._ws.readyState!==WebSocket.OPEN)return;this._ws.removeEventListener("open",this._onOpen),this._listeningForOpen=!1;let e=this._pendingSends;this._pendingSends=[];for(let t of e)this._ws.send(t)}listenForOpen(){this._listeningForOpen||(this._listeningForOpen=!0,this._ws.addEventListener("open",this._onOpen))}},wt=class{_handlers=new Map;_pendingSends=[];_target=null;_targetUnsubscribes=[];_disposed=!1;setTarget(e){if(this._disposed)return;this.detachTarget(),this._target=e;for(let[n,s]of this._handlers)for(let i of s)this._targetUnsubscribes.push(e.on(n,i));let t=this._pendingSends;this._pendingSends=[];for(let n of t)e.emit(n.channel,n.data)}rewriteSessionChannels(e,t){if(e===t)return;let n=`session:${e}:`,s=`session:${t}:`,i=new Map;for(let[o,a]of this._handlers)i.set(o.startsWith(n)?s+o.slice(n.length):o,a);this._handlers=i,this._pendingSends=this._pendingSends.map(o=>({...o,channel:o.channel.startsWith(n)?s+o.channel.slice(n.length):o.channel}))}on(e,t){if(this._disposed)return()=>{};let n=this._handlers.get(e);n||(n=new Set,this._handlers.set(e,n)),n.add(t);let s=this._target?.on(e,t);return s&&this._targetUnsubscribes.push(s),()=>{n?.delete(t),n?.size===0&&this._handlers.delete(e),s?.(),s&&(this._targetUnsubscribes=this._targetUnsubscribes.filter(i=>i!==s))}}emit(e,t){if(!this._disposed){if(this._target){this._target.emit(e,t);return}this._pendingSends.push({channel:e,data:t})}}dispose(){this._disposed=!0,this._pendingSends=[],this._handlers.clear(),this.detachTarget()}detachTarget(){for(let e of this._targetUnsubscribes)e();this._targetUnsubscribes=[],this._target=null}};var Ae=class extends Error{code="session_end_unavailable";constructor(e="[urun] this session handle cannot terminally end the session; disconnect the viewer instead",t){super(e),this.name="SessionEndUnavailableError",t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},ne=class extends Error{code;httpStatus;requestId;sessionId;constructor(e,t){super(e),this.name="SessionEndError",this.code=t.code??"session_end_failed",this.httpStatus=t.httpStatus,this.requestId=t.requestId,this.sessionId=t.sessionId,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},_e=class extends Error{code;httpStatus;constructor(e,t){super(e),this.name="SessionDirectoryError",this.code=t?.code??"session_directory_failed",this.httpStatus=t?.httpStatus,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},Te=class extends Error{requestId;code;constructor(e,t){super(e),this.name="RequestError",this.requestId=t?.requestId,this.code=t?.code,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},yt=class extends Te{timeoutMs;constructor(e,t){super(`[urun] request timed out after ${e}ms`,{requestId:t}),this.name="RequestTimeoutError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},bt=class extends Te{timeoutMs;constructor(e,t){super(`[urun] request doc-sync did not establish within ${e}ms \u2014 the request was never delivered to the runtime (the session doc never synced with the session-server; check the doc-sync transport / connection)`,{requestId:t}),this.name="RequestDocSyncError",this.timeoutMs=e,Object.setPrototypeOf(this,new.target.prototype)}},St=class extends Error{stream;owner;attempted;constructor(e,t,n){super(`[urun] stream "${e}" is already produced by the ${t}; this (${n}) peer cannot also produce it \u2014 a named stream has exactly one producer (consume it instead, or use a distinct name for the reverse direction)`),this.name="StreamDirectionConflict",this.stream=e,this.owner=t,this.attempted=n,Object.setPrototypeOf(this,new.target.prototype)}},Rt=15e3,kt=class extends Error{kind;stream;timeoutMs;constructor(e,t){let n=t?.timeoutMs??Rt,s=t?.stream??e,i=s!==e?` "${s}"`:"";super(`[urun] SFU did not ack producer ${e}${i} within ${Math.round(n/1e3)}s \u2014 the server never replied to 'produce'. The runtime's inbound port for this stream is likely unadvertised (a cold or capacity-queued runtime), so the SFU has nothing to forward the track to; the published track never reached the runtime.`),this.name="ProduceAckTimeout",this.kind=e,this.stream=s,this.timeoutMs=n,Object.setPrototypeOf(this,new.target.prototype)}},nt=class extends Te{constructor(e){super("[urun] request aborted",{requestId:e}),this.name="RequestAbortError",Object.setPrototypeOf(this,new.target.prototype)}},Tt=class extends Te{constructor(e){super("[urun] request cancelled: session disconnected",{requestId:e}),this.name="RequestCancelledError",Object.setPrototypeOf(this,new.target.prototype)}},ku=/^\[urun\] (?:timed out waiting for session allocation at|session allocation poll failed at|session allocation failed at|session allocation at|session create at) \S+(?::[ \t]+|[ \t]+|$)/;function Tu(r){return r.replace(/\bhttps?:\/\/[^\s)]+/g,"the session gateway")}function Co(r){let e=r.replace(ku,"");return Tu(e||r.replace(/^\[urun\] /,""))}function Eo(r){let e=r.error?.httpStatus;if(e===401||e===403)return"The backend rejected this client \u2014 sign in again or check the auth token / org access.";if(r.error?.code==="session_archived")return"This session is archived \u2014 call directory.unarchive(sessionId) (the session directory's un-archive verb), then reconnect with the same id.";let t=r.error?.retryAfterSeconds,n=t!==void 0?` It asked for ${Math.round(t)}s.`:"";return e===429?`The backend is shedding load \u2014 its admission queue is full, so this is capacity, not your request.${n} The SDK already retried with backoff; try again in a moment.`:e===408?`The request timed out before the backend answered \u2014 that is a timeout, not a verdict on your request.${n} The SDK already retried with backoff; try again in a moment.`:e!==void 0&&e>=500?"The backend is having an outage (nothing is wrong with your request) \u2014 the SDK already retried with backoff, so try again shortly and report the status above if it persists.":"The backend could not create a session \u2014 check the app/function name and auth, then retry."}function wr(r,e){let t=e.error?.reason,n=e.elapsedMs!==void 0?Math.round(e.elapsedMs/1e3):void 0;switch(r){case"create-failed":{let s=e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:"",i=e.error?.code;return i==="queue_ttl_expired"||i==="stale_poll_expired"?{message:`[urun] the queued session REQUEST timed out while waiting${s} (${i}) \u2014 the session itself is untouched`,hint:"Nothing was lost and nothing needs replacing: connect again with the same session and the control plane re-admits the request (a poll that arrives in time re-drives it on its own)."}:i==="session_archived"?{message:`[urun] this session is archived${s} \u2014 un-archive it before resuming`+(t?`: ${Co(t)}`:""),hint:Eo(e)}:{message:`[urun] session create failed${s}${t?`: ${Co(t)}`:""}`,hint:Eo(e)}}case"never-live":{let s=n!==void 0?` after ${n}s`:"",i=` (last server status: ${e.lastServerStatus??"none"})`;return e.error?.code==="expired"?{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} expired before media connected${s} \u2014 the control plane reclaims sessions whose media transport never establishes (~80s after create)`,hint:"Retry to mint a fresh session, and connect promptly after start (a backgrounded tab or paused debugger can miss the window)."}:e.sessionId?{message:`[urun] session ${e.sessionId} was created but never went live${s}${i} \u2014 the backend is busy or wedged (no runtime picked the session up)`,hint:"The backend is at capacity or stuck. Retry in a moment; if it persists, the session id above is what to report."}:{message:`[urun] no session went live${s} (phase=${e.phase}${e.lastServerStatus?`, last server status: ${e.lastServerStatus}`:""})`,hint:"The session never got past admission. Retry; if it persists, check the backend deployment."}}case"transport-failed":return e.error?.code==="transport-consumed"?{message:`[urun] the retry reused a session whose media transport was already connected${e.sessionId?` (id ${e.sessionId})`:""} \u2014 the session was consumed by an earlier attempt`,hint:"Start a fresh session (reload the page) \u2014 this session leg cannot be connected again."}:{message:`[urun] media/transport connection failed${t?`: ${t}`:""} (transport state: ${e.transportState})`,hint:"The network is likely blocking the media connection (WebRTC/WebSocket) \u2014 try a different network or disable VPN/proxy, then retry."};case"media-permission":return{message:`[urun] microphone/camera unavailable${t?`: ${t}`:""}`,hint:e.error?.code==="NotFoundError"||e.error?.code==="OverconstrainedError"?"No matching input device was found \u2014 connect or select a microphone/camera and retry.":"Allow microphone/camera access for this site (browser permission \u2014 or, when embedded, the parent page's permissions policy), then retry."};case"runtime-failed":return{message:`[urun] session${e.sessionId?` ${e.sessionId}`:""} failed at runtime${t?`: ${t}`:""}`,hint:"The session function crashed on the backend \u2014 check the app logs. The session itself is parked, not gone: attach to it again once the app is fixed."};case"produce-timeout":return{message:`[urun] publishing a track timed out${t?`: ${t}`:""} \u2014 the SFU never acked the produce (the runtime\u2019s inbound port for the stream was not advertised in time)`,hint:"The runtime was still cold or the backend was at capacity when the track was published. Retry in a moment; if it persists, the backend never opened the stream to receive it."};case"insufficient-credits":return{message:`[urun] session create refused${e.error?.httpStatus!==void 0?` (HTTP ${e.error.httpStatus})`:""} \u2014 the org has insufficient credits${t?`: ${t}`:""}`,hint:"Out of credits \u2014 add credits to keep running sessions."}}}var Le=class extends Error{kind;status;hint;constructor(e,t,n){let{message:s,hint:i}=wr(e,t);super(s),this.name="SessionFailedError",this.kind=e,this.status=t,this.hint=i,n?.cause!==void 0&&(this.cause=n.cause),Object.setPrototypeOf(this,new.target.prototype)}};function Po(r,e){if(r instanceof Le)return r;let t=r instanceof Error?r:new Error(String(r)),n={phase:e?.phase??"idle",transportState:e?.transportState??"disconnected",...e,error:{reason:t.message,code:t.name,kind:"media-permission"}};return new Le("media-permission",n,{cause:r})}var st=class extends Error{code="transport_session_mismatch";connectedSessionId;requestedSessionId;constructor(e,t){super(`[urun] cannot retarget a connected transport to a different session: this leg is live on ${e??"(unknown)"} but setConnection() asked for ${t} \u2014 disconnect() this leg first (or use a fresh session handle)`),this.name="TransportSessionMismatchError",this.connectedSessionId=e,this.requestedSessionId=t,Object.setPrototypeOf(this,new.target.prototype)}},H=class extends Error{httpStatus;code;balanceCredits;platformStatus;retryAfterSeconds;constructor(e,t){super(e),this.name="SessionAllocationError",this.httpStatus=t?.httpStatus,this.code=t?.code,this.balanceCredits=t?.balanceCredits,this.platformStatus=t?.platformStatus,this.retryAfterSeconds=t?.retryAfterSeconds,t?.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}};function sn(r){if(!r)return!1;let e=typeof r=="string"?r:r.name;return e==="queued"||e==="unavailable"||e==="provisioning"||e==="waiting_for_capacity"}function Io(r){return r?(typeof r=="string"?r:r.name)==="paused":!1}var Is=45e3,Do=6e5;function on(r,e={}){let{timeout:t=Is,signal:n}=e;return new Promise((s,i)=>{if(n?.aborted){i(n.reason instanceof Error?n.reason:new Error("whenLive aborted"));return}if(r.phase?.name==="live"){s();return}if(r.phase?.name==="error"){let v=r.phase,y=r.status??{phase:v.name,transportState:"disconnected",sessionId:v.sessionId,requestId:v.requestId,queue:v.queue,error:v.error,region:v.region};i(new Le(v.error?.kind??"transport-failed",y));return}let a,c,u=!1,d=v=>{u||(u=!0,c!==void 0&&clearTimeout(c),n?.removeEventListener("abort",l),a?.(),v?i(v):s())},l=()=>{d(n?.reason instanceof Error?n.reason:new Error("whenLive aborted"))};n?.addEventListener("abort",l,{once:!0});let p=()=>{let v=r.phase;return r.status??{phase:v?.name??"idle",transportState:"disconnected",sessionId:v?.sessionId,requestId:v?.requestId,queue:v?.queue,error:v?.error,region:v?.region}},f=v=>d(new Le(v,p())),h=Date.now(),m=t,g=()=>{if(m<=0)return;c!==void 0&&clearTimeout(c);let v=h+m-Date.now();c=setTimeout(()=>{let y=p();y.elapsedMs===void 0&&(y.elapsedMs=m),d(new Le("never-live",y))},Math.max(0,v))},_=v=>{u||m<=0||v?.runtime?.wake?.expectedWakePath==="cold-boot"&&(Do<=m||(m=Do,g()))};g(),a=r.onPhase(v=>{v?.name==="live"?d():v?.name==="error"?f(v.error?.kind??"transport-failed"):_(v)}),u||_(r.phase),u&&a()})}function xo(r){switch(r.name){case"idle":return"Initializing\u2026";case"unavailable":return"Starting the app\u2026";case"queued":return r.queue?`Waiting in queue (position ${r.queue.position} of ${r.queue.depth})\u2026`:r.runtime?.state==="busy"?"All runtimes are busy \u2014 waiting for capacity\u2026":"Waiting for capacity\u2026";case"provisioning":return r.runtime?.state==="starting"?"Starting model\u2026":"Provisioning\u2026";case"waiting_for_capacity":return r.queue?`Waiting for GPU capacity (position ${r.queue.position} of ${r.queue.depth})\u2026`:"Waiting for GPU capacity";case"connecting":return"Connecting\u2026";case"live":return"Live";case"paused":return Ru(r.reason);case"error":{if(r.error?.kind==="insufficient-credits")return"Out of credits \u2014 add credits to keep running sessions.";let e=r.error?.kind;if(e){let{message:t,hint:n}=wr(e,{phase:r.name,transportState:"disconnected",sessionId:r.sessionId,requestId:r.requestId,queue:r.queue,error:r.error});return`${t.replace(/^\[urun\] /,"")} \u2014 ${n}`}return r.error?.reason?`Session failed \u2014 ${r.error.reason}`:"Session failed"}case"unknown":return r.reason?`Session in an unrecognized state ("${r.reason}") \u2014 the client SDK may be out of date`:"Session in an unrecognized state \u2014 the client SDK may be out of date"}}function Ru(r){switch(r){case"client_ended":return"Paused \u2014 you hung up. Resume any time.";case"client_paused":return"Paused \u2014 you paused it. Resume any time.";case"client_detached":return"Paused \u2014 this device let go. Resume any time.";case"client_gone":return"Paused \u2014 every device disconnected. Resume any time.";case"session_ended":case"ended":case"closed":return"Paused \u2014 the compute was released. Resume any time.";case"idle_timeout":return"Paused \u2014 idle. Resume any time.";case"max_session_age":return"Paused \u2014 reached its maximum length. Resume any time.";case"credits_exhausted":return"Paused \u2014 out of credits. Add credits, then resume.";case"capacity_pressure":return"Paused \u2014 the GPU was reclaimed while the platform was under load. Resume any time.";case"control_plane_release":return"Paused \u2014 the platform reclaimed the compute. Resume any time.";case"superseded":return"Paused \u2014 another client attached. Resume any time.";case"superseded_by_redial":return"Paused \u2014 a newer connection from this session took over. Resume any time.";case"connect_deadline":return"Paused \u2014 the runtime never finished connecting in time. Resume to try again.";case"adoption_expired":return"Paused \u2014 the runtime was assigned but never picked the session up. Resume to try again.";case"media_lane_bind_failed":return"Paused \u2014 the audio/video lane could not be set up. Resume to try again.";case"lease_lost":return"Paused \u2014 the runtime stopped renewing its lease. Resume any time.";case"presence_unconfirmed":return"Paused \u2014 the platform could not confirm anyone was still attached. Resume any time.";case"runtime_inert":case"assignment_unconfirmable":return"Paused \u2014 the runtime never acknowledged its assignment. Resume to try again.";case"runtime_unreachable":return"Paused \u2014 the platform could not reach the runtime. Resume to try again.";case"runtime_silent":return"Paused \u2014 the runtime stopped sending audio/video. Resume to try again.";case"assignment_undelivered":return"Paused \u2014 the assignment never reached a runtime. Resume to try again.";case"dispatch_released":return"Paused \u2014 the worker finished and gave its GPU seat back. Resume any time.";case"dispatch_parked":return"Paused \u2014 the worker finished and parked the session. Resume any time.";case"runtime_swap_exhausted":return"Paused \u2014 the platform ran out of runtimes to try. Resume any time.";case"dispatch_failed":return"Paused \u2014 handing the session to a worker did not succeed. Resume to try again.";default:return r?`Paused \u2014 ${r}. Resume any time.`:"Paused \u2014 resume any time."}}var Ao=15e3,Lo=45e3,Mo=12e4,an="platform",cn="activation",dn="desired.activation";function xs(r){if(typeof r=="string"&&r.length>0)return r;if(r&&typeof r=="object"){let e=r.note;if(typeof e=="string"&&e.length>0)return e}}var Cu=[{state:"still-activating",afterMs:15e3},{state:"cold-boot",afterMs:45e3},{state:"degraded",afterMs:12e4}],Ct=class{constructor(e){this._options=e;this._offPhase=e.onPhase(t=>{if(!this._stopped)if(t?.name==="live"){if(this._liveAt===null){this._liveAt=Date.now();for(let n of this._watches.values())this._arm(n)}}else(t?.name==="error"||t?.name==="paused")&&this._park()})}_options;_watches=new Map;_handlers=new Set;_liveAt=null;_stopped=!1;_offPhase=null;_park(){this._liveAt=null;for(let e of this._watches.values())if(!e.done){for(let t of e.timers)clearTimeout(t);e.timers=[],e.startedAt=null,e.lastEvent=null}}watch(e,t){if(this._stopped||this._watches.has(e))return;let n={name:e,stream:t,startedAt:null,done:!1,timers:[],cleanups:[],lastEvent:null};this._watches.set(e,n),this._hookFirstMediaSignals(n),!n.done&&this._liveAt!==null&&this._arm(n)}unwatch(e){let t=this._watches.get(e);!t||t.done||this._settle(t)}onActivation(e){for(let t of this._watches.values())!t.done&&t.lastEvent&&e(t.lastEvent);return this._handlers.add(e),()=>this._handlers.delete(e)}dispose(){if(!this._stopped){this._stopped=!0;for(let e of this._watches.values())e.done||this._settle(e);this._offPhase?.(),this._offPhase=null,this._handlers.clear()}}_hookFirstMediaSignals(e){let t=n=>{if(!(!n||e.done)){if(n.muted===!0&&typeof n.addEventListener=="function"){let s=()=>this._firstMedia(e);n.addEventListener("unmute",s,{once:!0}),e.cleanups.push(()=>n.removeEventListener?.("unmute",s));return}this._firstMedia(e)}};e.cleanups.push(e.stream.on("track",n=>t(n))),this._options.onData&&e.cleanups.push(this._options.onData(e.name,()=>this._firstMedia(e))),t(e.stream.track)}_arm(e){if(!(e.done||e.startedAt!==null||this._stopped)){e.startedAt=Date.now(),this._emit(e,"activating",0);for(let t of Cu){let n=setTimeout(()=>{e.done||this._stopped||this._emit(e,t.state,Date.now()-e.startedAt)},t.afterMs);n.unref?.(),e.timers.push(n)}}}_firstMedia(e){if(e.done||this._stopped)return;let t=e.startedAt;this._settle(e),this._emit(e,"first-media",t===null?0:Date.now()-t)}_settle(e){e.done=!0;for(let t of e.timers)clearTimeout(t);e.timers=[];for(let t of e.cleanups.splice(0))t()}_emit(e,t,n){let s={state:t,elapsedMs:n,stream:e.name},i=xs(this._options.hint());i!==void 0&&(s.hint=i),e.lastEvent=s;for(let o of Array.from(this._handlers))o(s)}};var yr=500,Et=15e3,Qe=6;function Pt(r,e=Math.random){if(!Number.isFinite(r)||r<0)throw new Error(`[urun] computeBackoffDelay: attempt must be a non-negative number, got ${r}`);let t=Math.min(Et,yr*2**r);return Math.round(e()*t)}function br(r){if(r instanceof H){let e=r.httpStatus;return e===408||e===429||e!==void 0&&e>=500}return r instanceof Error?r.name==="TypeError"||r.name==="TimeoutError"||r.name==="AbortError":!1}var Oo=10,Eu=.5,un=Oo;function As(){return un<1?!1:(un-=1,!0)}function Ls(){un=Math.min(Oo,un+Eu)}var Pu="session-api.prod.cloud.urun.sh",Du=["https://session-api.use2.prod.cloud.urun.sh","https://session-api.usw2.prod.cloud.urun.sh"];function Y(r){return r.trim().replace(/\/+$/,"")}function Sr(r,e){let t=[],n=s=>{if(!s)return;let i=Y(s);i&&!t.includes(i)&&t.push(i)};n(r);for(let s of e??[])n(s);for(let s of nl(r))n(s);return t}function kr(r){try{if(typeof fetch!="function")return;let e=Y(r.baseUrl),t=r.sessionId?`${e}/api/sessions/${encodeURIComponent(r.sessionId)}/end`:`${e}/api/session-requests/${encodeURIComponent(r.requestId)}/cancel`;fetch(t,{method:"POST",headers:r.reason!==void 0?{...Ce(r,r.jwt),"Content-Type":"application/json"}:Ce(r,r.jwt),...r.reason!==void 0?{body:JSON.stringify({reason:r.reason})}:{},keepalive:!0}).catch(()=>{})}catch{}}async function Os(r){try{let e=`${Y(r.baseUrl)}/api/session-requests/${encodeURIComponent(r.requestId)}/cancel`,t=await Me(r);if(r.getAccessToken&&!t)throw new ne("[urun] session request cancel refused: getAccessToken resolved no token (an unauthenticated cancel is never sent)",{requestId:r.requestId,code:"no_access_token"});let n=await fetch(e,{method:"POST",headers:Ce(r,t),keepalive:!0});if((n.status===401||n.status===403)&&r.getAccessToken){let o=await Me(r,{forceRefresh:!0,reason:"unauthorized"});o&&o!==t&&(n=await fetch(e,{method:"POST",headers:Ce(r,o),keepalive:!0}))}let s=await It(n);if(!n.ok)throw new ne(`[urun] session request cancel failed: ${hn(s,n.status)}`,{requestId:r.requestId,code:s.error_code,httpStatus:n.status});let i=String(s.status??"");if(i==="cancelled"||i==="canceled"||i==="closed")return{status:"canceled",requestId:r.requestId};if(i==="failed"||i==="rejected"||i==="expired")return{status:"canceled",requestId:r.requestId,platformStatus:i};throw new ne(`[urun] session request cancel returned an unrecognized request status ${JSON.stringify(i)} (recognized: cancelled/canceled, closed, failed, rejected, expired)`,{requestId:r.requestId,code:"invalid_release_response",httpStatus:n.status})}catch(e){throw e instanceof ne?e:new ne("[urun] session request cancel failed",{requestId:r.requestId,cause:e})}}async function Us(r){let e;try{e=await Ns(r,`/api/sessions/${encodeURIComponent(r.sessionId)}/end`,{method:"POST",keepalive:!0},"session end")}catch(s){if(s instanceof ne)throw s;let i=s;throw new ne(i?.message??"[urun] session end request failed",{sessionId:r.sessionId,...i?.code!==void 0?{code:i.code}:{},...i?.httpStatus!==void 0?{httpStatus:i.httpStatus}:{},cause:s})}let t=String(e.status??""),n=e.pause_reason;if(t==="paused")return{status:"paused",sessionId:String(e.logical_id??e.id??r.sessionId),reason:typeof n=="string"&&n.length>0?n:"client_ended"};throw new ne(`[urun] session end returned ${JSON.stringify(t)} for session ${r.sessionId} \u2014 an end PARKS the session, so the only contract-valid answer is "paused" (a terminal word on this route would be a session-plane terminal write, which is forbidden)`,{sessionId:r.sessionId,code:"invalid_end_response"})}function qo(r){if(typeof r!="string"||r.length===0)return null;let e=new Date(r);return Number.isFinite(e.getTime())?e:null}var Iu=120,xu=1e3,Au=20,Lu=5,Mu=500,$o=1e4,Ou=new Set([502,503,504]),Uu=Qe,Nu=2,Fu=50,Uo=1e4;async function No(r,e){let t=Date.now()+Uo;for(;;){await Dt(Fu);let n=await Me(r);if(n)return n;if(Date.now()>=t)throw new H(`[urun] session allocation at ${e} never got an access token: the wired getAccessToken resolved nothing within ${Math.round(Uo/1e3)}s (no unauthenticated request was sent)`)}}function Wu(r,e){if(!r)return null;try{let t=new URL(r),n=e?new URL(Y(e)):null,s=t.pathname==="/api/sessions/create"||t.pathname==="/api/sessions/create/";return t.protocol!=="https:"||!s||!Bu(t,n)?null:Y(t.origin)}catch{return null}}function ju(r,e){if(!r||!r.trim())return{outcome:"absent"};if(!qu(e))return{outcome:"bootstrap-only"};let t=r.includes("://")?r:`https://${r}`,n;try{n=new URL(t)}catch{return{outcome:"rejected",reason:"not a parseable URL or host"}}return n.protocol!=="https:"?{outcome:"rejected",reason:`scheme ${n.protocol} is not https:`}:n.pathname!=="/"&&n.pathname!==""?{outcome:"rejected",reason:`expected a bare origin, got path ${n.pathname}`}:pn(n.hostname)?{outcome:"pinned",base:Y(n.origin)}:{outcome:"rejected",reason:`host ${n.hostname} is outside the urun.sh trust set`}}function qu(r){if(!r)return!1;try{let e=new URL(Y(r));return e.protocol==="https:"&&pn(e.hostname)}catch{return!1}}function $u(r){let e=Y(r);try{return Y(new URL(e).origin)}catch{return e}}function Bu(r,e){return pn(r.hostname)&&(!e||pn(e.hostname))}function pn(r){let e=r.toLowerCase();return e==="urun.sh"||e.endsWith(".urun.sh")}function Hu(r){let e=r instanceof H?r.retryAfterSeconds:void 0;return e===void 0||!Number.isFinite(e)||e<=0?0:Math.min(e*1e3,Et)}function Bo(r,e){let t=Hu(e);return t>0?Math.max(r,Date.now()+t):r}async function Ho(r){let e=Sr(r.baseUrl,r.fallbackUrls),t=null,n=0,s=e.length>1;for(let i=0;i<Qe;i++){for(let o of e)try{let a=await Vu(o,r,{pollAttempts:Iu,retryAfterLimitMs:s?xu:void 0});return Ls(),a}catch(a){if(t=a instanceof Error?a:new Error(String(a)),n=Bo(n,t),t instanceof Re||t instanceof it||Ku(t))throw t}if(!br(t))break;if(i+1<Qe){if(!As())break;await Dt(Math.max(Pt(i),n-Date.now()))}}throw t??new Error("[urun] session allocation failed")}async function Vu(r,e,t){let n,s,i,o=$u(r),a=0,c=new Set,u=Date.now()+t.pollAttempts*$o;for(let d=0;d<t.pollAttempts;d++){s=i??await Me(e),i=void 0,e.getAccessToken&&!s&&(s=await No(e,o));let l=!!n,p=Date.now(),f;if(n){let y=0,S=0,w=b=>{let L=Math.min(Et,yr*2**y),q=Math.max(Math.ceil(L/2),Pt(y));return y+=1,Math.min(Math.max(b,q),Math.max(0,u-Date.now()))};for(;;){let b=u-Date.now();if(b<=0)throw ln(o,!0);let L=Math.max(1,Math.min(Au,Math.floor(b/1e3)));p=Date.now();try{f=await fetch(`${o}/api/session-requests/${encodeURIComponent(n)}?wait_s=${L}`,{headers:Ce(e,s),redirect:"manual",signal:el((L+Lu)*1e3)})}catch(W){if(S+=1,S>=Uu)throw new it(`[urun] session allocation poll failed at ${o} after ${S} consecutive transport failures`,{cause:W});let B=w(0);if(B<=0)throw ln(o,!0);await Dt(B);continue}if(S=0,!Ou.has(f.status))break;try{await f.body?.cancel()}catch(W){throw new it(`[urun] session allocation poll response cleanup failed at ${o}`,{cause:W})}let q=w(Wo(f,{},t.retryAfterLimitMs));if(q<=0)throw ln(o,!0);await Dt(q)}}else f=await fetch(`${o}/api/sessions/create`,{method:"POST",redirect:"manual",headers:{...Ce(e,s),"Content-Type":"application/json","Idempotency-Key":e.idempotencyKey},body:JSON.stringify(zu(e))});if(f.type==="opaqueredirect"||f.status>=300&&f.status<400){try{await f.body?.cancel()}catch{}throw new Re(`[urun] ${l?"session poll":"session create"} at ${o} answered an HTTP redirect (status ${f.status}) \u2014 browsers cannot follow a cross-origin redirect with credentials; the control plane must emit the JSON redirect envelope ({status:"redirect", location})`)}let h=await It(f);if(!n&&h.status==="redirect"){let y=Wu(h.location,o);if(!y)throw new H(`[urun] session create at ${o} answered a redirect envelope without a usable location (${JSON.stringify(h.location??null)}) \u2014 refusing to re-issue an authenticated create to an untrusted target`);if(y===o)throw new H(`[urun] session create at ${o} redirected to ITSELF \u2014 control-plane region apex map misconfiguration`);if(a>=Nu)throw new H(`[urun] session create followed ${a} region redirects and was redirected AGAIN (${o} -> ${y}) \u2014 region forward loop, giving up loudly`);a+=1,o=y;continue}if(h.request_id)try{e.onRequest?.({requestId:h.request_id,baseUrl:o,...h.session_id?{sessionId:h.session_id}:{}})}catch{}if(f.ok&&(h.status==="allocated"||!h.status&&!!h.session_id)&&!!h.session_id){let y=h.session_id,S=ju(h.session_api_base,o);if(S.outcome==="rejected")throw new Re(`[urun] gateway allocated session ${h.session_id} with an unusable session_api_base (${JSON.stringify(h.session_api_base)}): ${S.reason} \u2014 refusing to pin the session to a region it may not belong to`);if(S.outcome==="pinned"&&S.base!==o&&(o=S.base,h.request_id))try{e.onRequest?.({requestId:h.request_id,baseUrl:o,...h.session_id?{sessionId:h.session_id}:{}})}catch{}let w=Qo(h.ws_url,o,y,"gateway allocated session");return{baseUrl:o,sessionId:y,wsUrl:w,endsAt:qo(h.ends_at),response:h}}if(f.status===202||h.status==="pending"||h.status==="queued"||h.queued){if(n=h.request_id||n,!n)throw new Error("[urun] gateway queued session without request_id");if(e.onAdmission)try{e.onAdmission(Zu(h,n))}catch{}let y=Date.now()-p<Mu;l&&y&&await Dt(Wo(f,h,t.retryAfterLimitMs));continue}if((f.status===401||f.status===403)&&e.getAccessToken&&h.error_code!=="session_name_not_yours"){let y=s??"";c.add(y);let S=await Me(e,{forceRefresh:!0,reason:"unauthorized"});if(S&&!c.has(S)){i=S;continue}if(S===void 0){let w=await No(e,o);if(!c.has(w)){i=w;continue}}}let g=hn(h,f.status),_=h.error_code??(f.status===402?"insufficient_credits":void 0),v=l?it:H;throw new v(`[urun] session allocation failed at ${o}: ${g}`,{httpStatus:f.status,code:_,balanceCredits:typeof h.balance_credits=="number"?h.balance_credits:void 0,platformStatus:h.status,retryAfterSeconds:js(f,h)})}throw ln(o,!!n)}function ln(r,e=!1){let t=e?it:H;return new t(`[urun] timed out waiting for session allocation at ${r}`)}function Ce(r,e){let t={"X-Tenant-Id":r.orgId,"X-Auth-Provider":r.authProvider||"default","X-User-Id":"anonymous"};return e&&(t.Authorization=`Bearer ${e}`),t}async function Me(r,e){return r.getAccessToken?await r.getAccessToken(e)??void 0:r.jwt}function zu(r){let e=r.priority==="preempt";return{app:r.app,function:r.functionName,gpus:1,idempotency_key:r.idempotencyKey,...r.sessionKey&&!e?{logical_id:r.sessionKey}:{},...r.label&&!r.sessionKey?{label:r.label}:{},...e?{priority:"preempt"}:{}}}async function Ns(r,e,t,n){let s=await Me(r);if(r.getAccessToken&&!s)throw new _e(`[urun] ${n} refused: getAccessToken resolved no token (an unauthenticated request is never sent)`,{code:"no_access_token"});let i=Sr(r.baseUrl,r.fallbackUrls),o;for(let a of i){let c=`${Y(a)}${e}`,u=p=>fetch(c,{method:t.method,headers:t.body!==void 0?{...Ce(r,p),"Content-Type":"application/json"}:Ce(r,p),...t.body!==void 0?{body:JSON.stringify(t.body)}:{},...t.keepalive?{keepalive:!0}:{}}),d;try{if(d=await u(s),(d.status===401||d.status===403)&&r.getAccessToken){let p=await Me(r,{forceRefresh:!0,reason:"unauthorized"});p&&p!==s&&(d=await u(p))}}catch(p){o=p;continue}let l=await It(d);if(!d.ok)throw new _e(`[urun] ${n} failed: ${hn(l,d.status)}`,{code:l.error_code,httpStatus:d.status});return l}throw new _e(`[urun] ${n} request failed`,{cause:o})}async function Vo(r){let e=new URLSearchParams;r.app&&e.set("app",r.app),r.functionName&&e.set("function",r.functionName),r.includeArchived&&e.set("include_archived","true"),r.limit!==void 0&&e.set("limit",String(r.limit)),r.cursor&&e.set("cursor",r.cursor);let t=e.toString(),n=await Ns(r,`/api/sessions${t?`?${t}`:""}`,{method:"GET"},"session list");if(!Array.isArray(n?.sessions))throw new _e("[urun] session list returned no `sessions` array \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_response"});return{rows:n.sessions,nextCursor:n.next_cursor??null}}async function Fs(r){let e=r.archived?"archive":"unarchive";await Ns(r,`/api/sessions/${encodeURIComponent(r.sessionId)}/${e}`,{method:"POST"},`session ${e}`)}async function zo(r){await Us(r)}async function Go(r){let e=Sr(r.baseUrl,r.fallbackUrls),t=null,n=0;for(let s=0;s<Qe;s++){for(let i of e)try{let o={baseUrl:i,app:"",functionName:"",orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider,idempotencyKey:""},a=`${Y(i)}/api/sessions/${encodeURIComponent(r.sessionId)}/viewer-connect`,c=await Me(o);if(r.getAccessToken&&!c)throw new H(`[urun] viewer-connect for ${r.sessionId} refused: getAccessToken resolved no token (an unauthenticated viewer-connect is never sent)`);let u=await fetch(a,{headers:Ce(o,c)});if((u.status===401||u.status===403)&&r.getAccessToken){let p=await Me(o,{forceRefresh:!0,reason:"unauthorized"});p&&p!==c&&(u=await fetch(a,{headers:Ce(o,p)}))}if(!u.ok){let p=await It(u);throw new H(`[urun] viewer-connect for ${r.sessionId} failed: `+hn(p,u.status),{httpStatus:u.status,retryAfterSeconds:js(u,p)})}let d=await It(u),l=Qo(d.ws_url,i,r.sessionId,"viewer-connect");return Ls(),{baseUrl:Y(i),sessionId:r.sessionId,wsUrl:l,endsAt:qo(d.ends_at),response:d}}catch(o){if(t=o instanceof Error?o:new Error(String(o)),n=Bo(n,t),t instanceof Re)throw t}if(!br(t))break;if(s+1<Qe){if(!As())break;await Dt(Math.max(Pt(s),n-Date.now()))}}throw t??new Error("[urun] viewer-connect failed")}async function Ko(r){try{let e=Y(r.baseUrl),t=await Me(r);if(r.getAccessToken&&!t)return{status:"unavailable"};let n=await fetch(`${e}/api/sessions/prewake`,{method:"POST",headers:{...Ce(r,t),"Content-Type":"application/json"},body:JSON.stringify({app:r.app,function:r.functionName})});if(n.status===404)return{status:"unknown-app"};if(!n.ok)return{status:"unavailable"};let s=await It(n),i={status:s.status==="prebound"?"prebound":"warming"};return typeof s.expires_at=="string"&&(i.expiresAt=s.expires_at),typeof s.warm_capable=="boolean"&&(i.warmCapable=s.warm_capable),i}catch(e){return console.debug?.("[urun] prewake failed (advisory, ignored):",e),{status:"unavailable"}}}async function It(r){try{let e=await r.json();return e&&typeof e=="object"?e:{}}catch{return{}}}function hn(r,e){let t=r.error_code,n=r.error_message||r.message||r.error,s=t&&n&&n!==t?`${t}: ${n}`:n||t;return s?`${s} (HTTP ${e})`:`HTTP ${e}`}var Gu=new Set([400,402,409]);function Ku(r){return r instanceof H&&r.httpStatus!==void 0&&Gu.has(r.httpStatus)}var Yu=new Set(["capture-attested","no-portable-golden","portable-golden-release-mismatch","portable-golden-attestation-invalid"]);function Yo(r){return typeof r=="object"&&r!==null&&!Array.isArray(r)}function Ms(r){return typeof r=="string"&&r.trim().length>0}function Fo(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>0}function Qu(r){return typeof r=="number"&&Number.isSafeInteger(r)&&r>=0}function Ju(r){if(Yo(r)&&!(!Ms(r.snapshot_id)||!Ms(r.snapshot_compat_key)||!Fo(r.artifact_size_bytes)||!Fo(r.durable_arena_bytes)||r.volatile_arena_bytes!==0||!Qu(r.uncovered_weight_bytes)))return{snapshotId:r.snapshot_id,snapshotCompatKey:r.snapshot_compat_key,artifactSizeBytes:r.artifact_size_bytes,durableArenaBytes:r.durable_arena_bytes,volatileArenaBytes:0,uncoveredWeightBytes:r.uncovered_weight_bytes}}function Xu(r){if(!Yo(r)||r.schema!=="urun.runtime.wake.v1"||r.portability!=="portable"&&r.portability!=="none"||r.expected_wake_path!=="portable-golden-restore"&&r.expected_wake_path!=="cold-boot"||typeof r.reason_code!="string"||!Yu.has(r.reason_code)||r.expectation_basis!=="snapshot-registry"||r.restore_observation!=="not-observed")return;let e=r.reason_code;if(r.portability==="portable"&&r.expected_wake_path==="portable-golden-restore"&&e==="capture-attested"){let t=Ju(r.golden);return t?{schema:"urun.runtime.wake.v1",portability:"portable",expectedWakePath:"portable-golden-restore",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed",golden:t}:void 0}if(r.portability==="none"&&r.expected_wake_path==="cold-boot"&&e!=="capture-attested"&&r.golden===void 0)return{schema:"urun.runtime.wake.v1",portability:"none",expectedWakePath:"cold-boot",reasonCode:e,expectationBasis:"snapshot-registry",restoreObservation:"not-observed"}}function Ws(r){if("serving_region"in r)return typeof r.serving_region=="string"&&r.serving_region.length>0?r.serving_region:null}function Zu(r,e){let n={status:typeof r.status=="string"&&r.status.length>0?r.status:r.queued?"queued":"pending",requestId:e};Ms(r.session_id)&&(n.sessionId=r.session_id);let s=Ws(r);s!==void 0&&(n.region=s),typeof r.reason=="string"&&r.reason.length>0&&(n.reason=r.reason),typeof r.decision_reason=="string"&&r.decision_reason.length>0&&(n.decisionReason=r.decision_reason),typeof r.provisioning_refusal_source=="string"&&r.provisioning_refusal_source.length>0&&(n.refusalSource=r.provisioning_refusal_source),typeof r.provisioning_refusal_message=="string"&&r.provisioning_refusal_message.length>0&&(n.refusalMessage=r.provisioning_refusal_message),typeof r.queue_position=="number"&&typeof r.queue_depth=="number"&&(n.queue={position:r.queue_position,depth:r.queue_depth});let i=r.runtime_state;if(i==="unavailable"||i==="starting"||i==="busy"){n.runtime={state:i},typeof r.runtime_reason=="string"&&r.runtime_reason.length>0&&(n.runtime.reason=r.runtime_reason);let o=Xu(r.runtime_wake);o&&(n.runtime.wake=o)}return n}function js(r,e){let t=Number(r.headers.get("Retry-After")||""),n=Number(e.retry_after_seconds??t);return Number.isFinite(n)&&n>0?n:void 0}function Wo(r,e,t){let n=js(r,e),s=t??$o;return n!==void 0?Math.min(n*1e3,s):1e3}function Dt(r){return new Promise(e=>setTimeout(e,r))}function el(r){let e=typeof AbortSignal<"u"?AbortSignal:void 0;return typeof e?.timeout=="function"?e.timeout(r):void 0}var Re=class extends Error{},it=class extends H{};function Qo(r,e,t,n){if(!r)throw new Re(`[urun] ${n} ${t} without ws_url`);let s,i;try{s=new URL(r)}catch{throw new Re(n==="viewer-connect"?`[urun] viewer-connect returned no usable ws_url for ${t}`:`[urun] ${n} ${t} with non-absolute ws_url`)}try{i=new URL(Y(e))}catch{throw new Re(`[urun] ${n} ${t} has invalid gateway base URL`)}let o=tl(i.hostname)&&i.protocol==="http:";if(!(o&&s.protocol==="ws:"||s.protocol==="wss:"))throw new Re(`[urun] ${n} ${t} with insecure ws_url`);if(!rl(s,i,o))throw new Re(`[urun] ${n} ${t} with cross-origin ws_url`);return s.toString()}function tl(r){return r==="localhost"||r==="127.0.0.1"||r==="::1"||r.endsWith(".localhost")}function rl(r,e,t){return!!(t||r.hostname===e.hostname&&r.port===e.port||jo(r.hostname)&&jo(e.hostname))}function jo(r){return r==="urun.sh"||r.endsWith(".urun.sh")}function nl(r){try{return new URL(r).hostname!==Pu?[]:Du}catch{return[]}}var se=class extends Error{status;code;constructor(e,t,n=t>0?`http_${t}`:"runtime_artifacts_error",s){super(e),this.name="RuntimeArtifactsError",this.status=t,this.code=n,s!==void 0&&(this.cause=s),Object.setPrototypeOf(this,new.target.prototype)}},Tr=class extends se{constructor(e="[urun] runtime artifacts: unauthorized",t="unauthorized"){super(e,401,t),this.name="RuntimeArtifactsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Rr=class extends se{constructor(e="[urun] runtime artifacts: not found",t="not_found"){super(e,404,t),this.name="RuntimeArtifactNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}};function Cr(r){return{baseUrl:r.baseUrl,fallbackUrls:r.fallbackUrls,orgId:r.orgId,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}function Zo(r){return new Je(r)}var Je=class{_options;constructor(e){this._options=e}async list(e){let n=Xo(await this._request(e,"")).artifacts;if(!Array.isArray(n))throw new se("[urun] runtime artifacts: response missing `artifacts`",0,"bad_response");return n.map(Jo)}async getDownloadUrl(e,t){let n=Xo(await this._request(t,`/${encodeURIComponent(e)}/download`)),s=n.download_url;if(typeof s!="string"||!il(s))throw new se("[urun] runtime artifacts: response missing HTTPS download_url",0,"bad_response");return{artifact:Jo(n.artifact),downloadUrl:s}}async _request(e,t){let n=Sr(this._options.baseUrl,this._options.fallbackUrls),s=null;for(let i of n)try{return await this._requestFromBase(i,e,t)}catch(o){if(s=o instanceof Error?o:new Error(String(o)),s instanceof se&&ol(s.status))throw s}throw s??new se("[urun] runtime artifacts request failed",0)}async _requestFromBase(e,t,n){let s=`${Y(e)}/api/sessions/${encodeURIComponent(t)}/artifacts${n}`,i=await this._resolveToken(),o=await fetch(s,{method:"GET",headers:this._headers(i)});if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await fetch(s,{method:"GET",headers:this._headers(i)}))}if(!o.ok){let{code:a,message:c}=await this._readError(o,e);throw al(o.status,a,c)}try{return await o.json()}catch(a){throw new se(`[urun] runtime artifacts: invalid JSON response from ${Y(e)}`,0,"bad_response",a)}}async _resolveToken(){return this._options.getAccessToken?await this._options.getAccessToken()??void 0:this._options.jwt}_headers(e){let t={Accept:"application/json","X-Tenant-Id":this._options.orgId,"X-Auth-Provider":this._options.authProvider||"default"};return e&&(t.Authorization=`Bearer ${e}`),t}async _readError(e,t){let n=Y(t);try{let i=(await e.json()).error;if(i&&typeof i=="object"){let{code:o,message:a}=i;return{code:typeof o=="string"&&o.length>0?o:`http_${e.status}`,message:typeof a=="string"&&a.length>0?`[urun] runtime artifacts request failed at ${n}: ${a}`:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}}catch{}return{code:`http_${e.status}`,message:`[urun] runtime artifacts request failed at ${n}: HTTP ${e.status}`}}};function Jo(r){if(!r||typeof r!="object")throw new se("[urun] runtime artifacts: malformed artifact",0,"malformed_artifact");let e=r,t=qe(e,"artifact_id")||qe(e,"id"),n=qe(e,"filename"),s=qe(e,"kind"),i=qe(e,"status")||"ready",o=sl(e,"size_bytes"),a=qe(e,"sha256");if(!t||!n||!s||o==null||!a)throw new se("[urun] runtime artifacts: malformed artifact metadata",0,"malformed_artifact");return{artifactId:t,kind:s,filename:n,contentType:qe(e,"content_type")||"application/octet-stream",sizeBytes:o,sha256:a,status:i,createdAt:qe(e,"created_at"),expiresAt:qe(e,"expires_at")}}function qe(r,e){let t=r[e];return typeof t=="string"&&t.length>0?t:void 0}function sl(r,e){let t=r[e];return typeof t=="number"&&Number.isFinite(t)&&Number.isInteger(t)&&t>=0?t:void 0}function il(r){try{return new URL(r).protocol==="https:"}catch{return!1}}function ol(r){return r===401||r===403}function al(r,e,t){return r===401?new Tr(t,e):r===404?new Rr(t,e):new se(t,r,e)}function Xo(r){if(!r||typeof r!="object"||Array.isArray(r))throw new se("[urun] runtime artifacts: malformed response",0,"bad_response");return r}var ve=class extends Error{status;code;constructor(e,t){super(e),this.name="RecordingsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},xt=class extends ve{constructor(e="[urun] recordings: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="RecordingsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}},Er=class extends ve{constructor(e="[urun] recordings: not found",t="not_found"){super(e,{status:404,code:t}),this.name="RecordingNotFoundError",Object.setPrototypeOf(this,new.target.prototype)}},Pr=class extends ve{constructor(e="[urun] recordings: retain requires a temp recording",t="retain_not_temp"){super(e,{status:409,code:t}),this.name="RetainNotTempError",Object.setPrototypeOf(this,new.target.prototype)}},Dr=class extends ve{constructor(e="[urun] recordings: pin requires an active temp recording",t="pin_requires_active_temp"){super(e,{status:409,code:t}),this.name="PinRequiresActiveTempError",Object.setPrototypeOf(this,new.target.prototype)}},Ir=class extends ve{constructor(e="[urun] recordings: recording is permanent and locked",t="permanent_locked"){super(e,{status:409,code:t}),this.name="PermanentLockedError",Object.setPrototypeOf(this,new.target.prototype)}},ot=class extends ve{constructor(e="[urun] recordings: invalid retention duration",t="bad_duration",n=400){super(e,{status:n,code:t}),this.name="InvalidDurationError",Object.setPrototypeOf(this,new.target.prototype)}};function fn(r){return/^(\d+[smhdw])+$/.test(r)}function ea(r){if(r==="pin")return{action:"pin"};if(fn(r))return{action:"retain",duration:r};throw new ot(`[urun] recordings: "${r}" is not a duration or "pin"`)}function cl(r,e,t){let n=t||e||`HTTP ${r}`;if(r===401)return new xt(n,e??"unauthorized");if(r===404)return new Er(n,e??"not_found");if(r===400)return new ot(n,e??"bad_request",400);if(r===409)switch(e){case"retain_not_temp":return new Pr(n,e);case"pin_requires_active_temp":return new Dr(n,e);case"permanent_locked":return new Ir(n,e)}return new ve(n,{status:r,code:e??`http_${r}`})}var at=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/recordings`}_options;_base;async list(e){let n=(await this._request("GET","",{params:e?{session_id:e}:void 0})).recordings;return Array.isArray(n)?n:[]}async get(e){return this._one(await this._request("GET",`/${encodeURIComponent(e)}`))}async retain(e,t){if(!fn(t))throw new ot(`[urun] recordings: "${t}" is not a valid retention duration`);return this._one(await this._request("POST",`/${encodeURIComponent(e)}/retain`,{body:{duration:t}}))}async pin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/pin`))}async unpin(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/unpin`))}async permanent(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/permanent`))}async delete(e){return this._one(await this._request("POST",`/${encodeURIComponent(e)}/delete`))}_one(e){let t=e.recording;if(!t||typeof t!="object")throw new ve("[urun] recordings: response missing `recording`",{status:0,code:"bad_response"});return t}async _request(e,t,n={}){let s=this._buildUrl(t,n.params),i=await this._resolveToken(),o=await this._fetch(s,e,i,n.body);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i,n.body))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw cl(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(n+=`?${s}`),n}_fetch(e,t,n,s){let i={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};this._options.authProvider&&(i["X-Auth-Provider"]=this._options.authProvider);let o={method:t,headers:i};return s!==void 0&&(i["Content-Type"]="application/json",o.body=JSON.stringify(s)),fetch(e,o)}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new xt("[urun] recordings: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:s,message:i}=n;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function ta(r){return new at(r)}var vd=Ye(_i());var Wi=Ye(Bc(),1);function tt(){return typeof window>"u"&&typeof process<"u"&&process.versions!=null&&process.versions.node!=null}function Vc(){return tt()?"Chrome111":void 0}var _f=["RTCSessionDescription","RTCIceCandidate","RTCRtpReceiver","RTCRtpSender","RTCRtpTransceiver","RTCDataChannel","MediaStream","MediaStreamTrack"],rs=null,zc=null;function Gc(){return typeof globalThis.RTCPeerConnection<"u"?null:zc??"the WebRTC peer globals (RTCPeerConnection) are not installed in this runtime"}function tr(){return tt()?rs||(rs=vf(),rs):Promise.resolve()}async function vf(){let r=globalThis;if(typeof r.WebSocket>"u")try{let e=await import("ws"),t=e.default??e;r.WebSocket=t}catch(e){Hc("WebSocket",e)}if(typeof r.RTCPeerConnection>"u")try{let e=await import("werift");wf(r,e)}catch(e){zc=Hc("werift",e)}}function wf(r,e){let{RTCPeerConnection:t,useH264:n,useVP8:s,useOPUS:i,useSdesMid:o,useSdesRTPStreamId:a,useAbsSendTime:c,useTransportWideCC:u,useVideoOrientation:d}=e,l=()=>({video:[n(),s()],audio:[i()]}),p=()=>({video:[o(),a(),c(),u(),d()],audio:[o(),c(),u()]});class f extends t{constructor(m){super({...m,codecs:m?.codecs??l(),headerExtensions:m?.headerExtensions??p()})}}r.RTCPeerConnection=f;for(let h of _f)e[h]!=null&&typeof r[h]>"u"&&(r[h]=e[h])}function Hc(r,e){let t=e instanceof Error?e.message:String(e),n=`optional dependency "${r}" unavailable (${t})`;return console.warn(`[urun-sh/core] Node WebRTC support: ${n}. Realtime media will not work in this Node process; install "${r}" to enable it. Doc/KV transport over WebSocket is unaffected.`),n}var Kc="0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";function yf(r){let e=globalThis.crypto,t=new Uint8Array(r);if(e?.getRandomValues)return e.getRandomValues(t),t;for(let n=0;n<r;n++)t[n]=Math.floor(Math.random()*256);return t}function rr(r=16){let e=yf(r),t="";for(let n=0;n<r;n++)t+=Kc[e[n]%Kc.length];return t}function Qc(r){return`stream:${r}`}var Jc="urun-stream-v1";var ji=1,de={BINARY:0,TEXT:1,JSON:2,END:3,CHUNK:4},nr=2,Yc=253952,bf=[de.BINARY,de.TEXT,de.JSON],gt=Symbol("urun:stream:end");function Kr(r){if(r===gt)return Uint8Array.from([ji,de.END]);let{kind:e,body:t}=Xc(r);return ns(e,t)}function Xc(r){return r instanceof Uint8Array?{kind:de.BINARY,body:r}:r instanceof ArrayBuffer?{kind:de.BINARY,body:new Uint8Array(r)}:typeof r=="string"?{kind:de.TEXT,body:new TextEncoder().encode(r)}:{kind:de.JSON,body:new TextEncoder().encode(JSON.stringify(r))}}function ns(r,e){let t=new Uint8Array(nr+e.length);return t[0]=ji,t[1]=r,t.set(e,nr),t}function Zc(r){if(r===gt)return[Kr(r)];let{kind:e,body:t}=Xc(r);if(t.length+nr<=Yc)return[ns(e,t)];let n=Yc-nr,s=[],i=0;for(;t.length-i>n;)s.push(ns(de.CHUNK,t.subarray(i,i+n))),i+=n;return s.push(ns(e,t.subarray(i))),s}function os(r){let{kind:e,body:t}=ed(r);if(e===de.CHUNK)throw new Error("[urun] CHUNK envelope requires StreamFragmentReassembler (oversized payload)");return ss(e,t)}function ed(r){let e=r instanceof Uint8Array?r:new Uint8Array(r);if(e.length<nr||e[0]!==ji)throw new Error(`[urun] bad stream envelope (version=${e[0]}, len=${e.length})`);return{kind:e[1],body:e.subarray(nr)}}function ss(r,e){switch(r){case de.BINARY:return e.slice();case de.TEXT:return new TextDecoder().decode(e);case de.JSON:return JSON.parse(new TextDecoder().decode(e));case de.END:return gt;default:throw new Error(`[urun] unknown stream envelope KIND 0x${r.toString(16)}`)}}var is=class{_chunks=[];_bufferedLength=0;feed(e){let{kind:t,body:n}=ed(e);if(t===de.CHUNK){this._chunks.push(n.slice()),this._bufferedLength+=n.length;return}if(bf.includes(t)){if(this._chunks.length===0)return ss(t,n);let s=new Uint8Array(this._bufferedLength+n.length),i=0;for(let o of this._chunks)s.set(o,i),i+=o.length;return s.set(n,i),this._chunks=[],this._bufferedLength=0,ss(t,s)}if(this._chunks.length>0)throw this._chunks=[],this._bufferedLength=0,new Error(`[urun] stream envelope KIND 0x${t.toString(16)} arrived mid-fragment-sequence; discarding partial payload`);return ss(t,n)}};function td(r){return{get consumerId(){return r.consumerId},onData(e,t){return r.onStreamData(e,t)},sendData(e,t,n){return r.sendStreamData(e,t,n)}}}var rd=[1e3,2e3,4e3,8e3,3e4],nd=5,Sf=15e3,kf=15e3,sd=15e3,id=15e3,Tf=2e3,Rf=6e3,Cf=2e3,Ef=300,od=4e3,Pf=2,Df=750,If=3,ad=[1e3,2e3,4e3],xf=15e3;var sr="--",Af=["video","audio"];function as(r){let e=r.lastIndexOf(sr);if(e<=0)return;let t=r.slice(e+sr.length);return Af.includes(t)?t:void 0}function wd(r,e){return`${r}${sr}${e}`}var qi="v1";function Lf(r,e){return r.name!==e.name||r.reason!==e.reason||r.sessionId!==e.sessionId||r.requestId!==e.requestId||r.wakingSince!==e.wakingSince||r.region!==e.region||(r.endsAt?.getTime()??null)!==(e.endsAt?.getTime()??null)||r.queue?.position!==e.queue?.position||r.queue?.depth!==e.queue?.depth||r.runtime?.state!==e.runtime?.state||r.runtime?.reason!==e.runtime?.reason||r.runtime?.wake!==e.runtime?.wake?!1:r.error?.reason===e.error?.reason&&r.error?.code===e.error?.code&&r.error?.kind===e.error?.kind&&r.error?.httpStatus===e.error?.httpStatus&&r.error?.retryAfterSeconds===e.error?.retryAfterSeconds}var cd={requested:"provisioning",queued:"queued",pending:"provisioning",allocating:"provisioning",provisioning:"provisioning",waking:"provisioning",waiting_for_capacity:"waiting_for_capacity",allocated:"connecting",connecting:"connecting",establishing:"connecting",live:"live",running:"live",paused:"paused",error:"error",failed:"error",rejected:"error",expired:"paused",cancelled:"paused",canceled:"paused",closed:"paused",releasing:"paused",released:"paused",reaped:"paused",superseded:"paused"};function dd(r){return Object.prototype.hasOwnProperty.call(cd,r)?{phase:cd[r],unknown:!1}:{phase:"unknown",unknown:!0}}function Mf(r){return r==="queued"||r==="pending"}function ud(r){return r==="credits_exhausted"}var ld=3,pd=4e3,hd=[{urls:"stun:stun.l.google.com:19302"},{urls:"stun:stun1.l.google.com:19302"}];function fd(r){if(!r)return;let e=/\/(?:ws\/)?rtc\/([^/?#]+)/.exec(r);if(e)try{return decodeURIComponent(e[1])}catch{return e[1]}}var ir=class{_state="disconnected";_sessionId=null;_tracks=new Map;_tracksByName=new Map;_options;_emitter=new Wi.default;_ws=null;_connectedUrl=null;_device=null;_mediaUnavailableReason=null;_mediaVerdictResolve;_mediaVerdict=new Promise(e=>{this._mediaVerdictResolve=e});_recvTransport=null;_sendTransport=null;_consumers=new Map;_audioProducer=null;_videoProducer=null;_publishedAudio=null;_publishedVideo=null;_wtMicUplink=null;_wtCamUplink=null;_wtDataUpSender=null;_pendingProduce=null;_multiplexer=null;_reconnectAttempts=0;_intentionalDisconnect=!1;_reconnectTimer=null;_cancelPendingDial=null;_stableResetTimer=null;_generation=0;_lastStartOptions;_resolveConnection=null;_recvIceRestartAttempts=0;_recvIceRestartTimer=null;_sendIceRestartAttempts=0;_sendIceRestartTimer=null;_phase={name:"idle"};_requestId;_liveReached=!1;_lastServerStatus;_endsAt=null;_forceResolveOnNextConnect=!1;_connectStartedAt;_wakingSince;_mediaProbeTimer=null;_statsTimer=null;_statsSampleInFlight=!1;_joinProbes=new Map;_decodeDeathHandled=!1;_selectedCandidatePair=bd();_reportedCandidatePairKey=null;_candidatePairRefreshSeq=0;_diagnosticSinkFailed=!1;_currentEpoch=0;_selfEpochAdoptUntil=0;_pausedIncarnation=null;_consumerId=null;_streamDataHandlers=new Map;_streamDataLane="sctp";_dataProducers=new Map;_dataProducerPromises=new Map;_dataConsumers=new Map;_pendingDataProduce=new Map;_sendTransportWaiters=[];get consumerId(){return this._consumerId===null&&(this._consumerId=Of()),this._consumerId}get state(){return this._state}get currentIncarnation(){return this._currentEpoch}get phase(){return this._phase}get isProducingMedia(){let e=n=>n!==null&&!n.closed&&!n.paused,t=(n,s)=>n!==null&&s!==null&&s.track.readyState!=="ended"&&n.deliveredDatagrams()>0;return e(this._audioProducer)||e(this._videoProducer)||t(this._wtMicUplink,this._publishedAudio)||t(this._wtCamUplink,this._publishedVideo)}get endsAt(){return this._endsAt}setEndsAt(e){this._endsAt=e}seedRegion(e){e!==void 0&&this._setPhase(this._phase.name,{reason:this._phase.reason,queue:this._phase.queue,runtime:this._phase.runtime,error:this._phase.error,region:e})}_pastDeadline(){return this._endsAt!==null&&Date.now()>=this._endsAt.getTime()}get status(){let e={phase:this._phase.name,transportState:this._state};return this._sessionId&&(e.sessionId=this._sessionId),this._requestId&&(e.requestId=this._requestId),this._lastServerStatus!==void 0&&(e.lastServerStatus=this._lastServerStatus),this._connectStartedAt!==void 0&&(e.elapsedMs=Date.now()-this._connectStartedAt),this._endsAt!==null&&(e.endsAt=this._endsAt),this._phase.queue&&(e.queue=this._phase.queue),this._phase.runtime&&(e.runtime=this._phase.runtime),this._phase.wakingSince!==void 0&&(e.wakingSince=this._phase.wakingSince),this._phase.error&&(e.error=this._phase.error),this._phase.region!==void 0&&(e.region=this._phase.region),e}get region(){return this._phase.region}get sessionId(){return this._sessionId}get tracks(){return this._tracks}get multiplexer(){return this._multiplexer}get isOpen(){return this._ws!==null&&this._ws.readyState===WebSocket.OPEN}get connectedUrl(){return this._connectedUrl}get intentionalDisconnect(){return this._intentionalDisconnect}getTrackByName(e){if(as(e)!==void 0)return;let t=this._tracksByName.get(e);if(t&&t.readyState!=="ended")return t;for(let n of this._tracks.values())if(!(n.kind!==e||n.readyState==="ended")&&this._streamNameOf(n)===void 0)return n;return t}_streamNameOf(e){for(let[t,n]of this._tracksByName)if(n===e)return t}setAuth(e){this._options={...this._options,...e},this.isOpen&&this._send({type:"auth",orgId:this._options.orgId,jwt:this._options.jwt,authProvider:this._options.authProvider})}constructor(e){this._options=e??{url:""},e?.sessionId&&(this._sessionId=e.sessionId)}setConnection(e){if(this.isOpen){let t=fd(e.url);if(e.sessionId!==void 0&&e.sessionId!==this._sessionId)throw new st(this._sessionId,e.sessionId);if(t!==void 0&&t!==this._sessionId)throw new st(this._sessionId,t);this._options={...this._options,...e};return}this._options={...this._options,...e},e.sessionId&&(this._sessionId=e.sessionId)}setConnectionResolver(e){this._resolveConnection=e}applyControlDocState(e){let t=e&&typeof e=="object"?e.session:void 0,n=qf(t);if(n!==void 0&&this.setIncarnation(n),!t||typeof t!="object")return;let s=t,i=typeof s.status=="string"?s.status:void 0;if(i&&!this.isStaleClosedMarker(s)){if(i==="error"){let o=s.error_reason??s.errorReason,a=typeof o=="string"&&o?o:"session failed";this._setPhase("error",{error:{reason:a,code:"runtime-failed",kind:"runtime-failed"}})}else if(i==="closed"||i==="ended"||i==="paused"){let o=s.close_reason??s.closeReason??s.pause_reason??s.pauseReason;if(ud(o)){this._setPhase("paused",{reason:"credits_exhausted"});return}if(this._pastDeadline()){this._setPhase("paused",{reason:"max_session_age"});return}this._setPhase("paused",{reason:typeof o=="string"&&o?o:i})}}}setIncarnation(e){if(!Number.isFinite(e)||e<=this._currentEpoch)return;let t=this._currentEpoch>0,n=this._state==="connected";this._currentEpoch=e;let i=this._selfEpochAdoptUntil>0&&Date.now()<=this._selfEpochAdoptUntil;this._selfEpochAdoptUntil=0,!i&&t&&n&&!this._intentionalDisconnect&&this._renegotiate()}isStaleIncarnation(e){return Number.isFinite(e)?e<this._currentEpoch:!1}isStaleClosedMarker(e){if(!e)return!1;let t=typeof e.status=="string"?e.status:void 0;if(t!=="closed"&&t!=="ended"&&t!=="paused"&&t!=="error")return!1;let n=e.status_epoch??e.statusEpoch,s=typeof n=="number"?n:Number(n);return Number.isFinite(s)?s<this._currentEpoch:!1}_isStaleLivenessEvidence(){return this._phase.name!=="paused"||this._pausedIncarnation===null?!1:this._currentEpoch<=this._pausedIncarnation}async connect(e){if(this.isOpen&&this._state==="connected"&&!this._intentionalDisconnect){e!==void 0&&(this._lastStartOptions=e);return}this._lastStartOptions=e,this._intentionalDisconnect=!1,this._pausedIncarnation=null,this._connectStartedAt??=Date.now(),this._cancelPendingDial?.(new Error("TransportSession: connect superseded by a newer connect()"));let t=++this._generation,n=this._state==="reconnecting"||this._state==="renegotiating";n||this._setState("connecting");let s=null,i=()=>t!==this._generation||this._intentionalDisconnect,o=()=>{if(i())throw new Error("TransportSession: connect cancelled")},a=async()=>{for(let l of this._connectUrls()){o();try{return await this._connectOnce(l,t,e),!0}catch(p){s=p instanceof Error?p:new Error(String(p)),i()||this._cleanupSocket()}}return!1},c=this._forceResolveOnNextConnect&&this._resolveConnection!==null;this._forceResolveOnNextConnect=!1;let u=c?0:this._resolveConnection?Pf:1;for(let l=0;l<u;l++)if(l>0&&(await md(Df),o()),await a())return;if(this._resolveConnection)for(let l=0;l<If;l++){this._setState("reconnecting"),await md(ad[Math.min(l,ad.length-1)]),o();try{let p=await this._resolveConnection();o(),this.setAuth({jwt:p.jwt??this._options.jwt,authProvider:this._options.authProvider,orgId:this._options.orgId}),this.setConnection({url:p.url,sessionId:p.sessionId,iceServers:p.iceServers??this._options.iceServers}),p.endsAt!==void 0&&(this._endsAt=p.endsAt)}catch(p){if(i())throw new Error("TransportSession: connect cancelled");s=p instanceof Error?p:new Error(String(p));continue}if(await a())return}if(i())throw s??new Error("TransportSession: connect cancelled");this._setState("failed");let d=s??new Error("TransportSession: connect failed");throw n||this._emitError(d),d}leaveLeg(){if(!this.isOpen)return!1;this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null);try{this._send({type:"leave"})}catch{}try{this._ws?.close()}catch{}return!0}disconnect(e="client_detached"){this._generation+=1,this._intentionalDisconnect=!0,this._selfEpochAdoptUntil=0,this._cancelPendingDial?.(new Error("TransportSession: connect cancelled by disconnect()")),this._stopMediaProbe(),this._stopStatsSampler(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._clearReconnectBudgetReset(),this._reconnectAttempts=0;try{this._publishedAudio?.track.stop()}catch{}try{this._publishedVideo?.track.stop()}catch{}if(this._publishedAudio=null,this._publishedVideo=null,this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}try{this._videoProducer.close()}catch{}this._videoProducer=null}for(let t of this._consumers.values())try{t.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._settleSendTransportWaiters(null,new Error("[urun] sendStreamData: transport disconnected before the send transport arrived")),this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}if(this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce.reject(new Error("TransportSession: disconnected")),this._pendingProduce=null),this._device=null,this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null),this._cleanupSocket(),this._tracks.clear(),this._tracksByName.clear(),this._setState("disconnected"),this._liveReached=!1,this._setPhase("paused",{reason:e}),this._emitter.emit("disconnected")}on(e,t){return this._emitter.on(e,t),()=>{this._emitter.off(e,t)}}_emitDiagnostic(e){let t=this._options.diagnosticSink;if(t)try{t(e)}catch(n){this._diagnosticSinkFailed||(this._diagnosticSinkFailed=!0,console.warn(`[urun] diagnosticSink threw (${String(n instanceof Error?n.message:n)}) \u2014 further diagnostics ride only the structured 'diagnostic' event`))}else e.level==="debug"?console.debug(`[urun] ${e.message}`,e.detail??{}):e.level==="error"?console.error(`[urun] ${e.message}`,e.detail??{}):console.warn(`[urun] ${e.message}`,e.detail??{});this._emitter.emit("diagnostic",e)}sendInput(e,t){this._send({type:"input",data:e,sequence:t})}sendSignal(e){return this._send(e)}onSignal(e){return this.on("signal",e)}emitDiagnostic(e){this._emitDiagnostic(e)}onStreamData(e,t){let n=this._streamDataHandlers.get(e);return n||(n=new Set,this._streamDataHandlers.set(e,n)),n.add(t),()=>{let s=this._streamDataHandlers.get(e);s?.delete(t),s&&s.size===0&&this._streamDataHandlers.delete(e)}}sendStreamData(e,t,n){try{this._requireMediaSupport("sendStreamData")}catch(s){return Promise.reject(s)}return this._wtDataUpSender?this._wtDataUpSender.send(e,Kr(t)):this._ensureDataProducer(e).then(s=>{for(let i of Zc(t))s.send(i)})}get wtDataUplinkSeam(){return{onUplink:e=>{this._wtDataUpSender=e},onUplinkLost:e=>{this._wtDataUpSender&&(this._wtDataUpSender=null,console.warn(`[urun-sh/core] WT data uplink lost (${e}) \u2014 data-up reverts to SCTP for this leg`))}}}_awaitSendTransport(){return this._sendTransport?Promise.resolve(this._sendTransport):new Promise((e,t)=>{let n={resolve:i=>{clearTimeout(s),e(i)},reject:i=>{clearTimeout(s),t(i)}},s=setTimeout(()=>{let i=this._sendTransportWaiters.indexOf(n);i>=0&&this._sendTransportWaiters.splice(i,1),t(new Error(`[urun] sendStreamData: no send transport after ${sd}ms (the server never offered createSendTransport \u2014 data-up produce is impossible on this leg)`))},sd);this._sendTransportWaiters.push(n)})}_settleSendTransportWaiters(e,t){let n=this._sendTransportWaiters;this._sendTransportWaiters=[];for(let s of n)e?s.resolve(e):s.reject(t??new Error("TransportSession: disconnected"))}_ensureDataProducer(e){let t=this._dataProducers.get(e);if(t&&!t.closed)return Promise.resolve(t);let n=this._dataProducerPromises.get(e);if(n)return n;let s=this._awaitSendTransport().then(i=>i.produceData({label:Qc(e),protocol:Jc,ordered:!0})).then(i=>this._awaitDataChannelOpen(i)).then(i=>(this._dataProducers.set(e,i),this._dataProducerPromises.delete(e),i)).catch(i=>{throw this._dataProducerPromises.delete(e),i});return this._dataProducerPromises.set(e,s),s}_awaitDataChannelOpen(e){if(e.closed)return Promise.reject(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"));let t=e.readyState;return t==="open"?Promise.resolve(e):t==="closing"||t==="closed"?Promise.reject(new Error(`[urun] sendStreamData: DataChannel is ${t} \u2014 cannot deliver data-up payloads`)):new Promise((n,s)=>{let i=()=>{u(),n(e)},o=l=>{d(new Error(`[urun] sendStreamData: DataChannel error before open: ${l.message}`))},a=()=>{u(),s(new Error("[urun] sendStreamData: DataProducer closed before its DataChannel opened"))},c=setTimeout(()=>{d(new Error(`[urun] sendStreamData: DataChannel not open after ${id}ms (the SCTP handshake never completed \u2014 data-up produce is impossible on this channel)`))},id),u=()=>{clearTimeout(c),e.off("open",i),e.off("error",o),e.observer.off("close",a)},d=l=>{u();try{e.close()}catch{}s(l)};e.on("open",i),e.on("error",o),e.observer.on("close",a)})}_dispatchStreamData(e,t){for(let n of this._streamDataHandlers.get(e)??[])n(t)}markStreamDataLaneQuic(){this._streamDataLane="quic"}dispatchQuicStreamData(e,t){this._dispatchStreamData(e,t)}raiseQuicStreamDataError(e){console.error(e.message),this._emitter.emit("error",e)}quicStreamDataLaneLost(e){if(this._streamDataLane!=="quic")return;this._streamDataLane="sctp";let t=[...this._streamDataHandlers.keys()];if(t.length===0)return;let n=new Error(`[urun] QUIC data lane lost mid-stream (${e}) \u2014 active named streams [${t.join(", ")}] resume over SCTP on the failover leg from now; envelopes in flight on the dead lane are gone (mid-stream-join semantics)`);console.error(n.message),this._emitter.emit("error",n)}_streamNameFromLabel(e){if(e)return e.startsWith("stream:")?e.slice(7):void 0}mediaUnavailableReason(){return this._mediaUnavailableReason}mediaAvailability(){return this._mediaVerdict}_requireMediaSupport(e){if(this._mediaUnavailableReason)throw new Error(`[urun-sh/core] ${e}: realtime media is unavailable in this process \u2014 ${this._mediaUnavailableReason}. This session joined in doc/KV-only mode (the media device was skipped); install the optional "werift" dependency to enable realtime media.`)}async addTrack(e,t){this._requireMediaSupport("addTrack"),await this._publishTrack(e,t)}async _publishTrack(e,t){let n=e.kind==="video";if(!n&&this._wtMicUplink){this._wtMicUplink.setSource(e),this._rememberPublishIntent(!1,e,t);return}if(n&&this._wtCamUplink){this._wtCamUplink.setSource(e),this._rememberPublishIntent(!0,e,t);return}let s=n?this._videoProducer:this._audioProducer;if(s&&!s.closed){if(s.track===e)return;await s.replaceTrack({track:e}),this._rememberPublishIntent(n,e,t);return}if(!this._sendTransport)throw new Error("TransportSession: send transport not ready");let i=await this._sendTransport.produce({track:e,...n?{}:{codecOptions:{opusStereo:!1,opusDtx:!1,opusFec:!1}},stopTracks:!1,...t?{appData:{name:t}}:{}});n?this._videoProducer=i:this._audioProducer=i,this._rememberPublishIntent(n,e,t)}_rememberPublishIntent(e,t,n){let s={track:t,...n!==void 0?{name:n}:{}};e?this._publishedVideo=s:this._publishedAudio=s}removeTrack(){let e=this._publishedAudio;if(this._publishedAudio=null,this._wtMicUplink){this._wtMicUplink.setSource(null);try{e?.track.stop()}catch{}}if(this._audioProducer){this._send({type:"stopAudio"});try{this._audioProducer.track?.stop()}catch{}this._audioProducer.close(),this._audioProducer=null}}async addVideoTrack(e,t){this._requireMediaSupport("addVideoTrack"),await this._publishTrack(e,t)}stopVideo(){let e=this._publishedVideo;if(this._publishedVideo=null,this._wtCamUplink){this._wtCamUplink.setSource(null);try{e?.track.stop()}catch{}}if(this._videoProducer){this._send({type:"stopVideo"});try{this._videoProducer.track?.stop()}catch{}this._videoProducer.close(),this._videoProducer=null}}requestDiagnostics(){this._send({type:"diagnostics"})}seekStream(e,t){this._send({type:"stream.seek",stream:e,target:t})}async _handleMessage(e){switch(e.type){case"routerRtpCapabilities":await this._onRouterCapabilities(e.rtpCapabilities);break;case"createWebRtcTransport":await this._onCreateRecvTransport(e);break;case"createSendTransport":await this._onCreateSendTransport(e);break;case"consume":await this._onConsume(e);break;case"consumerClosed":this._closeConsumer(e.consumerId);break;case"producerClosed":this._closeConsumersByProducer(e.producerId);break;case"consumerPaused":this._consumers.get(e.consumerId)?.pause();break;case"consumerResumed":this._consumers.get(e.consumerId)?.resume();break;case"iceRestarted":this._onIceRestarted(e);break;case"produced":if(this._pendingProduce){let t=this._pendingProduce;this._pendingProduce=null,clearTimeout(t.timeoutId),t.resolve(e.id)}break;case"dataProduced":{let t=e.label,n=t?this._pendingDataProduce.get(t):void 0;n&&t&&(this._pendingDataProduce.delete(t),n.resolve(e.id));break}case"consumeData":await this._onConsumeData(e);break;case"started":this._emitter.emit("started");break;case"status":this._onStatus(e);break;case"stream.seeked":this._onStreamSeeked(e);break;case"error":this._onServerError(e);break;default:this._emitter.emit("signal",e);break}}_onServerError(e){let t=typeof e.message=="string"?e.message:"signaling error",n=typeof e.code=="string"?e.code:void 0;if(/connect\(\) already called/i.test(t)){if(this._resolveConnection){this._generation++;let s=this._ws;this._ws=null;try{s?.close()}catch{}this._cleanupMedia(),this._forceResolveOnNextConnect=!0,this._renegotiate();return}this._setPhase("error",{error:{reason:t,code:"transport-consumed",kind:"transport-failed"}}),this._emitter.emit("error",new Error(t));return}if(n==="TRANSPORT_BIND_FAILED"){this._emitError(new Error(t),n);return}if(n==="PROTOCOL_VERSION_UNSUPPORTED"){this._setPhase("error",{error:{reason:t,code:n,kind:"create-failed"},reason:t}),this._emitter.emit("error",new Error(t));return}console.warn("[urun] signaling error from server:",t)}_onStreamSeeked(e){let t=typeof e.stream=="string"?e.stream:void 0;if(!t)return;let n=e.target,s=n==="live"?"live":typeof n=="number"?n:Number(n);this._emitter.emit("seeked",t,s)}_reportUnknownServerStatus(e,t,n="signaling",s){let o=`server reported unrecognized ${n==="admission"?"admission response":"session status"} status ${JSON.stringify(e)}`+(t?` (reason: ${JSON.stringify(t)})`:"")+' \u2014 this @urun-sh/core build does not know this word; refusing to render it as "provisioning". The SDK may be out of date for this server.';this._emitDiagnostic({level:"error",kind:"unknown-server-status",message:o,detail:{status:e,origin:n,...t?{reason:t}:{}}}),!this._liveReached&&(this._lastServerStatus=e,this._setPhase("unknown",{reason:e,region:s}))}_onStatus(e){let t=e.request_id??e.requestId;t&&(this._requestId=t);let n=typeof e.status=="string"?e.status:void 0,s=typeof e.reason=="string"&&e.reason?e.reason:void 0,i="region"in e?typeof e.region=="string"&&e.region.length>0?e.region:null:void 0,o=n!==void 0?dd(n):void 0;if(n!==void 0&&o?.unknown){this._reportUnknownServerStatus(n,s,"signaling",i);return}let a=o?.phase??"provisioning";if(this._liveReached&&a!=="paused"&&a!=="error"){a==="live"&&i!==void 0&&i!==this._phase.region&&this._setPhase("live",{reason:s,region:i});return}if(this._isStaleLivenessEvidence()&&a!=="live"&&a!=="paused"&&a!=="error")return;n!==void 0&&(this._lastServerStatus=n);let c=e.queue_position??e.queuePosition,u=e.queue_depth??e.queueDepth,d=typeof c=="number"&&typeof u=="number";if(a==="paused"){let l=e.reason??e.close_reason??e.closeReason??e.pause_reason??e.pauseReason,p=typeof l=="string"&&l?l:void 0,f=ud(l)?"credits_exhausted":this._pastDeadline()?"max_session_age":s??p??n??"paused";this._setPhase("paused",{reason:f,region:i??null}),this._stopMediaProbe();return}if(a==="error"){let l=s??n??"admission failed";this._setPhase("error",{error:{reason:l,code:n,kind:n==="error"?"runtime-failed":"create-failed"},reason:l,region:i});return}if(a==="queued"){this._setPhase("queued",{...d?{queue:{position:c,depth:u}}:{},reason:s,region:i});return}if(a==="waiting_for_capacity"){this._setPhase("waiting_for_capacity",{...d?{queue:{position:c,depth:u}}:{},reason:s,region:i});return}if(a==="connecting"){this._setPhase("connecting",{reason:s,region:i});return}if(a==="live"){this._setPhase("live",{reason:s,region:i});return}this._setPhase("provisioning",{reason:s,region:i})}_webRtcDialHeld=!1;_heldRouterCaps=null;holdWebRtcDial(){return this._webRtcDialHeld=!0,{proceed:e=>{if(!this._webRtcDialHeld)return;this._webRtcDialHeld=!1;let t=this._heldRouterCaps;this._heldRouterCaps=null,t&&(console.info(`[urun-sh/core] running the deferred WebRTC dial (${e})`),this._onRouterCapabilities(t).catch(n=>{console.error("[urun-sh/core] deferred WebRTC dial failed:",n)}))},skip:e=>{console.info(`[urun-sh/core] WebRTC dial SKIPPED (${e}) \u2014 WT-only leg, no RTCPeerConnection`)}}}async _onRouterCapabilities(e){if(this._webRtcDialHeld){this._heldRouterCaps=e;return}tt()&&await tr();let t=Gc();if(t){this._mediaUnavailableReason=t,this._mediaVerdictResolve(t);return}this._mediaVerdictResolve(null);let n=Vc(),s=new vd.Device(n?{handlerName:n}:void 0);await s.load({routerRtpCapabilities:e}),this._device=s,this._send({type:"rtpCapabilities",rtpCapabilities:s.rtpCapabilities})}async _onCreateRecvTransport(e){this._device&&this._buildRecvTransport(e)}_buildRecvTransport(e){if(!this._device)return;let t=e.iceCandidates,n=this._device.createRecvTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:t,dtlsParameters:e.dtlsParameters,...e.sctpParameters?{sctpParameters:e.sctpParameters}:{},iceServers:this._options.iceServers??hd});this._recvIceRestartAttempts=0,this._clearRecvIceRestart();let s=this._generation;n.on("connect",({dtlsParameters:i},o,a)=>{try{this._send({type:"connectTransport",transportId:n.id,dtlsParameters:i}),o()}catch(c){a(c)}}),n.on("connectionstatechange",i=>{if(s===this._generation){if(i==="connected"){this._clearRecvIceRestart(),this._recvIceRestartAttempts=0,this._reportSelectedCandidatePair(n);return}if(!(this._intentionalDisconnect&&i==="closed")&&(i==="failed"||i==="disconnected")){if(this._tryRestartRecvIce())return;i==="failed"&&this._emitError(new Error(`media transport ${i}`),i),this._renegotiate()}}}),this._recvTransport=n}async _reportSelectedCandidatePair(e){let t=++this._candidatePairRefreshSeq,n=null;if(typeof e.getStats=="function")try{n=await e.getStats()}catch{}if(this._recvTransport!==e||t!==this._candidatePairRefreshSeq)return;let s=jf(n);if(s.localType===null&&s.remoteType===null&&s.protocol===null&&s.remoteAddress===null&&s.remotePort===null&&this._reportedCandidatePairKey!==null)return;this._selectedCandidatePair=s;let o=JSON.stringify(s);if(this._reportedCandidatePairKey===o)return;this._reportedCandidatePairKey=o;let a=Object.values(this._selectedCandidatePair).some(c=>c!==null);this._emitDiagnostic({level:a?"info":"debug",kind:"ice-candidate-pair",message:`selected ICE candidate pair: local=${this._selectedCandidatePair.localType??"unknown"} remote=${this._selectedCandidatePair.remoteType??"unknown"} protocol=${this._selectedCandidatePair.protocol??"unknown"} remote=${this._selectedCandidatePair.remoteAddress??"unknown"}:${this._selectedCandidatePair.remotePort??"unknown"}`,detail:{sessionId:this._options.sessionId,...this._selectedCandidatePair}})}_tryRestartRecvIce(){let e=this._recvTransport;return!e||e.closed?!1:this._recvIceRestartTimer?!0:this._recvIceRestartAttempts>=ld?!1:(this._recvIceRestartAttempts++,this._armRecvIceRestartWatchdog(),this._requestIceRestart(e.id),!0)}_trySendIceRestart(){let e=this._sendTransport;return!e||e.closed?!1:this._sendIceRestartTimer?!0:this._sendIceRestartAttempts>=ld?!1:(this._sendIceRestartAttempts++,this._armSendIceRestartWatchdog(),this._requestIceRestart(e.id),!0)}_requestIceRestart(e){this._send({type:"restartIce",transportId:e})}_onIceRestarted(e){let t=e.transportId??e.id,n=e.iceParameters;if(!n)return;let s=!!this._recvTransport&&this._recvTransport.id===t,i=!s&&!!this._sendTransport&&this._sendTransport.id===t,o=s?this._recvTransport:i?this._sendTransport:null;o&&(Promise.resolve(o.restartIce({iceParameters:n})).catch(a=>{this._emitter.emit("error",a instanceof Error?a:new Error(String(a)))}),s&&this._recvIceRestartTimer?this._armRecvIceRestartWatchdog():i&&this._sendIceRestartTimer&&this._armSendIceRestartWatchdog())}_armRecvIceRestartWatchdog(){this._clearRecvIceRestart();let e=this._generation;this._recvIceRestartTimer=setTimeout(()=>{this._recvIceRestartTimer=null,!(e!==this._generation||this._intentionalDisconnect)&&this._recvTransport?.connectionState!=="connected"&&(this._emitError(new Error("media transport failed (ice restart timeout)"),"failed"),this._renegotiate())},pd)}_armSendIceRestartWatchdog(){this._clearSendIceRestart();let e=this._generation;this._sendIceRestartTimer=setTimeout(()=>{this._sendIceRestartTimer=null,!(e!==this._generation||this._intentionalDisconnect)&&this._sendTransport?.connectionState!=="connected"&&this._emitError(new Error("media send transport failed (ice restart timeout)"),"failed")},pd)}_clearRecvIceRestart(){this._recvIceRestartTimer&&(clearTimeout(this._recvIceRestartTimer),this._recvIceRestartTimer=null)}_clearSendIceRestart(){this._sendIceRestartTimer&&(clearTimeout(this._sendIceRestartTimer),this._sendIceRestartTimer=null)}async _onCreateSendTransport(e){if(!this._device)return;let t=this._device.createSendTransport({id:e.id,iceParameters:e.iceParameters,iceCandidates:e.iceCandidates,dtlsParameters:e.dtlsParameters,...e.sctpParameters?{sctpParameters:e.sctpParameters}:{},iceServers:this._options.iceServers??hd});this._sendIceRestartAttempts=0,this._clearSendIceRestart();let n=this._generation;t.on("connect",({dtlsParameters:s},i,o)=>{try{this._send({type:"connectSendTransport",transportId:t.id,dtlsParameters:s}),i()}catch(a){o(a)}}),t.on("produce",({kind:s,rtpParameters:i,appData:o},a,c)=>{if(this._pendingProduce){c(new Error("produce already pending"));return}let u=o&&typeof o.name=="string"?o.name:void 0,d=setTimeout(()=>{let l=this._pendingProduce;if(!l||l.timeoutId!==d)return;this._pendingProduce=null;let p=new kt(s,{stream:u,timeoutMs:Rt});this._setPhase("error",{error:{reason:p.message,code:"produce-ack-timeout",kind:"produce-timeout"}}),this._emitter.emit("error",p),l.reject(p)},Rt);this._pendingProduce={timeoutId:d,resolve:l=>{a({id:l})},reject:c};try{this._send(u?{type:"produce",kind:s,name:u,rtpParameters:i}:{type:"produce",kind:s,rtpParameters:i})}catch(l){this._pendingProduce?.timeoutId===d&&(this._pendingProduce=null,clearTimeout(d)),c(l)}}),t.on("producedata",({sctpStreamParameters:s,label:i,protocol:o},a,c)=>{try{i&&this._pendingDataProduce.set(i,{resolve:u=>a({id:u}),reject:c}),this._send({type:"produceData",sctpStreamParameters:s,label:i,protocol:o})}catch(u){i&&this._pendingDataProduce.delete(i),c(u)}}),t.on("connectionstatechange",s=>{if(n===this._generation){if(s==="connected"){this._clearSendIceRestart(),this._sendIceRestartAttempts=0;return}this._intentionalDisconnect&&s==="closed"||(s==="failed"||s==="disconnected")&&this._trySendIceRestart()||(s==="failed"||s==="closed")&&this._emitError(new Error(`media send transport ${s}`),s)}}),this._sendTransport=t,this._settleSendTransportWaiters(t),this._emitter.emit("audioTransportReady"),this._republishPublishedTracks()}async _republishPublishedTracks(){let e=this._publishedAudio;if(e&&e.track.readyState!=="ended"&&(!this._audioProducer||this._audioProducer.closed))try{await this.addTrack(e.track,e.name)}catch(n){console.warn("[urun] republish: mic re-produce after reconnect failed",n)}else e&&e.track.readyState==="ended"&&console.warn("[urun] republish: published mic track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)");let t=this._publishedVideo;if(t&&t.track.readyState!=="ended"&&(!this._videoProducer||this._videoProducer.closed))try{await this.addVideoTrack(t.track,t.name)}catch(n){console.warn("[urun] republish: camera re-produce after reconnect failed",n)}else t&&t.track.readyState==="ended"&&console.warn("[urun] republish: published camera track is ended \u2014 not republishing (device re-acquisition is the app/page-recovery pass)")}async _onConsumeData(e){if(this._streamDataLane==="quic"){this.raiseQuicStreamDataError(new Error(`[urun] consumeData (label=${String(e.label)}) pushed on a leg whose data lane is QUIC \u2014 refusing (one canonical data path per leg, contract urun-infra#1605)`));return}let t=this._recvTransport;if(!t)return;let n=e.label,s=this._streamNameFromLabel(n);if(!s)return;let i=this._generation,o=await t.consumeData({id:e.id,dataProducerId:e.dataProducerId,sctpStreamParameters:e.sctpStreamParameters,label:n,protocol:e.protocol});if(i!==this._generation||this._recvTransport!==t||t.closed||this._intentionalDisconnect){try{o.close()}catch{}return}this._dataConsumers.set(s,o);let a=new is;o.on("message",d=>{try{let l=typeof d=="string"?new TextEncoder().encode(d):new Uint8Array(d),p=a.feed(l);p!==void 0&&this._dispatchStreamData(s,p)}catch(l){this._emitter.emit("error",l instanceof Error?l:new Error(String(l)))}});let c=!1,u=()=>{c||o.closed||(c=!0,this._send({type:"dataConsumerReady",id:e.id}))};o.readyState==="open"?u():o.on("open",u)}async _onConsume(e){let t=this._recvTransport;if(!t)return;let n=this._generation,s=await t.consume({id:e.id,producerId:e.producerId,kind:e.kind,rtpParameters:e.rtpParameters});if(n!==this._generation||this._recvTransport!==t||t.closed||this._intentionalDisconnect){try{s.close()}catch{}return}this._consumers.set(s.id,s),this._tracks.set(s.track.id,s.track),this._capJitterBuffer(s,s.kind==="video"?"video":"audio");let i=e.streamName??e.label;i&&this._tracksByName.set(i,s.track),s.track.addEventListener?.("unmute",()=>{n!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._liveReached||this._setPhase("live")},{once:!0}),this._emitter.emit("track",s.track);let o=s.id;s.track.addEventListener("ended",()=>{n!==this._generation||this._intentionalDisconnect||this._closeConsumer(o)},{once:!0}),this._send({type:"resumeConsumer",consumerId:s.id}),this._startMediaProbe(),this._startStatsSampler()}get audioPlayoutOptions(){return this._options.audioPlayout}get wtMicUplinkSeam(){return{onUplink:e=>{this._wtMicUplink=e;let t=this._publishedAudio;if(this._audioProducer&&!this._audioProducer.closed){console.warn("[urun-sh/core] WT mic uplink engaged \u2014 moving the mic from WebRTC produce to the QUIC lane"),this._send({type:"stopAudio"});try{this._audioProducer.close()}catch{}this._audioProducer=null}t&&e.setSource(t.track)},onUplinkLost:e=>{if(!this._wtMicUplink)return;this._wtMicUplink=null;let t=this._publishedAudio;if(!(!t||t.track.readyState==="ended")){if(console.warn(`[urun-sh/core] WT mic uplink lost (${e}) \u2014 republishing the mic over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-mic-uplink-dead",message:`WT mic uplink lost (${e}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the mic is now DEAD until the WT uplink re-engages.`,detail:{reason:e}});return}this._publishTrack(t.track,t.name).catch(n=>{console.error("[urun-sh/core] mic republish over WebRTC failed:",n)})}}}}get wtCamUplinkSeam(){return{onUplink:e=>{this._wtCamUplink=e;let t=this._publishedVideo;if(this._videoProducer&&!this._videoProducer.closed){console.warn("[urun-sh/core] WT video uplink engaged \u2014 moving the camera from WebRTC produce to the QUIC lane"),this._send({type:"stopVideo"});try{this._videoProducer.close()}catch{}this._videoProducer=null}t&&e.setSource(t.track)},onUplinkLost:e=>{if(!this._wtCamUplink)return;this._wtCamUplink=null;let t=this._publishedVideo;if(!(!t||t.track.readyState==="ended")){if(console.warn(`[urun-sh/core] WT video uplink lost (${e}) \u2014 republishing the camera over WebRTC`),!this._sendTransport){this._emitDiagnostic({level:"error",kind:"wt-cam-uplink-dead",message:`WT camera uplink lost (${e}) with NO WebRTC send transport \u2014 the republish above cannot run. If a reconnect is in flight this self-heals; on a WT-only leg (no RTCPeerConnection was dialled) the camera is now DEAD until the WT uplink re-engages.`,detail:{reason:e}});return}this._publishTrack(t.track,t.name).catch(n=>{console.error("[urun-sh/core] camera republish over WebRTC failed:",n)})}}}}_jitterBufferTargetMs(e){if(e==="audio"){let t=this._options.audioPlayout?.jitterBufferTargetMs;return t===void 0?Ef:t}return this._options.videoPlayout?.jitterBufferTargetMs}_capJitterBuffer(e,t){let n=this._jitterBufferTargetMs(t);if(n===void 0)return;let s=t==="video"?"videoPlayout":"audioPlayout",i={mediaKind:t,transportId:this._recvTransport?.id??null};if(!Number.isFinite(n)){this._emitDiagnostic({level:"warning",kind:`${t}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be a finite number of milliseconds; got ${String(n)}. No jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:String(n),...i}});return}if(n<=0)return;if(n>od){this._emitDiagnostic({level:"warning",kind:`${t}-jitter-buffer-invalid`,message:`${s}.jitterBufferTargetMs must be within the W3C jitterBufferTarget range 0-${od}ms; got ${n}. No jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:n,...i}});return}let o=e.rtpReceiver;if(!o){this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-unsupported`,message:`${t} consumer exposes no RTCRtpReceiver (node/werift leg); no jitter-buffer cap applied.`,detail:{consumerId:e.id,targetMs:n,reason:"no-receiver",...i}});return}let a=[];if("jitterBufferTarget"in o&&(o.jitterBufferTarget=n,a.push("jitterBufferTarget")),"playoutDelayHint"in o&&(o.playoutDelayHint=n/1e3,a.push("playoutDelayHint")),a.length===0){this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-unsupported`,message:`${t==="audio"?"Audio":"Video"} receiver exposes neither jitterBufferTarget nor playoutDelayHint; standing ${t} playout delay is unbounded on this engine.`,detail:{consumerId:e.id,targetMs:n,...i}});return}this._emitDiagnostic({level:"debug",kind:`${t}-jitter-buffer-capped`,message:`${t==="audio"?"Audio":"Video"} receiver jitter buffer capped at ${n}ms.`,detail:{consumerId:e.id,targetMs:n,applied:a,...i}})}_closeConsumer(e){let t=this._consumers.get(e);if(!t)return;this._consumers.delete(e);let n=t.track;try{t.close()}catch{}if(n){this._tracks.delete(n.id);for(let[s,i]of this._tracksByName)i===n&&this._tracksByName.delete(s)}}_closeConsumersByProducer(e){for(let[t,n]of this._consumers)n.producerId===e&&this._closeConsumer(t)}_mediaPollMs(){let e=this._options.mediaLiveness?.pollMs;return e===void 0?Tf:e}_firstFrameWindowMs(){let e=this._options.mediaLiveness?.stallTimeoutMs;return e===void 0?Rf:e}_startMediaProbe(){let e=this._mediaPollMs();if(e<=0||this._mediaProbeTimer)return;let t=this._generation;this._mediaProbeTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence()||this._sampleMediaArrival(t)},e)}_stopMediaProbe(){this._mediaProbeTimer&&(clearInterval(this._mediaProbeTimer),this._mediaProbeTimer=null)}_statsPollMs(){let e=this._options.sessionStats;if(!e)return 0;let t=e.pollMs;return t===void 0?Cf:Number.isFinite(t)&&t>0?t:0}_startStatsSampler(){let e=this._statsPollMs();if(e<=0||this._statsTimer)return;let t=this._generation;this._statsTimer=setInterval(()=>{t!==this._generation||this._intentionalDisconnect||this._isParkedPhase()||this._statsSampleInFlight||(this._statsSampleInFlight=!0,this._sampleSessionStats(t).catch(n=>{try{this._emitter.emit("error",n instanceof Error?n:new Error(String(n)))}catch{}}).finally(()=>{this._statsSampleInFlight=!1}))},e)}_stopStatsSampler(){this._statsTimer&&(clearInterval(this._statsTimer),this._statsTimer=null),this._statsSampleInFlight=!1}_lanePairKey(e){let t=e.track,n=t?this._streamNameOf(t):void 0;if(n===void 0)return null;let s=as(n);return s===void 0?n:n.slice(0,n.length-sr.length-s.length)}async _sampleSessionStats(e){if(this._consumers.size===0)return;let t=Array.from(this._consumers.values()),n=await Promise.all(t.map(async p=>({consumerId:p.id,kind:p.kind==="video"?"video":"audio",pairKey:this._lanePairKey(p),sample:await _d(p)})));if(e!==this._generation||this._intentionalDisconnect||this._isParkedPhase())return;let s=n.filter(p=>p.pairKey===null),i=n.filter(p=>p.pairKey!==null),o=null,a=n;if(i.length>0){let p=new Map;for(let m of i){let g=m.pairKey,_=p.get(g);_?_.push(m):p.set(g,[m])}let f=-1,h=-1;for(let[m,g]of p){let _=new Set(g.map(y=>y.kind)).size>=2?1:0,v=g.reduce((y,S)=>y+S.sample.total,0);(_>f||_===f&&v>h)&&(f=_,h=v,o=m,a=[...g,...s])}}let c=p=>{let f=null,h=-1;for(let{consumerId:m,kind:g,sample:_}of a)g===p&&_.total>h&&(h=_.total,f={consumerId:m,..._});return f},u=c("audio"),d=c("video"),l=d?.estimatedPlayoutTimestamp!=null&&u?.estimatedPlayoutTimestamp!=null?d.estimatedPlayoutTimestamp-u.estimatedPlayoutTimestamp:null;this._emitter.emit("stats",{timestamp:Date.now(),stream:o,avSyncMs:l,audio:u,video:d})}_resetJoinProbes(){this._joinProbes.clear(),this._decodeDeathHandled=!1}async _sampleMediaArrival(e){if(this._consumers.size===0)return;let t=Array.from(this._consumers.entries()),n=await Promise.all(t.map(async([a,c])=>[a,await _d(c)]));if(e!==this._generation||this._intentionalDisconnect||this._phase.name==="error"&&this._isParkedPhase()||this._isStaleLivenessEvidence())return;for(let a of this._joinProbes.keys())this._consumers.has(a)||this._joinProbes.delete(a);let s=Date.now();!this._liveReached&&n.some(([,a])=>a.total>0)&&this._setPhase("live");let i=null,o=!1;for(let[a,c]of n){if(c.total<=0){o=!0;continue}let u=this._joinProbes.get(a);if(u||(u={firstBytesAt:s,startSample:c,settled:!1},this._joinProbes.set(a,u)),!u.settled){if(c.framesDecoded===null){u.settled=!0;continue}if(c.framesDecoded>0){u.settled=!0;continue}if(s-u.firstBytesAt>=this._firstFrameWindowMs()){i??={id:a,probe:u,sample:c};continue}o=!0}}if(i&&!this._decodeDeathHandled){this._decodeDeathHandled=!0;let a=this._firstFrameWindowMs(),c=Wf(i.probe.startSample,i.sample),u=c.lossPct!==null&&c.lossPct>=5?" \u2014 consistent with network packet loss between the SFU and this browser":"";this._emitDiagnostic({level:"warning",kind:"decode-wall",message:`video is arriving but the decoder never produced its first frame within ${a/1e3}s of join (framesDecoded still 0) \u2014 no keyframe to start from${u}; re-consuming the stream`,detail:{sessionId:this._options.sessionId,consumerId:i.id,firstFrameWindowMs:a,inboundTotal:i.sample.total,framesDecoded:i.sample.framesDecoded,...Ff(i.sample),...c,likelyCause:c.lossPct!==null&&c.lossPct>=5?"network-packet-loss":null,...this._selectedCandidatePair}}),this._renegotiate();return}!o&&!i&&this._stopMediaProbe()}_renegotiate(){this._intentionalDisconnect||this._isParkedPhase()||this._reconnectTimer||(this._stopMediaProbe(),this._stopStatsSampler(),this._setState("renegotiating"),this._attemptReconnect())}recover(){if(this._intentionalDisconnect||this._isParkedPhase()||this._connectStartedAt===void 0||this._cancelPendingDial)return;if(!this.isOpen){this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null),this._reconnectAttempts=0,this._attemptReconnect(void 0,!0);return}let e=this._recvTransport?.connectionState;(e==="disconnected"||e==="failed")&&(this._recvIceRestartTimer||(this._recvIceRestartAttempts=0),this._tryRestartRecvIce()||this._renegotiate());let t=this._sendTransport?.connectionState;(t==="disconnected"||t==="failed")&&(this._sendIceRestartTimer||(this._sendIceRestartAttempts=0),this._trySendIceRestart())}_attemptReconnect(e,t=!1){if(this._intentionalDisconnect||this._isParkedPhase()||this._reconnectTimer)return;if(this._reconnectAttempts>=nd){this._setState("failed"),this._emitError(new Error(`Failed after ${nd} attempts`));return}let n=t?0:rd[Math.min(this._reconnectAttempts,rd.length-1)];this._reconnectAttempts++,this._state!=="renegotiating"&&this._setState("reconnecting"),this._reconnectTimer=setTimeout(async()=>{this._reconnectTimer=null,this._replaceCurrentLegForReconnect();try{await this.connect(e??this._lastStartOptions)}catch(s){if(s instanceof Error&&s.message==="TransportSession: connect cancelled")return;this._attemptReconnect(e)}},n)}_connectUrls(){let e=[],t=n=>{if(!n)return;let s=fd(n)!==void 0,i=this._sessionId&&!s?`${n}${n.includes("?")?"&":"?"}sessionId=${encodeURIComponent(this._sessionId)}`:n;e.includes(i)||e.push(i)};t(this._options.url);for(let n of this._options.fallbackUrls??[])t(n);return e}_connectOnce(e,t,n){return new Promise((s,i)=>{let o=!1,a=!1,c=null,u=new WebSocket(e);this._ws=u;let d=()=>this._ws!==u||t!==this._generation,l=f=>{a||(a=!0,c&&clearTimeout(c),this._cancelPendingDial===p&&(this._cancelPendingDial=null),i(f))},p=f=>{try{u.close()}catch{}l(f)};this._cancelPendingDial=p,c=setTimeout(()=>{try{u.close()}catch{}l(new Error("TransportSession: connect timed out"))},Sf),u.onopen=()=>{if(!a){if(d()){try{u.close()}catch{}l(new Error("TransportSession: connect superseded during dial"));return}o=!0,c&&clearTimeout(c),this._connectedUrl=e,this._multiplexer=new vt(u),u.send(JSON.stringify(this._startMessage(n))),this._scheduleReconnectBudgetReset(),this._selfEpochAdoptUntil=Date.now()+kf,this._setState("connected"),this._liveReached||this._setPhase("connecting"),this._emitter.emit("connected"),a=!0,this._cancelPendingDial===p&&(this._cancelPendingDial=null),s()}},u.onerror=()=>{o||l(new Error("WebSocket connection error"))},u.onclose=()=>{if(!o){l(new Error("WebSocket closed before connecting"));return}if(!d()&&(this._clearReconnectBudgetReset(),c&&clearTimeout(c),this._setState("disconnected"),!this._intentionalDisconnect)){if(this._pastDeadline()&&this._phase.name!=="paused"){this._setPhase("paused",{reason:"max_session_age"}),this._emitter.emit("disconnected");return}this._emitter.emit("disconnected"),!this._isParkedPhase()&&this._attemptReconnect(n)}},u.onmessage=f=>{if(!(this._ws!==u||t!==this._generation)&&typeof f.data=="string")try{this._handleMessage(JSON.parse(f.data)).catch(h=>{this._emitter.emit("error",h instanceof Error?h:new Error(String(h)))})}catch(h){this._emitter.emit("error",h instanceof Error?h:new Error(String(h)))}}})}_startMessage(e){let t={type:"start",version:qi,video:e?.video??{width:854,height:480,frameRate:16}};return e?.prompt&&(t.prompt=e.prompt),e?.cameraControl&&(t.camera_control=e.cameraControl),e?.args&&(t.args=e.args),e?.app&&(t.app=e.app),e?.functionName&&(t.function=e.functionName),e?.role&&(t.role=e.role),this._options.orgId&&(t.orgId=this._options.orgId),this._options.jwt&&(t.jwt=this._options.jwt),this._options.authProvider&&(t.authProvider=this._options.authProvider),t}_cleanupSocket(){if(this._clearReconnectBudgetReset(),!this._ws)return;let e=this._ws;this._ws=null,e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null;try{e.close()}catch{}}_replaceCurrentLegForReconnect(){this._cleanupSocket(),this._cancelPendingDial?.(new Error("TransportSession: reconnect replacing current dial")),this._cleanupMedia()}_scheduleReconnectBudgetReset(){this._clearReconnectBudgetReset(),this._reconnectAttempts!==0&&(this._stableResetTimer=setTimeout(()=>{this._stableResetTimer=null,this._reconnectAttempts=0},xf))}_clearReconnectBudgetReset(){this._stableResetTimer&&(clearTimeout(this._stableResetTimer),this._stableResetTimer=null)}_cleanupDataChannels(){for(let e of this._dataProducers.values())try{e.close()}catch{}this._dataProducers.clear(),this._dataProducerPromises.clear();for(let e of this._dataConsumers.values())try{e.close()}catch{}this._dataConsumers.clear();for(let e of this._pendingDataProduce.values())try{e.reject(new Error("TransportSession: disconnected"))}catch{}this._pendingDataProduce.clear()}_cleanupMedia(){this._stopMediaProbe(),this._stopStatsSampler(),this._resetJoinProbes();for(let e of this._consumers.values())try{e.close()}catch{}if(this._consumers.clear(),this._cleanupDataChannels(),this._audioProducer){try{this._audioProducer.close()}catch{}this._audioProducer=null}if(this._videoProducer){try{this._videoProducer.close()}catch{}this._videoProducer=null}if(this._clearRecvIceRestart(),this._clearSendIceRestart(),this._recvTransport){try{this._recvTransport.close()}catch{}this._recvTransport=null}if(this._sendTransport){try{this._sendTransport.close()}catch{}this._sendTransport=null}this._pendingProduce&&(clearTimeout(this._pendingProduce.timeoutId),this._pendingProduce=null),this._device=null,this._tracks.clear(),this._tracksByName.clear(),this._multiplexer&&(this._multiplexer.dispose(),this._multiplexer=null)}_send(e){return!this._ws||this._ws.readyState!==WebSocket.OPEN?!1:(this._ws.send(JSON.stringify(e)),!0)}_setState(e){this._state!==e&&(this._state=e,this._emitter.emit("stateChange",e))}_isParkedPhase(){return this._phase.name==="paused"?!0:this._phase.name!=="error"?!1:this._phase.error?.kind!=="transport-failed"}_setPhase(e,t){e==="live"?this._liveReached=!0:(e==="paused"||e==="error")&&(this._liveReached=!1);let n={name:e};t?.queue&&(n.queue=t.queue),t?.runtime&&(n.runtime=t.runtime),t?.reason&&(n.reason=t.reason),n.region=t?.region!==void 0?t.region:this._phase.region,sn(e)?(this._wakingSince??=Date.now(),n.wakingSince=this._wakingSince):this._wakingSince=void 0,this._requestId&&(n.requestId=this._requestId),this._sessionId&&(n.sessionId=this._sessionId),this._endsAt!==null&&(n.endsAt=this._endsAt),t?.error&&(n.error=t.error),!Lf(this._phase,n)&&(this._phase=n,this._pausedIncarnation=e==="paused"?this._currentEpoch:null,this._isParkedPhase()&&(this._stopMediaProbe(),this._stopStatsSampler(),this._clearRecvIceRestart(),this._clearSendIceRestart(),this._reconnectTimer&&(clearTimeout(this._reconnectTimer),this._reconnectTimer=null)),this._emitter.emit("phase",n))}reportAdmission(e){e.requestId&&(this._requestId=e.requestId),this._lastServerStatus=e.status;let t=dd(e.status);if(t.unknown){this._reportUnknownServerStatus(e.status,e.reason,"admission",e.region);return}if(this._liveReached)return;e.sessionId&&!this._sessionId&&(this._sessionId=e.sessionId);let{runtime:n,queue:s}=e,i=e.decisionReason==="provisioning_refused"?e.refusalMessage??e.decisionReason:e.reason,o={runtime:n,queue:s,...i?{reason:i}:{},...e.region!==void 0?{region:e.region}:{}};if(Mf(e.status)){if(n?.state==="unavailable"){this._setPhase("unavailable",o);return}if(n?.state==="starting"){this._setPhase("provisioning",o);return}if(n?.state==="busy"||e.status==="queued"){this._setPhase("queued",o);return}this._setPhase("provisioning",o);return}this._setPhase(t.phase,t.phase==="paused"?{...o,region:o.region??null}:o)}_emitError(e,t){this._setPhase("error",{error:{reason:e.message,code:t,kind:"transport-failed"}}),this._emitter.emit("error",e)}reportAllocationFailure(e,t,n,s){n==="insufficient_credits"?this._setPhase("error",{error:{reason:e.message,code:n,kind:"insufficient-credits",httpStatus:t}}):this._setPhase("error",{error:{reason:e.message,code:n??"allocation-failed",kind:"create-failed",httpStatus:t,retryAfterSeconds:s}}),this._emitter.emit("error",e)}};function md(r){return new Promise(e=>setTimeout(e,r))}function Of(){return rr()}var yd=["packetsReceived","packetsLost","nackCount","pliCount","firCount","keyFramesDecoded","framesReceived","framesDropped","retransmittedPacketsReceived","retransmittedBytesReceived","jitterBufferDelay","jitterBufferEmittedCount","estimatedPlayoutTimestamp","jitterBufferTargetDelay","jitterBufferMinimumDelay","concealedSamples","insertedSamplesForDeceleration"],Uf=new Set(["estimatedPlayoutTimestamp"]);function Nf(){return{total:0,framesDecoded:null,packetsReceived:null,packetsLost:null,nackCount:null,jitter:null,pliCount:null,firCount:null,keyFramesDecoded:null,framesReceived:null,framesDropped:null,retransmittedPacketsReceived:null,retransmittedBytesReceived:null,jitterBufferDelay:null,jitterBufferEmittedCount:null,estimatedPlayoutTimestamp:null,jitterBufferTargetDelay:null,jitterBufferMinimumDelay:null,concealedSamples:null,insertedSamplesForDeceleration:null}}function Ff(r){return Object.fromEntries(yd.map(e=>[e,r[e]]))}function gd(r,e){return r===null||e===null||e<r?null:e-r}function Wf(r,e){let t=r.packetsLost!==null&&e.packetsLost!==null?e.packetsLost-r.packetsLost:null,n=gd(r.packetsReceived,e.packetsReceived),s=gd(r.nackCount,e.nackCount),i=t===null?null:Math.max(0,t),o=i!==null&&n!==null?i+n:0;return{packetsLostWindow:t,packetsReceivedWindow:n,nackCountWindow:s,jitterSec:e.jitter,lossPct:o>0&&i!==null?i/o*100:null}}function bd(){return{localType:null,remoteType:null,protocol:null,remoteAddress:null,remotePort:null}}function jf(r){let e=new Map;Sd(r,a=>{let c=typeof a.id=="string"?a.id:null;c&&e.set(c,a)});let t=Array.from(e.values()).find(a=>a.type==="transport"),n=typeof t?.selectedCandidatePairId=="string"?t.selectedCandidatePairId:null,s=(n?e.get(n):void 0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.selected===!0)??Array.from(e.values()).find(a=>a.type==="candidate-pair"&&a.nominated===!0);if(!s)return bd();let i=typeof s.localCandidateId=="string"?e.get(s.localCandidateId):void 0,o=typeof s.remoteCandidateId=="string"?e.get(s.remoteCandidateId):void 0;return{localType:typeof i?.candidateType=="string"?i.candidateType:null,remoteType:typeof o?.candidateType=="string"?o.candidateType:null,protocol:typeof i?.protocol=="string"?i.protocol:typeof o?.protocol=="string"?o.protocol:null,remoteAddress:typeof o?.address=="string"?o.address:typeof o?.ip=="string"?o.ip:null,remotePort:typeof o?.port=="number"?o.port:null}}function Sd(r,e){let t=n=>{n&&typeof n=="object"&&e(n)};if(r instanceof Map)for(let[n,s]of r.entries()){if(!s||typeof s!="object")continue;let i=s;e(typeof i.id=="string"?i:{...i,id:n})}else(Array.isArray(r)||r&&typeof r.forEach=="function")&&r.forEach(t)}async function _d(r){let e=Nf();if(typeof r.getStats!="function")return e;let t;try{t=await r.getStats()}catch{return e}return Sd(t,s=>{if(s.type==="inbound-rtp"){let i=typeof s.bytesReceived=="number"?s.bytesReceived:0,o=typeof s.packetsReceived=="number"?s.packetsReceived:0;e.total+=i+o,typeof s.framesDecoded=="number"&&(e.framesDecoded=(e.framesDecoded??0)+s.framesDecoded),typeof s.jitter=="number"&&(e.jitter=e.jitter===null?s.jitter:Math.max(e.jitter,s.jitter));for(let a of yd)typeof s[a]=="number"&&(e[a]=Uf.has(a)?e[a]===null?s[a]:Math.max(e[a],s[a]):(e[a]??0)+s[a])}}),e}function qf(r){if(!r||typeof r!="object")return;let e=r.epoch,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?t:void 0}var Qr=Ye(require("yjs"));var kd=require("y-websocket"),Bi=require("y-protocols/awareness"),$f=1;function ds(r){let e=new URL(r);return`${e.protocol}//${e.host}/doc`}var Bf=2500,Hf=3e4,Vf=1e4,zf=3;function Td(r){let e=r.WebSocketPolyfill??globalThis.WebSocket;if(!e)throw new Error("[urun] no WebSocket implementation available for the yjs doc provider (browser global missing and no WebSocketPolyfill passed)");return(t,n,s)=>{let i=`${r.sessionId}/${t}`,o=typeof r.token=="function"?r.token:null,a=typeof r.token=="string"?r.token:void 0,c=r.maxBackoffTimeMs??Bf,u=r.dialTimeoutMs??Hf,d=new kd.WebsocketProvider(r.serverUrl,i,n,{awareness:s,params:{dsv:String($f),...a?{token:a}:{}},WebSocketPolyfill:e,disableBc:!0,maxBackoffTime:c,resyncInterval:Vf,connect:o===null}),l=!1,p=0,f=!1,h=M=>{f||(f=!0,console.error(`[urun] doc token refresh failed for room ${i} (redialing with previous token):`,M))},m=()=>{if(!o)return;let M=++p;try{let N=o();if(typeof N=="string"){d.params.token=N,f=!1;return}if(N&&typeof N.then=="function")return N.then(U=>{M===p&&typeof U=="string"&&(d.params.token=U,f=!1)},U=>{h(U)})}catch(N){h(N)}},g=r.resolveServerUrl,_=0,v=!1,y=M=>{if(typeof M!="string"||M==="")return;let N=M.replace(/\/+$/,"");N!==d.serverUrl&&(d.serverUrl=N,v=!1)},S=()=>{if(!g)return;let M=++_,N=U=>{v||(v=!0,console.error(`[urun] doc endpoint re-resolve failed for room ${i} (redialing previous host):`,U))};try{let U=g();if(U&&typeof U.then=="function")return U.then(O=>{M===_&&y(O)},N);y(U)}catch(U){N(U)}},w={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null},b=new Set,L=!1,q=()=>{let M={...w};for(let N of[...b])N(M)},W=null,B=()=>{W!==null&&(clearTimeout(W),W=null)},ee=()=>{B(),W=setTimeout(()=>{if(W=null,!l&&d.wsconnecting&&d.ws)try{d.ws.close()}catch{}},u)},re=null,ge=()=>{re!==null&&(clearTimeout(re),re=null)},xe=()=>{ge(),re=setTimeout(()=>{if(re=null,!l&&d.shouldConnect&&!d.wsconnected&&!d.wsconnecting&&d.ws===null)try{d.connect()}catch(M){L||(L=!0,console.error(`[urun] doc connection redial threw for room ${i} (still retrying):`,M)),xe()}},c+500)},je=({status:M})=>{if(M==="connecting"){ge(),ee();return}if(M==="connected"){B(),ge(),w={...w,connected:!0},q();return}w.connected&&(w={...w,connected:!1},q())},vr=M=>{M&&(L&&(console.info(`[urun] doc connection recovered for room ${i}`),L=!1),w.consecutiveFailures!==0&&(w={...w,consecutiveFailures:0},q()))},R=M=>{B(),w={connected:!1,consecutiveFailures:w.consecutiveFailures+1,lastCloseCode:M?M.code:null,lastCloseReason:M&&M.reason?M.reason:null},!L&&w.consecutiveFailures>=zf&&(L=!0,console.error(`[urun] doc connection failing for room ${i}: ${w.consecutiveFailures} consecutive failures (last close ${w.lastCloseCode===null?"by provider liveness reap":`code ${w.lastCloseCode}`}${w.lastCloseReason?`, reason "${w.lastCloseReason}"`:""}). Still retrying \u2014 the doc provider never gives up.`)),q(),m(),S(),xe()};d.on("status",je),d.on("sync",vr),d.on("connection-close",R),d.wsconnecting?ee():d.wsconnected&&(w={...w,connected:!0});let x=!1,F=!1,K=null;if(o!==null){let M=m();if(M){F=!0;let N=()=>{F&&(F=!1,K!==null&&(clearTimeout(K),K=null),!l&&!x&&d.connect())};K=setTimeout(N,u),M.then(N)}else d.connect()}return{get awareness(){return d.awareness},get synced(){return d.synced},onSync(M){let N=U=>M(U);return d.on("sync",N),()=>d.off("sync",N)},onConnectionState(M){return b.add(M),M({...w}),()=>b.delete(M)},ensureConnected(){x=!1,!d.wsconnected&&!F&&d.connect()},disconnect(){x=!0,d.disconnect()},destroy(){l=!0,K!==null&&(clearTimeout(K),K=null),B(),ge(),d.off("status",je),d.off("sync",vr),d.off("connection-close",R),b.clear(),d.destroy()}}}}var $i=class{constructor(e,t,n){this._name=e;this._doc=t;this.awareness=n}_name;_doc;awareness;_inner=null;_innerUnsub=null;_innerStateUnsub=null;_syncHandlers=new Set;_stateHandlers=new Set;_lastState={connected:!1,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};_destroyed=!1;_suspended=!1;get synced(){return this._inner?.synced??!1}get destroyed(){return this._destroyed}onSync(e){return this._syncHandlers.add(e),()=>this._syncHandlers.delete(e)}onConnectionState(e){return this._stateHandlers.add(e),e({...this._lastState}),()=>this._stateHandlers.delete(e)}attach(e){if(!this._destroyed){if(this._inner&&(this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner.destroy(),this._inner=null),this._inner=e(this._name,this._doc,this.awareness),this._innerUnsub=this._inner.onSync(t=>{for(let n of[...this._syncHandlers])n(t)}),this._inner.onConnectionState)this._innerStateUnsub=this._inner.onConnectionState(t=>{this._lastState=t;for(let n of[...this._stateHandlers])n(t)});else{this._innerStateUnsub=null,this._lastState={connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null};for(let t of[...this._stateHandlers])t({...this._lastState})}if(this._suspended&&this._inner.disconnect?.(),this._inner.synced)for(let t of[...this._syncHandlers])t(!0)}}ensureConnected(){this._suspended=!1,this._inner?.ensureConnected?.()}get disconnect(){return this._inner?.disconnect?()=>{this._suspended=!0,this._inner.disconnect()}:void 0}destroy(){this._destroyed=!0,this._innerUnsub?.(),this._innerUnsub=null,this._innerStateUnsub?.(),this._innerStateUnsub=null,this._inner?.destroy(),this._inner=null,this._syncHandlers.clear(),this._stateHandlers.clear()}},cs=class{_target=null;_bridges=[];connect=(e,t,n)=>{let s=new $i(e,t,n);return this._bridges.push(s),this._target&&s.attach(this._target),s};get connected(){return this._target!==null}setTarget(e){if(this._target!==e){this._target=e,this._bridges=this._bridges.filter(t=>!t.destroyed);for(let t of this._bridges)t.attach(e)}}};function Jr(r){if(r===null||typeof r!="object"||Array.isArray(r))return!1;let e=Object.getPrototypeOf(r);return e===Object.prototype||e===null}var us="$bytes";function Gf(r){return r instanceof Uint8Array||r instanceof ArrayBuffer}function Kf(r){if(!Jr(r))return!1;let e=Object.keys(r);return e.length===1&&e[0]===us&&typeof r[us]=="string"}function Yf(r){return r instanceof ArrayBuffer?new Uint8Array(r):r}function Qf(r){if(typeof Buffer<"u")return Buffer.from(r).toString("base64");let e="";for(let t=0;t<r.length;t++)e+=String.fromCharCode(r[t]);return btoa(e)}function Jf(r){if(typeof Buffer<"u")return new Uint8Array(Buffer.from(r,"base64"));let e=atob(r),t=new Uint8Array(e.length);for(let n=0;n<e.length;n++)t[n]=e.charCodeAt(n);return t}function Hi(r){if(Gf(r))return{[us]:Qf(Yf(r))};if(Array.isArray(r))return r.map(Hi);if(Jr(r)){let e={};for(let[t,n]of Object.entries(r))e[t]=Hi(n);return e}return r}function Yr(r){if(Kf(r))return Jf(r[us]);if(Array.isArray(r))return r.map(Yr);if(Jr(r)){let e={};for(let[t,n]of Object.entries(r))e[t]=Yr(n);return e}return r}var Rd=Symbol("urun:doc:path-absent");function Xf(r,e){let t=e.split("."),n=r;for(let s of t){if(n===null||typeof n!="object"||!(s in n))return Rd;n=n[s]}return n}function Zf(r,e){return r===e?!0:JSON.stringify(r)===JSON.stringify(e)}function Vi(r,e){for(let[t,n]of Object.entries(e))if(Jr(n)){let s=r.get(t);if(!(s instanceof Qr.Map)){let i=s;s=new Qr.Map,r.set(t,s),Jr(i)&&Vi(s,i)}Vi(s,n)}else{if(Zf(r.get(t),n))continue;r.set(t,n)}}var em=Symbol("urun:doc:local"),ls=class{_doc=new Qr.Doc;_root=this._doc.getMap("session");_awareness=new Bi.Awareness(this._doc);_listeners=new Set;_key;_sessionId;_connection=null;_connUnsub=null;_synced;_syncWaiters=new Set;_texts=new Map;_observer=()=>this.notify();constructor(e,t,n){this._key=e,this._sessionId=t,this._root.observeDeep(this._observer),n?(this._connection=n(e,this._doc,this._awareness),this._synced=this._connection.synced,this._connUnsub=this._connection.onSync(s=>{s&&this._markSynced()}),this._synced&&this._markSynced()):this._synced=!0}get awareness(){return this._awareness}setSessionId(e){this._sessionId=e}get synced(){return this._synced}ensureConnected(){this._connection?.ensureConnected?.()}reconnect(){this.ensureConnected()}disconnect(){let e=this._connection;if(!e?.disconnect)throw new Error(`[urun-sh/core] doc('${this._key}').disconnect(): no disconnect-capable connection to sever (a local-only doc, or a connector with no live socket) \u2014 there is nothing to disconnect`);e.disconnect()}onConnectionState(e){return this._connection?.onConnectionState?this._connection.onConnectionState(e):(e({connected:!0,consecutiveFailures:0,lastCloseCode:null,lastCloseReason:null}),()=>{})}onSynced(e){return this._synced?(e(),()=>{}):(this._syncWaiters.add(e),()=>this._syncWaiters.delete(e))}set(e){e=Hi(e),this.applyPatch(e)}get(e,t){let n=this.snapshot();if(!e)return Yr(n);let s=Xf(n,e);return s===Rd?t:Yr(s)}on(e,t){return this._listeners.add(t),()=>this._listeners.delete(t)}text(e){let t=this._texts.get(e);return t||(t=new zi(this._doc.getText(`text:${e}`)),this._texts.set(e,t)),t}dispose(){this._root.unobserveDeep(this._observer),this._connUnsub?.(),this._connUnsub=null,this._connection?.destroy(),this._connection=null,this._listeners.clear(),this._syncWaiters.clear();for(let e of this._texts.values())e.dispose();this._texts.clear(),this._awareness.destroy(),this._doc.destroy()}_markSynced(){let e=[...this._syncWaiters];this._synced=!0,this._syncWaiters.clear();for(let t of e)t()}applyPatch(e){this._doc.transact(()=>{Vi(this._root,e)},em)}snapshot(){return this._root.toJSON()}notify(){let e=Yr(this.snapshot());for(let t of this._listeners)t(e)}},zi=class{constructor(e){this._ytext=e;this._observer=t=>{for(let n of t.delta)if(typeof n.insert=="string"&&n.insert.length>0){let s=n.insert;for(let i of this._delta)i(s)}},this._ytext.observe(this._observer)}_ytext;_delta=new Set;_observer;append(e){e.length!==0&&this._ytext.insert(this._ytext.length,e)}toString(){return this._ytext.toString()}get length(){return this._ytext.length}on(e,t){return this._delta.add(t),()=>this._delta.delete(t)}dispose(){this._ytext.unobserve(this._observer),this._delta.clear()}};function Cd(r){return{get clientId(){return r.clientID},set(e){r.setLocalState(e)},setField(e,t){r.setLocalStateField(e,t)},getLocal(){return r.getLocalState()??null},getStates(){return r.getStates()},on(e,t){let n=()=>t(r.getStates());return r.on("change",n),n(),()=>r.off("change",n)}}}var Ed=1e3,Pd=12e3;function ps(r,e,t={}){let n=null,s=0,i=0,o=null,a=-1,c=()=>{let g=r.get("desired.billing.generationSeconds");if(typeof g!="number"||!Number.isFinite(g)||g<=0)return null;let _=r.get("desired.billing.epoch"),v=r.get("desired.billing.updatedAtMs");return{seconds:g,epoch:typeof _=="number"&&Number.isFinite(_)?_:0,updatedAtMs:typeof v=="number"&&Number.isFinite(v)?v:null}},u=()=>{if(n===null)return null;let g=Math.min(Math.max(0,Date.now()-s),i);return n+g/1e3},d=()=>{let g=t.creditsPerSecond;if(typeof g=="number"&&Number.isFinite(g)&&g>0)return g;let _=r.get("desired.billing.creditsPerSecond");return typeof _=="number"&&Number.isFinite(_)&&_>0?_:null},l=()=>{let g=u();if(g===null)return;let _=Math.floor(g);if(_<=a)return;a=_;let v={seconds:_},y=d();y!==null&&(v.estimatedCredits=_*y),e(v)},p=g=>{s=Date.now();let _=g===null?0:Math.max(0,s-g);i=Math.max(0,12e3-_)},f=()=>{let g=c();if(g!==null){if(o!==null&&g.epoch!==o){o=g.epoch,n=g.seconds,a=-1,p(g.updatedAtMs),l();return}n!==null&&g.seconds<=n||(o=g.epoch,n=g.seconds,p(g.updatedAtMs),l())}};f();let h=r.on("change",f),m=setInterval(l,1e3);return m.unref?.(),()=>{clearInterval(m),h()}}var Gi="activity",Ki="visibility",Dd=15e3,hs=["pointerdown","pointermove","keydown","wheel","touchstart"];function fs(r){let e=r.now??Date.now,t=r.mode==="explicit",n=t?null:r.windowTarget!==void 0?r.windowTarget:typeof window<"u"?window:null,s=t?null:r.documentTarget!==void 0?r.documentTarget:typeof document<"u"?document:null,i=!1,o,a=()=>{if(i)return;let p=e();if(!(o!==void 0&&p-o<15e3)){o=p;try{r.awareness.setLocalStateField(Gi,{at:p})}catch{}}},c=()=>{if(!(i||!s||s.visibilityState===void 0))try{r.awareness.setLocalStateField(Ki,s.visibilityState)}catch{}},u=()=>a(),d=()=>{c(),(!s||s.visibilityState===void 0||s.visibilityState==="visible")&&a()};if(n)for(let p of hs)n.addEventListener(p,u,{passive:!0,capture:!0});s&&s.addEventListener("visibilitychange",d);let l=null;return!t&&r.isProducing&&(l=setInterval(()=>{if(!i)try{r.isProducing?.()&&a()}catch{}},15e3),l.unref?.()),a(),c(),{touch:a,dispose(){if(!i){if(i=!0,n)for(let p of hs)n.removeEventListener(p,u,{capture:!0});s&&s.removeEventListener("visibilitychange",d),l&&(clearInterval(l),l=null)}}}}var Yi="user_activity",Qi="focus",xd=3e4;function Id(r){switch(r){case"connecting":case"renegotiating":return"connecting";case"connected":return"ready";case"reconnecting":case"disconnected":case"failed":return"transient_failure"}}var or=class{_awareness;_now;_win;_state="idle";_stateHandlers=new Set;_transportUnsubs=new Set;_disposed=!1;_counts={typing:0,pointer:0,tty:0,consumer_reads:0};_inflight=0;_visibility;_focus;_lastSignalAt;_lastPublishedAt;_trailing=null;_onWindowFocus=null;_onWindowBlur=null;constructor(e={}){this._awareness=e.awareness??null,this._now=e.now??Date.now,this._win=e.windowTarget!==void 0?e.windowTarget:typeof window<"u"?window:null;let t=e.documentTarget!==void 0?e.documentTarget:typeof document<"u"?document:null;this._win&&t&&typeof t.hasFocus=="function"&&(this._onWindowFocus=()=>this.setFocus("focused"),this._onWindowBlur=()=>this.setFocus("unfocused"),this._win.addEventListener("focus",this._onWindowFocus),this._win.addEventListener("blur",this._onWindowBlur),this.setFocus(t.hasFocus()?"focused":"unfocused"))}get state(){return this._state}onState(e){return this._stateHandlers.add(e),()=>this._stateHandlers.delete(e)}transportConnecting(){this._setState("connecting")}transportReady(){this._setState("ready")}transportClosed(){this._setState("transient_failure")}attachTransport(e){if(this._disposed)return()=>{};this._setState(Id(e.state));let t=e.on("stateChange",s=>{this._setState(Id(s))}),n=()=>{t(),this._transportUnsubs.delete(n)};return this._transportUnsubs.add(n),n}_setState(e){if(!(this._disposed||e===this._state)){this._state=e;for(let t of this._stateHandlers)try{t(e)}catch{}}}interaction(e,t=1){this._disposed||!Number.isFinite(t)||t<=0||e==="pointer"&&this._focus==="unfocused"||(this._counts[e]+=t,this._signal())}consumerRead(e=1){this._disposed||!Number.isFinite(e)||e<=0||(this._counts.consumer_reads+=e,this._signal())}get inflight(){return this._inflight}workBegin(){if(this._disposed)return()=>{};this._inflight+=1,this._inflight===1&&this._publishNow();let e=!1;return()=>{e||this._disposed||(e=!0,this._inflight-=1,this._inflight===0&&this._publishNow())}}setVisibility(e){this._disposed||(this._visibility=e)}setFocus(e){if(!(this._disposed||e===this._focus)){this._focus=e;try{this._awareness?.setLocalStateField(Qi,e)}catch{}}}_signal(){this._lastSignalAt=this._now();let e=this._lastPublishedAt===void 0?1/0:this._lastSignalAt-this._lastPublishedAt;if(e>=3e4){this._publishNow();return}if(this._trailing)return;let t=Math.max(3e4-e,0);this._trailing=setTimeout(()=>{this._trailing=null,this._disposed||this._publishNow()},t),this._trailing.unref?.()}_publishNow(){this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._lastPublishedAt=this._now();let e={at:this._lastSignalAt??this._lastPublishedAt,counts:{...this._counts},inflight:this._inflight};this._visibility!==void 0&&(e.visibility=this._visibility),this._focus!==void 0&&(e.focus=this._focus);try{this._awareness?.setLocalStateField(Yi,e)}catch{}}dispose(){if(!this._disposed){for(let e of Array.from(this._transportUnsubs))e();this._transportUnsubs.clear(),this._win&&(this._onWindowFocus&&this._win.removeEventListener("focus",this._onWindowFocus),this._onWindowBlur&&this._win.removeEventListener("blur",this._onWindowBlur)),this._onWindowFocus=null,this._onWindowBlur=null,this._trailing&&(clearTimeout(this._trailing),this._trailing=null),this._state="idle",this._stateHandlers.clear(),this._disposed=!0}}};var Ad=250;function ms(r){if(typeof document>"u"||typeof window>"u"||typeof document.addEventListener!="function"||typeof window.addEventListener!="function")return()=>{};let e=0,t=()=>{if(document.visibilityState==="hidden")return;let n=Date.now();n-e<250||(e=n,r())};return document.addEventListener("visibilitychange",t),window.addEventListener("pageshow",t),window.addEventListener("focus",t),()=>{document.removeEventListener("visibilitychange",t),window.removeEventListener("pageshow",t),window.removeEventListener("focus",t)}}function gs(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=!1,t=n=>{n.persisted||e||(e=!0,r())};return window.addEventListener("pagehide",t),()=>{window.removeEventListener("pagehide",t)}}function _s(r){if(typeof window>"u"||typeof window.addEventListener!="function")return()=>{};let e=t=>{r()&&(t.preventDefault(),t.returnValue="")};return window.addEventListener("beforeunload",e),()=>{window.removeEventListener("beforeunload",e)}}var Ld="video/mp4";function vs(r,e={}){let t=e.timesliceMs??1e3,n=null,s=null,i=!1,o=(a,c,u)=>{let d=typeof MediaRecorder>"u"?void 0:MediaRecorder;if(!d)throw new Error("[urun] stream.chunks(): MediaRecorder is unavailable in this runtime. Pass { source } to chunks() to inject a byte-tap (e.g. a Node/werift consumer).");let l=e.mimeType??(typeof d.isTypeSupported=="function"&&d.isTypeSupported(Ld)?Ld:void 0),p=new MediaStream([a]),f=new d(p,l?{mimeType:l}:void 0);n=f;let h=Promise.resolve();f.ondataavailable=m=>{let g=m.data;i||!g||g.size===0||(h=h.then(async()=>{let _=new Uint8Array(await g.arrayBuffer());i||c(_)}))},f.onstop=()=>{h.then(()=>{i||u()})},f.onerror=()=>{h.then(()=>{i||u()})},f.start(t)};return{start(a,c){if(n||i)return;let u=r.track();if(u){o(u,a,c);return}s=r.onTrack(d=>{!d||n||i||(s?.(),s=null,o(d,a,c))})},stop(){if(i)return;i=!0,s?.(),s=null;let a=n;if(n=null,a&&a.state!=="inactive")try{a.stop()}catch{}}}}function tm(r){let e=r;return typeof e[Symbol.asyncIterator]=="function"||(e[Symbol.asyncIterator]=function(){let t=r.getReader();return{next(){return t.read()},async return(){try{await t.cancel()}catch{}try{t.releaseLock()}catch{}return{value:void 0,done:!0}},[Symbol.asyncIterator](){return this}}}),e}function Md(r,e){let t=null,n=!1,s=!1,i=new ReadableStream({pull(o){n||(n=!0,t=r(e),t.start(a=>{if(!s)try{o.enqueue(a)}catch{}},()=>{if(!s){s=!0;try{o.close()}catch{}}}))},cancel(){s=!0,t?.stop(),t=null}},new CountQueuingStrategy({highWaterMark:0}));return tm(i)}var ws=require("@msgpack/msgpack"),Xi=65536;function ys(r){let e=(0,ws.encode)(r),t=new Uint8Array(4+e.byteLength);return new DataView(t.buffer).setUint32(0,e.byteLength,!0),t.set(e,4),t}var ar=class{buf=new Uint8Array(0);push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(n>Xi)throw new Error("[urun] wt control frame too large");if(this.buf.byteLength<4+n)break;let s=this.buf.subarray(4,4+n);this.buf=this.buf.subarray(4+n),t.push((0,ws.decode)(s))}return t}},ue=12,Ji=1,rm=0,bs=1,Od=2;function cr(r){let e=r.getUint8(8);return{groupId:r.getUint32(0,!0),frameSeq:r.getUint32(4,!0),keyframe:(e&Ji)===Ji,fragIndex:r.getUint8(9),fragCount:r.getUint8(10),lane:r.getUint8(11)}}function Ss(r){let e=new Uint8Array(ue),t=new DataView(e.buffer);return t.setUint32(0,r.groupId,!0),t.setUint32(4,r.frameSeq,!0),t.setUint8(8,r.keyframe?Ji:0),t.setUint8(9,r.fragIndex),t.setUint8(10,r.fragCount),t.setUint8(11,r.lane??rm),e}var nm=100,Ud=100,dr=class{constructor(e,t={}){this.cb=e;this.now=t.now??(()=>performance.now()),this.debounceMs=t.keyframeRequestDebounceMs??nm}cb;pending=new Map;newestGroupSeen=-1;newestFrameDelivered=-1;needKeyframe=!0;kfRequestedAt=-1/0;now;debounceMs;bytesInWindow=0;framesDelivered=0;framesAbandoned=0;push(e){if(e.byteLength<ue)return;let t=cr(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.isSourceRestart(t.groupId,t.frameSeq))this.resync(t.groupId);else if(t.groupId<this.newestGroupSeen||(t.groupId>this.newestGroupSeen&&(this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=t.groupId,this.needKeyframe=!0),t.frameSeq<=this.newestFrameDelivered))return;let n=this.pending.get(t.frameSeq);if(n||(n={groupId:t.groupId,keyframe:t.keyframe,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n)),!n.chunks[t.fragIndex]){n.chunks[t.fragIndex]=e.subarray(ue),n.received++,n.received===n.fragCount&&(this.pending.delete(t.frameSeq),this.deliver(t.frameSeq,n));for(let s of this.pending.keys())s<t.frameSeq-1&&(this.pending.delete(s),this.framesAbandoned++)}}isSourceRestart(e,t){return this.newestGroupSeen<0?!1:e<this.newestGroupSeen-Ud?!0:e!==this.newestGroupSeen?!1:t<this.newestFrameDelivered-Ud}resync(e){this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestGroupSeen=e,this.newestFrameDelivered=-1,this.needKeyframe=!0,this.requestKeyframe()}requireKeyframe(){this.needKeyframe=!0}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}deliver(e,t){if(this.needKeyframe&&!t.keyframe){this.framesAbandoned++,this.requestKeyframe();return}if(e!==this.newestFrameDelivered+1&&!t.keyframe&&this.newestFrameDelivered>=0){this.needKeyframe=!0,this.framesAbandoned++,this.requestKeyframe();return}let n=t.chunks.reduce((o,a)=>o+a.byteLength,0),s=new Uint8Array(n),i=0;for(let o of t.chunks)s.set(o,i),i+=o.byteLength;this.needKeyframe=!1,this.newestFrameDelivered=e,this.framesDelivered++,this.cb.onFrame({seq:e,groupId:t.groupId,keyframe:t.keyframe,data:s})}requestKeyframe(){let e=this.now();e-this.kfRequestedAt<this.debounceMs||(this.kfRequestedAt=e,this.cb.onKeyframeNeeded())}};var sm=/^avc[13]\.[0-9a-fA-F]{6}$/;function im(r){return sm.test(r)?null:`codec ${JSON.stringify(r)} is not a fully-qualified WebCodecs H.264 string \u2014 the WT pipeline carries H.264, which VideoDecoder.configure needs as "avc1.PPCCLL" (e.g. "avc1.42E01F"); RTP MIMEs ("video/H264") and bare names ("h264") are rejected by WebCodecs as "Unknown or ambiguous codec name"`}function Zi(r,e){let t=im(r);if(t)throw new Error(`[urun] webtransport ${e} ${t}`)}var eo=1,Xr=class{buf=new Uint8Array(0);name=null;ended=!1;get streamName(){return this.name}push(e){if(e.byteLength>0){let n=new Uint8Array(this.buf.byteLength+e.byteLength);n.set(this.buf),n.set(e,this.buf.byteLength),this.buf=n}if(this.name===null){if(this.buf.byteLength<2)return[];let n=this.buf[0];if(n!==eo)throw new Error(`[urun] wt data stream: unknown header version 0x${n.toString(16)} \u2014 rejecting stream`);let s=this.buf[1];if(s===0)throw new Error("[urun] wt data stream: empty stream name in header \u2014 rejecting stream");if(this.buf.byteLength<2+s)return[];this.name=new TextDecoder().decode(this.buf.subarray(2,2+s)),this.buf=this.buf.subarray(2+s)}let t=[];for(;this.buf.byteLength>=4;){let n=new DataView(this.buf.buffer,this.buf.byteOffset).getUint32(0,!0);if(this.buf.byteLength<4+n)break;if(this.ended)throw new Error(`[urun] wt data stream "${this.name}": envelope after the END envelope \u2014 rejecting stream`);let s=os(this.buf.subarray(4,4+n));this.buf=this.buf.subarray(4+n),s===gt&&(this.ended=!0),t.push({name:this.name,payload:s})}if(this.ended&&this.buf.byteLength>0)throw new Error(`[urun] wt data stream "${this.name}": trailing bytes after the END envelope \u2014 rejecting stream`);return t}finish(){if(this.ended&&this.buf.byteLength===0)return;let e=this.name===null?"<incomplete header>":`"${this.name}"`;throw this.buf.byteLength>0?new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN mid-${this.name===null?"header":"envelope"} (${this.buf.byteLength} dangling byte(s), no END envelope)`):new Error(`[urun] wt data stream ${e}: truncated \u2014 FIN without an END envelope`)}};async function ks(r,e){let t=r.getReader();for(;;){let{value:n,done:s}=await t.read();if(s)return;n&&om(n,e).catch(i=>{e.onLaneError(i instanceof Error?i:new Error(String(i)))})}}async function om(r,e){let t=r.getReader(),n=new Xr;try{for(;;){let{value:s,done:i}=await t.read();if(i)break;if(!(!s||s.byteLength===0))for(let{name:o,payload:a}of n.push(s))e.onData(o,a)}n.finish()}catch(s){try{await t.cancel?.(s)}catch{}throw s}}var to=40,no=48e3,am=64,cm=100,ro=class{constructor(e){this.onFrame=e}onFrame;pending=new Map;newestDelivered=-1;framesDelivered=0;framesAbandoned=0;bytesInWindow=0;push(e){if(e.byteLength<ue)return;let t=cr(new DataView(e.buffer,e.byteOffset));if(this.bytesInWindow+=e.byteLength,this.newestDelivered>=0&&t.frameSeq<this.newestDelivered-cm)this.framesAbandoned+=this.pending.size,this.pending.clear(),this.newestDelivered=-1;else if(t.frameSeq<=this.newestDelivered)return;if(t.fragCount===0)return;let n=this.pending.get(t.frameSeq);if(!n)for(n={timestamp:t.groupId,fragCount:t.fragCount,received:0,chunks:new Array(t.fragCount)},this.pending.set(t.frameSeq,n);this.pending.size>am;){let a=1/0;for(let c of this.pending.keys())c<a&&(a=c);this.pending.delete(a),this.framesAbandoned++}if(t.fragIndex>=n.fragCount||n.chunks[t.fragIndex]||(n.chunks[t.fragIndex]=e.subarray(ue),n.received++,n.received<n.fragCount))return;this.pending.delete(t.frameSeq);for(let a of this.pending.keys())a<t.frameSeq&&(this.pending.delete(a),this.framesAbandoned++);let s=n.chunks.reduce((a,c)=>a+(c?.byteLength??0),0),i=new Uint8Array(s),o=0;for(let a of n.chunks)i.set(a,o),o+=a.byteLength;this.newestDelivered=t.frameSeq,this.framesDelivered++,this.onFrame({seq:t.frameSeq,timestamp:n.timestamp,data:i})}drainWindow(){let e={bytes:this.bytesInWindow,delivered:this.framesDelivered,abandoned:this.framesAbandoned};return this.bytesInWindow=0,this.framesDelivered=0,this.framesAbandoned=0,e}},dm=3,um=1e4,Ts=class{constructor(e,t){this.config=e;this.seam=t;let n=this.seam.jitterBufferTargetMs??to;Number.isFinite(n)||(console.warn(`[urun] WT audio jitterBufferTargetMs=${n} is not finite \u2014 using default ${to}ms`),n=to),this.targetS=Math.max(0,n)/1e3}config;seam;decoder=null;decoderErrorsAt=[];ctx=null;dest=null;trackSurfaced=!1;stopped=!1;playhead=0;targetS;deadCb=null;assembler=new ro(e=>this.decodeFrame(e));start(){let e=globalThis.AudioDecoder,t=globalThis.AudioContext;if(typeof e!="function"||typeof t!="function")throw new Error("[urun] WT audio lane engaged without AudioDecoder/AudioContext");this.ctx=new t({sampleRate:this.config.sampleRate}),this.dest=this.ctx.createMediaStreamDestination();try{this.initDecoder(e)}catch(n){throw this.ctx.close().catch(()=>{}),this.ctx=null,this.dest=null,n}}onDead(e){this.deadCb=e}stop(){if(!this.stopped){this.stopped=!0,this.trackSurfaced&&(this.trackSurfaced=!1,this.seam.onTrack(null));try{this.decoder?.close()}catch{}this.ctx?.close().catch(()=>{})}}initDecoder(e){this.decoder=new e({output:t=>this.schedule(t),error:t=>this.onDecoderError(t)}),this.decoder.configure({codec:this.config.codec,sampleRate:this.config.sampleRate,numberOfChannels:this.config.channels})}decodeFrame(e){let t=globalThis.EncodedAudioChunk;!this.decoder||typeof t!="function"||this.stopped||this.decoder.decode(new t({type:"key",timestamp:Math.round(e.timestamp*(1e6/no)),data:e.data}))}schedule(e){let t=this.ctx,n=this.dest;if(!t||!n||this.stopped){e.close();return}if(!this.trackSurfaced){this.trackSurfaced=!0,t.resume?.().catch(()=>{});let d=n.stream.getAudioTracks()[0];d&&this.seam.onTrack(d)}let s=e.numberOfFrames,i=Math.max(1,e.numberOfChannels),o=t.createBuffer(i,s,e.sampleRate);for(let d=0;d<i;d++){let l=new Float32Array(s);e.copyTo(l,{planeIndex:d,format:"f32-planar"}),o.copyToChannel(l,d)}let a=s/e.sampleRate;e.close();let c=t.createBufferSource();c.buffer=o,c.connect(n);let u=Math.max(this.playhead,t.currentTime+this.targetS);c.start(u),this.playhead=u+a}onDecoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(s=>t-s<um),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=dm){let s=`audio decoder: ${e.message}`;console.warn(`[urun] WT audio lane dead (${s}) \u2014 audio reverts to the WebRTC track`),this.stop(),this.deadCb?.(s);return}console.warn("[urun] WT audio decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let n=globalThis.AudioDecoder;typeof n=="function"&&this.initDecoder(n)}};var Zr=1200,lm=3,pm=1e4;function hm(r){return Math.round(r*(no/1e6))%2**32>>>0}function so(r,e,t,n,s){let i=n-ue;if(i<=0)return null;let o=Math.max(1,Math.ceil(t.byteLength/i));if(o>255)return null;let a=[];for(let c=0;c<o;c++){let u=t.subarray(c*i,Math.min((c+1)*i,t.byteLength)),d=Ss({groupId:e>>>0,frameSeq:r>>>0,keyframe:s?.keyframe??!0,fragIndex:c,fragCount:o,lane:s?.lane??bs}),l=new Uint8Array(ue+u.byteLength);l.set(d,0),l.set(u,ue),a.push(l)}return a}var Rs=class{constructor(e){this.sink=e}sink;encoder=null;encoderConfig=null;encoderErrorsAt=[];frameSeq=0;stopped=!1;deadCb=null;generation=0;cancelCapture=null;captureTrack=null;nodeBridge=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}setSource(e){if(this.stopped||e!==null&&e===this.captureTrack&&this.captureTrack.readyState==="live"||(this.teardownCapture(),e===null))return;let n=globalThis.MediaStreamTrackProcessor;if(typeof n!="function"){this.die("MediaStreamTrackProcessor is not available");return}let s;if(fm(e)){let c=e,u=c.context.createMediaStreamDestination();c.connect(u),this.nodeBridge={node:c,dest:u};let d=u.stream.getAudioTracks()[0];if(!d){this.die("AudioNode bridge produced no audio track");return}s=d}else s=e;let i=++this.generation,o=new n({track:s}).readable.getReader();this.captureTrack=s;let a=!1;this.cancelCapture=()=>{a=!0,o.cancel().catch(()=>{})},(async()=>{for(;!a&&!this.stopped&&i===this.generation;){let{value:c,done:u}=await o.read();if(u)break;if(c){if(a||this.stopped||i!==this.generation){c.close();break}this.encodeAudioData(c)}}!a&&!this.stopped&&i===this.generation&&(this.captureTrack=null)})().catch(c=>{!a&&!this.stopped&&i===this.generation&&this.die(`capture: ${c instanceof Error?c.message:String(c)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){if(this.cancelCapture?.(),this.cancelCapture=null,this.captureTrack=null,this.nodeBridge){try{this.nodeBridge.node.disconnect(this.nodeBridge.dest)}catch{}this.nodeBridge=null}this.generation++}encodeAudioData(e){if(!this.encoder){let n=globalThis.AudioEncoder;if(typeof n!="function"){e.close(),this.die("AudioEncoder is not available");return}this.encoderConfig={sampleRate:e.sampleRate,numberOfChannels:e.numberOfChannels};try{this.initEncoder(n)}catch(s){e.close(),this.encoder=null,this.die(`encoder configure: ${s instanceof Error?s.message:String(s)}`);return}}let t=this.encoder;if(!t){e.close();return}try{t.encode(e)}catch(n){this.onEncoderError(n instanceof Error?n:new Error(String(n)))}e.close()}initEncoder(e){let t=this.encoderConfig;this.encoder=new e({output:n=>this.sendFrame(n),error:n=>this.onEncoderError(n)}),this.encoder.configure({codec:"opus",sampleRate:t.sampleRate,numberOfChannels:t.numberOfChannels,bitrate:32e3})}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let n=so(this.frameSeq,hm(e.timestamp),t,this.sink.maxDatagramSize()||Zr);if(n===null){console.warn(`[urun] WT mic uplink: frame of ${t.byteLength}B exceeds the fragment budget \u2014 dropped`),this.frameSeq=this.frameSeq+1>>>0;return}for(let s of n)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(s=>t-s<pm),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=lm){this.die(`audio encoder: ${e.message}`);return}console.warn("[urun] WT mic uplink encoder error \u2014 re-initializing the encoder:",e.message);try{this.encoder?.close()}catch{}this.encoder=null;let n=globalThis.AudioEncoder;if(!(typeof n!="function"||!this.encoderConfig))try{this.initEncoder(n)}catch(s){this.die(`encoder re-init: ${s instanceof Error?s.message:String(s)}`)}}die(e){this.stopped||(console.warn(`[urun] WT mic uplink lane dead (${e}) \u2014 the mic reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function fm(r){let e=r;return typeof e.connect=="function"&&typeof e.context=="object"&&e.context!==null}var mm=9e4,gm="avc1.42E01F",_m=60,vm=3,wm=1e4;function ym(r){return Math.round(r*(mm/1e6))%2**32>>>0}var Cs=class{constructor(e){this.sink=e}sink;encoder=null;encoderDims=null;encoderErrorsAt=[];frameSeq=0;framesSinceKeyframe=0;keyframeWanted=!1;stopped=!1;deadCb=null;generation=0;cancelCapture=null;deliveredDatagrams(){return this.sink.delivered()}onDead(e){this.deadCb=e}requestKeyframe(){this.keyframeWanted=!0}setSource(e){if(this.stopped||(this.teardownCapture(),e===null))return;let n=globalThis.MediaStreamTrackProcessor;if(typeof n!="function"){this.die("MediaStreamTrackProcessor is not available");return}this.keyframeWanted=!0;let s=++this.generation,i=new n({track:e}).readable.getReader(),o=!1;this.cancelCapture=()=>{o=!0,i.cancel().catch(()=>{})},(async()=>{for(;!o&&!this.stopped&&s===this.generation;){let{value:a,done:c}=await i.read();if(c)break;if(a){if(o||this.stopped||s!==this.generation){a.close();break}this.encodeFrame(a)}}})().catch(a=>{!o&&!this.stopped&&s===this.generation&&this.die(`capture: ${a instanceof Error?a.message:String(a)}`)})}stop(){if(!this.stopped){this.stopped=!0,this.teardownCapture();try{this.encoder?.close()}catch{}this.encoder=null}}teardownCapture(){this.cancelCapture?.(),this.cancelCapture=null,this.generation++}encodeFrame(e){let t={width:e.codedWidth,height:e.codedHeight};if(!this.encoder||!this.encoderDims||this.encoderDims.width!==t.width||this.encoderDims.height!==t.height){let i=globalThis.VideoEncoder;if(typeof i!="function"){e.close(),this.die("VideoEncoder is not available");return}try{this.encoder||(this.encoder=new i({output:o=>this.sendFrame(o),error:o=>this.onEncoderError(o)})),this.encoderDims=t,this.encoder.configure({codec:gm,avc:{format:"annexb"},width:t.width,height:t.height,latencyMode:"realtime",hardwareAcceleration:"no-preference"}),this.keyframeWanted=!0}catch(o){e.close();try{this.encoder?.close()}catch{}this.encoder=null,this.die(`encoder configure: ${o instanceof Error?o.message:String(o)}`);return}}let s=this.keyframeWanted||this.framesSinceKeyframe>=_m;this.keyframeWanted=!1,this.framesSinceKeyframe=s?0:this.framesSinceKeyframe+1;try{this.encoder.encode(e,{keyFrame:s})}catch(i){this.onEncoderError(i instanceof Error?i:new Error(String(i)))}e.close()}sendFrame(e){if(this.stopped)return;let t=new Uint8Array(e.byteLength);e.copyTo(t);let n=so(this.frameSeq,ym(e.timestamp),t,this.sink.maxDatagramSize()||Zr,{lane:Od,keyframe:e.type==="key"});if(n===null){console.warn(`[urun] WT video uplink: AU of ${t.byteLength}B exceeds the fragment budget \u2014 dropped, re-keying`),this.frameSeq=this.frameSeq+1>>>0,this.keyframeWanted=!0;return}for(let s of n)this.sink.send(s);this.frameSeq=this.frameSeq+1>>>0}onEncoderError(e){if(this.stopped)return;let t=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();if(this.encoderErrorsAt=this.encoderErrorsAt.filter(n=>t-n<wm),this.encoderErrorsAt.push(t),this.encoderErrorsAt.length>=vm){this.die(`video encoder: ${e.message}`);return}console.warn("[urun] WT video uplink encoder error \u2014 re-initializing:",e.message);try{this.encoder?.close()}catch{}this.encoder=null,this.encoderDims=null}die(e){this.stopped||(console.warn(`[urun] WT video uplink lane dead (${e}) \u2014 the camera reverts to the WebRTC produce path`),this.stop(),this.deadCb?.(e))}};function bm(r){return r.byteLength>=2&&r[0]===1&&r[1]===3}var Es=class{constructor(e){this.transport=e}transport;streams=new Map;dead=null;deadCb=null;chain=Promise.resolve();onDead(e){this.deadCb=e}send(e,t){let n=new TextEncoder().encode(e);if(n.byteLength===0||n.byteLength>255)return Promise.reject(new Error(`[urun] wt data uplink: stream name must be 1..=255 utf8 bytes (got ${n.byteLength})`));let s=this.chain.then(async()=>{if(this.dead!==null)throw new Error(`[urun] wt data uplink lane is dead (${this.dead})`);try{let i=this.streams.get(e);if(!i){let a=await this.transport.openUniStream(),c=new Uint8Array(2+n.byteLength);c[0]=1,c[1]=n.byteLength,c.set(n,2),await a.write(c),i={writer:a},this.streams.set(e,i)}let o=new Uint8Array(4+t.byteLength);new DataView(o.buffer).setUint32(0,t.byteLength,!0),o.set(t,4),await i.writer.write(o),bm(t)&&(this.streams.delete(e),await i.writer.close().catch(()=>{}))}catch(i){throw this.die(i instanceof Error?i.message:String(i)),i}});return this.chain=s.catch(()=>{}),s}stop(e="stopped"){if(this.dead===null){this.dead=e;for(let t of this.streams.values())t.writer.close().catch(()=>{});this.streams.clear()}}die(e){this.dead===null&&(console.warn(`[urun] WT data uplink lane dead (${e})`),this.stop(e),this.deadCb?.(e))}};var io=250,Sm=3,km=1e4,oo=2500,Tm=25,Rm=2e3,ur=class{constructor(e,t,n,s,i,o,a){this.offer=e;this.sessionId=t;this.canvas=n;this.audioLane=s;this.audioUplink=i;this.videoUplink=o;this.dataUplink=a;this.firstMedia=new Promise((c,u)=>{this.firstFrameResolve=c,this.firstFrameReject=u}),this.firstMedia.catch(()=>{})}offer;sessionId;canvas;audioLane;audioUplink;videoUplink;dataUplink;kind="webtransport";wt;decoder=null;decoderConfig=null;decoderErrorsAt=[];writer;dgramWriter=null;deadCb=null;deadFired=!1;stopped=!1;feedbackTimer=null;closedReason=null;controlWriteError=null;controlWritesAccepted=0;gatewayPings=0;reassembler=new dr({onFrame:e=>this.decodeFrame(e.seq,e.keyframe,e.data),onKeyframeNeeded:()=>{this.sendControl({t:"keyframe-request"}).catch(()=>{})}});lastArrivalTs=0;jitterEwmaMs=0;lastStats={recvBps:0,lossPct:0,jitterMs:0};dataLaneSink=null;audioPlayout=null;audioUplinkLane=null;videoUplinkLane=null;dataUplinkSender=null;firstFrameResolve=null;firstFrameReject=null;uplinkSendErrorsAt=[];uplinkSendErrorLogged=!1;hasVideoLane=!1;videoArrivedEver=!1;videoArrivalsInWindow=0;frameOutputEver=!1;frameOutputsInWindow=0;decodeStalledMs=0;firstMedia;async start(){let e=globalThis.WebTransport;if(typeof e!="function")throw new Error("[urun] WebTransport API not available");let t=this.offer.codec,n=t!==void 0&&t!=="";this.hasVideoLane=n,n&&Zi(t,"transport.offer"),this.wt=new e(this.offer.url,{serverCertificateHashes:this.offer.certHashes.map(d=>({algorithm:"sha-256",value:Uint8Array.from(atob(d),l=>l.charCodeAt(0))})),congestionControl:"low-latency"}),await this.wt.ready;let s=await this.wt.createBidirectionalStream();this.writer=s.writable.getWriter(),await this.sendControl({t:"hello",token:this.offer.token,sessionId:this.sessionId});let i=s.readable.getReader(),o=new ar,a=[],c=await this.readControl(i,o,a);if(c?.t!=="hello-ack")throw new Error("[urun] gateway rejected hello");if(n&&(Zi(c.codec,"hello-ack"),this.initDecoder(c.codec,c.width,c.height)),this.offer.audio&&this.audioLane){let d=new Ts(this.offer.audio,this.audioLane);d.onDead(()=>{this.audioPlayout=null});try{d.start(),this.audioPlayout=d}catch(l){console.warn(`[urun] WT audio lane failed to start (${l instanceof Error?l.message:String(l)}) \u2014 keeping the WT video session; audio stays on the WebRTC path`),d.stop()}}let u=()=>{this.datagramWriter();let d=0;return{send:l=>this.uplinkSend(l,()=>{d++}),delivered:()=>d,maxDatagramSize:()=>this.wt.datagrams.maxDatagramSize??Zr}};if(this.offer.audioUp===!0&&this.audioUplink)try{let d=new Rs(u());d.onDead(l=>{this.audioUplinkLane=null,this.audioUplink.onUplinkLost(l)}),this.audioUplinkLane=d,this.audioUplink.onUplink(d)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT mic uplink failed to engage (${l}) \u2014 keeping the WT session; the mic stays on the WebRTC produce path`),this.audioUplink.onUplinkLost(l)}if(this.offer.videoUp===!0&&this.videoUplink)try{let d=new Cs(u());d.onDead(l=>{this.videoUplinkLane=null,this.videoUplink.onUplinkLost(l)}),this.videoUplinkLane=d,this.videoUplink.onUplink(d)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT video uplink failed to engage (${l}) \u2014 keeping the WT session; the camera stays on the WebRTC produce path`),this.videoUplink.onUplinkLost(l)}if(this.offer.dataUp===!0&&this.dataUplink)try{let d=this.wt.createUnidirectionalStream?.bind(this.wt);if(!d)throw new Error("WebTransport uni streams are not creatable in this environment");let l=new Es({openUniStream:async()=>(await d()).getWriter()});l.onDead(p=>{this.dataUplinkSender=null,this.dataUplink.onUplinkLost(p)}),this.dataUplinkSender=l,this.dataUplink.onUplink(l)}catch(d){let l=d instanceof Error?d.message:String(d);console.warn(`[urun] WT data uplink failed to engage (${l}) \u2014 keeping the WT session; data-up stays on SCTP for this leg`),this.dataUplink.onUplinkLost(l)}this.controlLoop(i,o,a).catch(d=>this.die(`control loop: ${d}`)),this.datagramLoop().catch(d=>this.die(`datagram loop: ${d}`)),this.feedbackLoop(),this.wt.closed.then(()=>{this.closedReason="connection closed",this.die("connection closed")}).catch(d=>{this.closedReason=`connection error: ${d}`,this.die(`connection error: ${d}`)})}pathLiveness(){return this.closedReason?{alive:!1,evidence:`quic session closed (${this.closedReason})`}:this.controlWriteError?{alive:!1,evidence:`quic control stream refused a write (${this.controlWriteError}) \u2014 the send path is gone`}:this.stopped?{alive:!1,evidence:"webtransport session stopped"}:{alive:!0,evidence:`quic session open; ${this.controlWritesAccepted} control frames accepted by the QUIC stack (one per ${io}ms, so the path is continuously exercised); ${this.gatewayPings} gateway pings`}}fail(e){this.die(e)}async stop(){this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error("[urun] webtransport session stopped")),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks("webtransport session stopped"),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}try{this.wt?.close()}catch{}}datagramWriter(){if(!this.dgramWriter){let e=this.wt.datagrams.writable;if(!e)throw new Error("WebTransport datagrams are not writable in this environment");this.dgramWriter=e.getWriter()}return this.dgramWriter}releaseDatagramWriter(){let e=this.dgramWriter;if(e){this.dgramWriter=null;try{e.releaseLock?.()}catch{}}}dropUplinks(e){this.dropDatagramUplinks(e);let t=this.dataUplinkSender;t&&(this.dataUplinkSender=null,t.stop(e),this.dataUplink?.onUplinkLost(e))}dropDatagramUplinks(e){let t=this.audioUplinkLane;t&&(this.audioUplinkLane=null,t.stop(),this.audioUplink?.onUplinkLost(e));let n=this.videoUplinkLane;n&&(this.videoUplinkLane=null,n.stop(),this.videoUplink?.onUplinkLost(e))}onDead(e){this.deadCb=e}stats(){return this.lastStats}consumeDataStreams(e){if(this.dataLaneSink)throw new Error("[urun] webtransport data lane is already consuming (one lane per session)");this.dataLaneSink=e,ks(this.wt.incomingUnidirectionalStreams,e).catch(t=>{this.die(`data lane: ${t instanceof Error?t.message:String(t)}`)})}initDecoder(e,t,n){let s=globalThis.VideoDecoder;if(typeof s!="function")throw new Error("[urun] WebCodecs VideoDecoder not available");let i=this.canvas.getContext("2d");if(!i)throw new Error("[urun] canvas 2d context unavailable");this.decoderConfig={codec:e,width:t,height:n},this.decoder=new s({output:o=>{this.frameOutputEver=!0,this.frameOutputsInWindow++,this.canvas.width=o.displayWidth,this.canvas.height=o.displayHeight,i.drawImage(o,0,0),o.close()},error:o=>this.onDecoderError(o)}),this.decoder.configure({codec:e,...t>0&&n>0?{codedWidth:t,codedHeight:n}:{},optimizeForLatency:!0,hardwareAcceleration:"no-preference"})}onDecoderError(e){if(this.stopped||this.deadFired)return;let t=performance.now();if(this.decoderErrorsAt=this.decoderErrorsAt.filter(s=>t-s<km),this.decoderErrorsAt.push(t),this.decoderErrorsAt.length>=Sm){this.die(`decoder: ${e.message}`);return}console.warn("[urun] webtransport decoder error \u2014 re-initializing the decoder:",e.message);try{this.decoder?.close()}catch{}this.decoder=null;let n=this.decoderConfig;if(!n){this.die(`decoder: ${e.message} (no config to re-init from)`);return}try{this.initDecoder(n.codec,n.width,n.height)}catch(s){this.die(`decoder re-init: ${s instanceof Error?s.message:String(s)}`);return}this.reassembler.requireKeyframe(),this.sendControl({t:"keyframe-request"}).catch(()=>{})}evaluateDecodeLiveness(e,t){if(!this.videoArrivedEver)return!1;if(t>0)return this.decodeStalledMs=0,!1;if(e>0||!this.frameOutputEver)this.decodeStalledMs+=io;else return this.decodeStalledMs=0,!1;return this.decodeStalledMs<oo?!1:(console.error(`[urun] webtransport: media datagrams arriving but NO frame decoded within ${oo}ms \u2014 broken WT media leg; failing over LOUDLY`),this.die(`decode-stall: datagrams flowing but nothing decoded within ${oo}ms`),!0)}uplinkSend(e,t){if(this.stopped||this.deadFired)return;this.datagramWriter().write(e).then(t,s=>this.onUplinkSendError(s))}onUplinkSendError(e){if(this.stopped||this.deadFired)return;let t=e instanceof Error?e.message:String(e);this.uplinkSendErrorLogged||(this.uplinkSendErrorLogged=!0,console.error(`[urun] WT uplink datagram send FAILED (${t}) \u2014 the QUIC session is still established but nothing this client publishes is leaving it`));let n=typeof performance<"u"&&typeof performance.now=="function"?performance.now():Date.now();this.uplinkSendErrorsAt=this.uplinkSendErrorsAt.filter(s=>n-s<Rm),this.uplinkSendErrorsAt.push(n),!(this.uplinkSendErrorsAt.length<Tm)&&(this.uplinkSendErrorsAt=[],this.dropDatagramUplinks(`uplink datagram send failing: ${t}`))}async datagramLoop(){let e=this.wt.datagrams.readable.getReader();for(;!this.stopped;){let{value:t,done:n}=await e.read();if(n)break;if(!t)continue;if(t.byteLength>=ue&&t[11]===bs){this.audioPlayout?.assembler.push(t);continue}if(!this.hasVideoLane)continue;this.videoArrivedEver=!0,this.videoArrivalsInWindow++;let s=performance.now();if(this.lastArrivalTs>0){let i=s-this.lastArrivalTs;this.jitterEwmaMs+=(Math.abs(i-1e3/24)-this.jitterEwmaMs)/16}this.lastArrivalTs=s,this.reassembler.push(t)}}decodeFrame(e,t,n){let s=globalThis.EncodedVideoChunk;!this.decoder||typeof s!="function"||(this.decoder.decode(new s({type:t?"key":"delta",timestamp:e*(1e6/24),data:n})),this.firstFrameResolve?.(),this.firstFrameResolve=null,this.firstFrameReject=null)}async sendControl(e){try{await this.writer.write(ys(e)),this.controlWritesAccepted++}catch(t){let n=t instanceof Error?t.message:String(t);throw this.controlWriteError||(this.controlWriteError=n),this.die(`control stream write refused: ${n}`),t}}async readControl(e,t,n=[]){for(;;){let s=n.shift();if(s)return s;let{value:i,done:o}=await e.read();if(o)return null;i&&n.push(...t.push(i))}}async controlLoop(e,t,n){for(;!this.stopped;){let s=await this.readControl(e,t,n);if(!s)break;s.t==="ping"&&(this.gatewayPings++,this.sendControl({t:"pong",ts:s.ts}).catch(()=>{})),s.t==="keyframe-request"&&this.videoUplinkLane?.requestKeyframe()}}feedbackLoop(){let e=performance.now();this.feedbackTimer=setInterval(()=>{if(this.stopped)return;let t=performance.now(),n=(t-e)/1e3;e=t;let s=this.reassembler.drainWindow(),i=this.videoArrivalsInWindow,o=this.frameOutputsInWindow;if(this.videoArrivalsInWindow=0,this.frameOutputsInWindow=0,this.evaluateDecodeLiveness(i,o))return;let a=s.delivered+s.abandoned;this.lastStats={recvBps:n>0?s.bytes*8/n:0,lossPct:a>0?100*s.abandoned/a:0,jitterMs:this.jitterEwmaMs},this.sendControl({t:"feedback",...this.lastStats}).catch(()=>{})},io)}die(e){if(!(this.stopped||this.deadFired)){this.deadFired=!0,this.stopped=!0,this.feedbackTimer&&clearInterval(this.feedbackTimer),this.firstFrameReject?.(new Error(e)),this.firstFrameReject=null,this.firstFrameResolve=null,this.audioPlayout?.stop(),this.audioPlayout=null,this.dropUplinks(e),this.releaseDatagramWriter();try{this.decoder?.close()}catch{}this.deadCb?.(e)}}};var Nd=2500,Fd=["av01.0.08M.08","avc1.42E01F","avc1.640028"],Cm=1e4,lr=class{constructor(e,t,n){this.signaling=e;this.sessionId=t;this.opts=n}signaling;sessionId;opts;session=null;offer=null;quicDataLane=!1;wtOnlyLeg=!1;webRtcDialProceeded=!1;get activeTransport(){return this.session?.kind??null}get isWtOnlyLeg(){return this.wtOnlyLeg}async connect(){let e=globalThis,t=typeof e.WebTransport=="function",n=typeof e.VideoDecoder=="function",s=this.opts.allowWebTransport??!0,i={webtransport:t&&n&&s,webcodecs:n,codecs:Fd,wtData:t&&n&&s&&this.opts.dataLane!==void 0,wtAudio:t&&n&&s&&this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",wtAudioUp:t&&n&&s&&this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtVideoUp:t&&n&&s&&this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",wtDataUp:t&&n&&s&&this.opts.dataUplink!==void 0};this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:i});let o=i.webtransport&&!!this.offer.webtransport,a=this.offer.webtransport,c=o&&!!a&&(this.opts.audioLane===void 0||a.audio!==void 0)&&(this.opts.audioUplink===void 0||a.audioUp===!0)&&(this.opts.videoUplink===void 0||a.videoUp===!0)&&(this.opts.dataLane===void 0||a.data===!0)&&(this.opts.dataUplink===void 0||a.dataUp===!0);if(c||this.proceedWebRtcDial(o?"mixed grants \u2014 some lanes need WebRTC":"no WT attempt"),i.webtransport&&!this.offer.webtransport&&console.warn("[urun] webtransport unavailable: server offered webrtc only \u2014 staying on webrtc"),o){let u=null;try{return u=this.createWebTransportSession(),await ao(u.start(),this.opts.quicDeadlineMs??Nd,"quic connect deadline"),this.engageQuicDataLane(u,i.wtData===!0),this.session=u,c&&this.skipWebRtcDial("fully-granted WT leg established"),this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport"),this.session}catch(d){if(u?.stop().catch(()=>{}),this.opts.allowWebRtcFallback===!1){let l=String(d instanceof Error?d.message:d);throw console.error(`[urun] WT-REQUIRED leg failed to establish (${l}) \u2014 NO WebRTC fallback by policy; retrying WT`),this.opts.onWtRequiredOutage?.(l),d}console.warn("[urun] webtransport failed, falling back to webrtc:",d),this.proceedWebRtcDial(`wt failed: ${String(d instanceof Error?d.message:d)}`),this.notifyEstablished("webrtc",String(d instanceof Error?d.message:d))}}if(this.opts.allowWebRtcFallback===!1){let u=o?"unreachable":"no WT offer (server declined or client incapable)";throw console.error(`[urun] WT-REQUIRED leg cannot establish: ${u} \u2014 NO WebRTC fallback by policy`),this.opts.onWtRequiredOutage?.(u),new Error(`[urun] WT required but unavailable: ${u}`)}return this.session=await this.startWebRtc(),o||this.notifyEstablished("webrtc"),this.opts.onTransportChange?.("webrtc"),this.session}async disconnect(){this.quicDataLane=!1;let e=this.session;this.session=null,this.wtOnlyLeg=!1,await e?.stop()}async retryWebTransport(){if(this.session?.kind==="webtransport")return null;let e=globalThis;if(!(typeof e.WebTransport=="function"&&typeof e.VideoDecoder=="function")||!(this.opts.allowWebTransport??!0))return null;let n=this.session,s=this.opts.dataLane!==void 0,i=this.opts.audioLane!==void 0&&typeof e.AudioDecoder=="function"&&typeof e.AudioContext=="function",o=this.opts.audioUplink!==void 0&&typeof e.AudioEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",a=this.opts.videoUplink!==void 0&&typeof e.VideoEncoder=="function"&&typeof e.MediaStreamTrackProcessor=="function",c=this.opts.dataUplink!==void 0;if(this.offer=await this.signaling.request("transport.offer",{sessionId:this.sessionId,capabilities:{webtransport:!0,webcodecs:!0,codecs:Fd,wtData:s,wtAudio:i,wtAudioUp:o,wtVideoUp:a,wtDataUp:c}}),!this.offer.webtransport)return null;let u=this.createWebTransportSession();try{await ao(u.start(),this.opts.quicDeadlineMs??Nd,"quic connect deadline")}catch(d){throw u.stop().catch(()=>{}),d}if(this.session!==n)return u.stop().catch(()=>{}),null;try{this.engageQuicDataLane(u,s)}catch(d){throw u.stop().catch(()=>{}),d}this.session=u;{let d=this.offer.webtransport;d&&(this.opts.audioLane===void 0||d.audio!==void 0)&&(this.opts.audioUplink===void 0||d.audioUp===!0)&&(this.opts.videoUplink===void 0||d.videoUp===!0)&&(this.opts.dataLane===void 0||d.data===!0)&&(this.opts.dataUplink===void 0||d.dataUp===!0)&&this.skipWebRtcDial("fully-granted WT leg re-established")}return this.armFailover(),this.notifyEstablished("webtransport"),this.opts.onTransportChange?.("webtransport","background upgrade"),n?.stop().catch(()=>{}),u}engageQuicDataLane(e,t){if(!t||this.offer?.webtransport?.data!==!0)return;let n=this.opts.dataLane;if(typeof e.consumeDataStreams!="function")throw new Error("[urun] QUIC data lane negotiated but this WebTransport session cannot consume it \u2014 refusing the leg (a consumeData-less leg with an unconsumed lane black-holes every named stream)");e.consumeDataStreams({onData:(s,i)=>n.onData(s,i),onLaneError:s=>n.onLaneError(s)}),n.onQuicLane(),this.quicDataLane=!0}createWebTransportSession(){let e=this.offer.webtransport;if(this.opts.createWebTransportSession)return this.opts.createWebTransportSession(e);if(!this.opts.canvas)throw new Error("[urun] TransportNegotiator: canvas is required for the WebTransport path");return new ur(e,this.sessionId,this.opts.canvas,this.opts.audioLane,this.opts.audioUplink,this.opts.videoUplink,this.opts.dataUplink)}createWebRtc(){return this.opts.createWebRtcSession()}async startWebRtcOn(e){return await e.start(),e.onDead(t=>{console.error("[urun] webrtc path died:",t)}),e}async startWebRtc(){return this.startWebRtcOn(this.createWebRtc())}skipWebRtcDial(e){this.webRtcDialProceeded||!this.opts.webRtcDial||(this.opts.webRtcDial.skip(e),this.wtOnlyLeg=!0)}proceedWebRtcDial(e){this.webRtcDialProceeded=!0,this.wtOnlyLeg=!1,this.opts.webRtcDial?.proceed(e)}armFailover(){let e=this.session;e.onDead(t=>{if(this.opts.allowWebRtcFallback===!1){console.error(`[urun] WT-REQUIRED leg died mid-session (${t}) \u2014 NO WebRTC failover by policy; retrying WT`),this.wtOnlyLeg=!1,this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),this.session=null,this.opts.onWtRequiredOutage?.(t);return}let n=this.wtOnlyLeg;n&&this.proceedWebRtcDial(`failover: ${t}`),console.warn(n?"[urun] quic died mid-session on a WT-only leg (no RTCPeerConnection) \u2014 attempting a late WebRTC dial from scratch:":"[urun] quic died mid-session, failing over to webrtc:",t),this.quicDataLane&&(this.quicDataLane=!1,this.opts.dataLane?.onQuicLaneLost(t)),e.stop().catch(()=>{}),(async()=>{let s=this.createWebRtc();try{let i=await ao(this.startWebRtcOn(s),this.opts.webRtcFailoverDeadlineMs??Cm,"webrtc failover produced no media transport");if(this.session!==e){i.stop().catch(()=>{});return}this.session=i,this.notifyEstablished("webrtc",`failover: ${t}`),this.opts.onTransportChange?.("webrtc",t)}catch(i){if(s.stop().catch(()=>{}),this.session!==e)return;this.session=null;let o=i instanceof Error?i.message:String(i),a=n?`media transport lost \u2014 the WebTransport connection dropped (${t}) and this session is a WT-only leg with no RTCPeerConnection: WebRTC was never dialled, and the late fallback dial produced no media (${o}). No media transport is active.`:`media transport lost \u2014 the WebTransport connection dropped (${t}) and the WebRTC fallback produced no media (${o}). No media transport is active.`;console.error(`[urun] ${a}`),this.opts.onMediaTransportLost?.(a)}})()})}notifyEstablished(e,t){this.signaling.notify("transport.established",{sessionId:this.sessionId,transport:e,fallbackReason:t})}};function ao(r,e,t){return new Promise((n,s)=>{let i=setTimeout(()=>s(new Error(t)),e);r.then(o=>{clearTimeout(i),n(o)},o=>{clearTimeout(i),s(o)})})}var Em=1e4,pr=class{constructor(e,t=Em){this.carrier=e;this.requestTimeoutMs=t}carrier;requestTimeoutMs;request(e,t){let n=rr();return new Promise((s,i)=>{let o=setTimeout(()=>{a(),i(new Error(`[urun] signaling request timed out: ${e}`))},this.requestTimeoutMs),a=this.carrier.onSignal(c=>{if(c.type!==`${e}.response`||c.requestId!==n)return;if(clearTimeout(o),a(),c.error){i(new Error(`[urun] ${e} failed: ${String(c.error)}`));return}let{type:u,requestId:d,...l}=c;s(l)});this.carrier.sendSignal({type:e,requestId:n,...t})||(clearTimeout(o),a(),i(new Error(`[urun] signaling request not sent: ${e} \u2014 the signaling socket is not open`)))})}notify(e,t){this.carrier.sendSignal({type:e,...t})||this.carrier.emitDiagnostic({level:"warning",kind:"signaling-notify-undelivered",message:`signaling notify not sent: ${e} \u2014 the signaling socket is not open`,detail:{method:e}})}on(e,t){return this.carrier.onSignal(n=>{n.type===e&&t(n)})}};var Pm="video",hr=class{constructor(e,t=Pm){this.transport=e;this.streamName=t;this.firstMedia=new Promise((n,s)=>{this.firstMediaResolve=n,this.firstMediaReject=s}),this.firstMedia.catch(()=>{})}transport;streamName;kind="webrtc";deadCb=null;deadFired=!1;unsubscribers=[];firstMediaResolve=null;firstMediaReject=null;firstMedia;async start(){if(this.unsubscribers.push(this.transport.on("stateChange",t=>{t==="failed"&&this.die(`webrtc transport ${t}`)})),this.transport.getTrackByName(this.streamName)){this.firstMediaResolve?.(),this.firstMediaResolve=null;return}await new Promise(t=>{let n=this.transport.on("track",()=>{this.transport.getTrackByName(this.streamName)&&(n(),this.firstMediaResolve?.(),this.firstMediaResolve=null,t())});this.unsubscribers.push(n)})}async stop(){for(let e of this.unsubscribers.splice(0))e()}onDead(e){this.deadCb=e}stats(){return{recvBps:0,lossPct:0,jitterMs:0}}die(e){this.deadFired||(this.deadFired=!0,this.firstMediaReject?.(new Error(e)),this.firstMediaReject=null,this.firstMediaResolve=null,this.deadCb?.(e))}};function Wd(r){let e=r;return typeof e.pathLiveness=="function"&&typeof e.fail=="function"?e:null}var Dm="video";function jd(r,e,t){let n=globalThis,s=n.document;if(!(typeof s?.createElement=="function"&&typeof n.WebTransport=="function"&&typeof n.VideoDecoder=="function")||t.allowWebTransport===!1)return null;let o=r.holdWebRtcDial?.(),a=s.createElement("canvas"),c=!1,u=null,d=!1,l=()=>{if(u){for(let b of u.getVideoTracks())try{b.stop()}catch{}u=null}d&&(d=!1,t.onOverrideTrack(null))},p=new lr(new pr(r),e,{canvas:a,createWebRtcSession:t.createWebRtcSession??(()=>new hr(r,t.streamName??Dm)),createWebTransportSession:t.createWebTransportSession,dataLane:{onData:(b,L)=>r.dispatchQuicStreamData(b,L),onQuicLane:()=>r.markStreamDataLaneQuic(),onQuicLaneLost:b=>r.quicStreamDataLaneLost(b),onLaneError:b=>r.raiseQuicStreamDataError(b)},audioLane:t.onOverrideAudioTrack?{jitterBufferTargetMs:t.audioPlayout?.jitterBufferTargetMs,onTrack:b=>{c||t.onOverrideAudioTrack(b)}}:void 0,audioUplink:t.audioUplink,videoUplink:t.videoUplink,dataUplink:t.dataUplink,webRtcDial:o,allowWebRtcFallback:t.allowWebRtcFallback,onWtRequiredOutage:()=>y(),onMediaTransportLost:b=>{c||(l(),t.onOverrideAudioTrack?.(null),t.onMediaTransportLost?.(b),y())},onTransportChange:(b,L)=>{c||(b==="webrtc"&&(l(),y()),t.onTransportChange?.(b,L))}}),f=null,h=()=>{f!==null&&(clearInterval(f),f=null)},m=t.wtRetryBaseMs??2e3,g=t.wtRetryCapMs??3e4,_=null,v=0,y=()=>{if(c||_!==null||p.activeTransport==="webtransport")return;let b=Math.min(m*2**v,g);_=setTimeout(()=>{_=null,v+=1,p.retryWebTransport().then(L=>{if(c){L&&p.disconnect().catch(()=>{});return}if(L)return console.debug(`[urun] webtransport upgraded in background (retry ${v})`),v=0,w(L);y()}).catch(L=>{c||(console.debug(`[urun] webtransport background retry ${v} failed:`,L),y())})},b)},S=()=>{_!==null&&(clearTimeout(_),_=null)},w=async b=>{if(c||b.kind!=="webtransport")return;let L=t.pathHealthProbeMs??1e4;h();let q=!1;f=setInterval(()=>{if(c||p.activeTransport!=="webtransport")return;let B=Wd(b);if(!B){console.error("[urun] BUG: webtransport session does not implement PathHealthReporting \u2014 the path-health probe cannot run and this leg cannot be judged; disarming (no verdict is better than a verdict derived from media arrival)"),h();return}let ee=B.pathLiveness();if(!ee.alive){let re=p.isWtOnlyLeg;console.error(`[urun] webtransport path is DEAD: ${ee.evidence}`+(re?" \u2014 this is a WT-ONLY leg (the WebRTC dial was skipped, so NO RTCPeerConnection and no webrtc track exist to fall back to)":" \u2014 a WebRTC floor exists and stays authoritative")+"; failing the leg so WT is re-established"),h(),B.fail(`path health: ${ee.evidence}`);return}if(!q){if(q=!0,p.isWtOnlyLeg){console.warn(`[urun] webtransport established, no application media yet after ${L}ms \u2014 the QUIC PATH IS HEALTHY (${ee.evidence}), so this is an IDLE APPLICATION, not a dead path; keeping the leg (WT-only leg: no webrtc track exists) and continuing to watch the path`);return}console.warn(`[urun] webtransport established but no QUIC media after ${L}ms \u2014 no media datagrams reached this client (path healthy: ${ee.evidence}); webrtc track remains authoritative`)}},L);try{await b.firstMedia}catch(B){h(),console.debug("[urun] webtransport ended before any media flowed:",B);return}if(h(),c||p.activeTransport!=="webtransport"||typeof a.captureStream!="function")return;u=a.captureStream();let W=u.getVideoTracks()[0];W&&(d=!0,t.onOverrideTrack(W))};return(async()=>{let b=await p.connect();if(c){p.disconnect().catch(()=>{});return}await w(b)})().catch(b=>{if(h(),c){console.debug("[urun] transport negotiation aborted: session disposed mid-dial:",b);return}if(t.allowWebRtcFallback===!1){console.error("[urun] WT-REQUIRED: negotiation failed and WebRTC fallback is disabled \u2014 retrying WT:",b),y();return}o?.proceed(`negotiation unavailable: ${b instanceof Error?b.message:String(b)}`),console.warn("[urun] transport negotiation unavailable, staying on webrtc:",b),y()}),{activeTransport:()=>p.activeTransport,dispose(){c=!0,h(),S(),l(),t.onOverrideAudioTrack?.(null),p.disconnect().catch(()=>{})}}}var Im=new Set;function lo(r){if(r.functionsUrl)return{functionsUrl:r.functionsUrl,orgId:r.orgId,apiKey:r.apiKey,jwt:r.jwt,getAccessToken:r.getAccessToken,authProvider:r.authProvider}}var xm="rpc",po=3e4,qd=3e4,Am="rpc-resp";function Lm(r){return`${Am}:${r}`}function co(){return rr()}function Mm(r){if(r&&typeof r=="object"){let e=r.error;if(e&&typeof e=="object"){let{message:t,code:n}=e;return{message:typeof t=="string"?t:JSON.stringify(e),code:typeof n=="string"?n:void 0}}if(typeof e=="string")return{message:e}}return{message:typeof r=="string"?r:JSON.stringify(r)}}function Om(r,e,t,n,s,i,o,a,c,u){let d=[],l=null,p=!1,f=null,h=!1,m,g,_=new Promise((O,le)=>{m=O,g=le});_.catch(()=>{});let v=o(),y=null,S=null,w=null,b=null,L=null,q=null,W=!0,B=()=>{w&&(clearTimeout(w),w=null),b&&(b(),b=null)},ee=()=>{L&&(clearTimeout(L),L=null),q&&(q(),q=null)},re=!1,ge=()=>{re||!h||(re=!0,r.set({rpc:{[e]:null}}))},xe=()=>{W=!1,B(),ee(),y?.(),y=null,S?.(),S=null,a?.removeEventListener("abort",F),v.dispose(),ge()},je=()=>{if(l){if(d.length>0){let O=l;l=null,O.resolve({value:d.shift(),done:!1})}else if(f!==null){let O=l;l=null,O.reject(f)}else if(p){let O=l;l=null,O.resolve({value:void 0,done:!0})}}},vr=O=>{p||(d.push(O),je())},R=O=>{p||(f=O,p=!0,g(O),xe(),je())},x=O=>{p||(p=!0,m(O),xe(),je())},F=()=>{let O=a?.reason;R(O instanceof Te?O:new nt(e))},K=O=>{if(!(p||!O||typeof O!="object"))switch(ee(),ge(),O.t){case"delta":typeof O.delta=="string"&&vr(O.delta);break;case"response":x(O.body);break;case"error":{let{message:le,code:Ge}=Mm(O.body);R(new Te(le,{requestId:e,code:O.code??Ge}));break}}},M=()=>{let O=v.messages()[Symbol.asyncIterator]();y=()=>{O.return?.(void 0)};let le=()=>{W&&O.next().then(Ge=>{if(W){if(Ge.done){p||x(void 0);return}K(Ge.value),le()}},Ge=>{W&&R(Ge)})};le()},N=()=>{if(!h){if(h=!0,a){if(a.aborted){R(new nt(e));return}a.addEventListener("abort",F,{once:!0})}S=c?.(O=>R(O))??null,M(),r.set({rpc:{[e]:{args:t,respond_on:n,consumer_id:s,stream:i}}}),u&&u>0&&!r.synced&&(w=setTimeout(()=>{w=null,!p&&!r.synced&&R(new bt(u,e))},u),b=r.onSynced(()=>B())),q=r.onSynced(()=>{q=null,!(p||re||L)&&(L=setTimeout(()=>{L=null,!(p||re)&&console.warn(`[urun] request ${e} has not been picked up by the runtime after ${Math.round(qd/1e3)}s. If this app is a urun-python serve app (\`ctx.serve\`), its runtime does not read the \`rpc\` doc that request()/requestStream()/complete() writes \u2014 the call will never resolve (urun-sh/urun-ts#330). Serve-app chat rides the \`llm\` doc + \`llm-resp:<id>\` stream contract instead. The request keeps waiting; abort it via options.signal (request() also supports options.timeout).`)},qd))})}};return{deltas:{[Symbol.asyncIterator](){return{next(){if(N(),d.length>0)return Promise.resolve({value:d.shift(),done:!1});if(f!==null){let O=f;return f=null,Promise.reject(O)}return p?Promise.resolve({value:void 0,done:!0}):new Promise((O,le)=>{l={resolve:O,reject:le}})},return(){return p||(p=!0,m(void 0),xe()),Promise.resolve({value:void 0,done:!0})},throw(O){return p||(p=!0,g(O),xe()),Promise.reject(O)}}}},body:_,start:N}}function $d(r){if(r&&typeof r=="object"){let{epoch:e,by:t}=r,n={epoch:typeof e=="number"?e:0};return(t==="runtime"||t==="browser")&&(n.by=t),n}}function Um(r,e){let n=r.get("streams")?.[e];if(!n||typeof n!="object")return null;let{kind:s,rt:i,br:o}=n,a={};(s==="audio"||s==="video"||s==="data")&&(a.kind=s);let c=$d(i);c&&(a.rt=c);let u=$d(o);return u&&(a.br=u),a}var uo=class{constructor(e,t,n,s,i){this._name=e;this._transport=t;this._streamData=n;this._controlDoc=s;this._onActivity=i;this._track=this._transport.getTrackByName(this._name)??null,this._unsubscribeTransport=this._transport.on("track",()=>{let o=this._transport.getTrackByName(this._name)??null;o!==this._track&&this._setTrack(o)})}_name;_transport;_streamData;_controlDoc;_onActivity;_track=null;_overrideTrack=null;_handlers=new Map;_unsubscribeTransport=null;_subscribed=!1;_messageConsumers=new Set;_dataUnsub=null;_replay=[];_disposed=!1;messages(){this._requireStreamConsumeSupport(),this._ensureSubscribed();let e=this;return{[Symbol.asyncIterator](){let t=[...e._replay],n=null,s=!1,i=null,o={push(c){if(!s)if(n){let u=n;n=null,u.resolve({value:c,done:!1})}else t.push(c)},end(){if(s=!0,n){let c=n;n=null,c.resolve({value:void 0,done:!0})}}};e._messageConsumers.add(o);let a=()=>{s=!0,e._messageConsumers.delete(o)};return e._transport.mediaAvailability().then(c=>{if(!(c===null||s)&&(i=e._streamConsumeUnavailableError(c),a(),n)){let u=n;n=null,u.reject(i)}}),{next(){return t.length>0?Promise.resolve({value:t.shift(),done:!1}):i?Promise.reject(i):s?Promise.resolve({value:void 0,done:!0}):new Promise((c,u)=>{n={resolve:c,reject:u}})},return(){return a(),Promise.resolve({value:void 0,done:!0})}}}}}_requireStreamConsumeSupport(){let e=this._transport.mediaUnavailableReason();if(e)throw this._streamConsumeUnavailableError(e)}_streamConsumeUnavailableError(e){return new Error(`[urun-sh/core] stream('${this._name}').messages(): token/named streams require WebRTC data channels (contract \xA75) and this session joined without WebRTC support \u2014 ${e}. This session is doc/KV-only (the media device was skipped); install the optional "werift" dependency to consume streams.`)}_ensureSubscribed(){this._subscribed||this._disposed||(this._subscribed=!0,this._streamData&&(this._dataUnsub=this._streamData.onData(this._name,e=>this._deliver(e))))}_deliver(e){this._replay.push(e);for(let t of this._messageConsumers)t.push(e)}get track(){let e=this._transport.getTrackByName(this._name)??this._track;return e!==this._track&&this._setTrack(e),this._overrideTrack??this._track}_setOverrideTrack(e){if(this._overrideTrack===e)return;this._overrideTrack=e,e&&e.addEventListener?.("ended",()=>{this._overrideTrack===e&&this._setOverrideTrack(null)},{once:!0});let t=e??this._transport.getTrackByName(this._name)??this._track,n=this._handlers.get("track");if(n)for(let s of n)s(t)}_claimBrowserProducer(e){if(!this._controlDoc)return;let t=this._controlDoc(),n=Um(t,this._name),s=n?.br;if(s?.by==="runtime")throw new St(this._name,"runtime","browser");if(s)return;let i={br:{epoch:1}};n?.rt&&(i.rt=n.rt);let o=n?.kind??e;o&&(i.kind=o),t.set({streams:{[this._name]:i}})}async attach(e){this._onActivity?.(),this._claimBrowserProducer("audio"),await this._transport.addTrack(e,this._name)}async attachVideo(e){this._onActivity?.(),this._claimBrowserProducer("video"),await this._transport.addVideoTrack(e,this._name)}async emit(e,t={}){if(this._onActivity?.(),this._claimBrowserProducer("data"),!this._streamData)throw new Error("[urun] stream.emit requires the data-stream transport (no streamData wired)");await this._streamData.sendData(this._name,e,t)}async detach(){this._transport.removeTrack()}async detachVideo(){this._transport.stopVideo()}async seek(e){if(e!=="live"&&(!Number.isFinite(e)||e<0))throw new Error('[urun] stream.seek target must be "live" or a non-negative number of seconds');this._transport.seekStream(this._name,e)}chunks(e={}){let t=e.source??vs;return Md(t,{track:()=>this.track,onTrack:s=>this.on("track",s)})}onSeeked(e){return this._transport.on("seeked",(t,n)=>{t===this._name&&e(n)})}on(e,t){let n=this._handlers.get(e);return n||(n=new Set,this._handlers.set(e,n)),n.add(t),()=>{n?.delete(t),n?.size===0&&this._handlers.delete(e)}}dispose(){this._disposed=!0,this._unsubscribeTransport?.(),this._unsubscribeTransport=null,this._handlers.clear(),this._dataUnsub?.(),this._dataUnsub=null;for(let e of this._messageConsumers)e.end();this._messageConsumers.clear()}_setTrack(e){if(this._track=e,e&&e.addEventListener("ended",()=>{this._track===e&&this._setTrack(null)},{once:!0}),this._overrideTrack)return;let t=this._handlers.get("track");if(t)for(let n of t)n(e)}},fr=class r{_sessionId;_multiplexer;_transport;_docs=new Map;_streams=new Map;_docConnector=new cs;_docEndpointKey=null;_streamData;_presence=null;_activity=null;_activityMode="auto";_presenceTracker=null;_activation;_activeRequests=new Set;_endHandler;_endPromise;_cancelHandler;_cancelPromise;_recordingsAuth;_artifactsAuth;_recordingsAccessor=null;_artifactsAccessor=null;_recoveryHooks=new Set;_disconnectHooks=new Set;_lifecycleUnsub=null;_dialNegotiation=null;_dialNegotiationStarted=!1;_generationTickHandlers=new Set;_generationTickStop=null;constructor(e,t,n,s,i,o){this._sessionId=e,this._multiplexer=t,this._transport=n,this._recordingsAuth=s,this._artifactsAuth=i,this._streamData=td(n),this._wireControlDocIncarnation(),this._lifecycleUnsub=ms(()=>this.recover()),this._activityMode=o?.activity??"auto",this._activity=fs({awareness:this.doc("control").awareness,isProducing:()=>this._transport.isProducingMedia===!0,mode:this._activityMode}),this._presenceTracker=new or({awareness:this.doc("control").awareness}),this._presenceTracker.attachTransport(this._transport),this._activation=new Ct({onPhase:a=>this.onPhase(a),hint:()=>this.doc(an).get(cn)??this.doc("control").get(dn),onData:(a,c)=>this._streamData.onData(a,c)})}_wireControlDocIncarnation(){let e=this.doc("control");this._transport.applyControlDocState(e.get()),e.on("change",t=>{this._transport.applyControlDocState(t)})}static async attach(e,t){let n=await Go({baseUrl:t.baseUrl,fallbackUrls:t.fallbackUrls,sessionId:e,orgId:t.orgId,jwt:t.jwt,getAccessToken:t.getAccessToken,authProvider:t.authProvider}),s=t.getAccessToken?await t.getAccessToken()??void 0:t.jwt,i=new wt,o=new ir({url:n.wsUrl,orgId:t.orgId,jwt:s,authProvider:t.authProvider,sessionId:e,iceServers:n.response.ice_servers}),a=new r(e,i,o,lo(t),Cr({...t,baseUrl:n.baseUrl}),{activity:t.activity});o.on("connected",()=>{o.multiplexer&&i.setTarget(o.multiplexer)}),o.setConnection({url:n.wsUrl,sessionId:e,iceServers:n.response.ice_servers}),o.setEndsAt(n.endsAt),tt()&&await tr();let c=t.getAccessToken,u=c?async()=>await c()??s:s;return a.setDocTransport({wsUrl:n.wsUrl,token:u}),await o.connect({role:"viewer"}),a}get id(){return this._sessionId}get phase(){return this._transport.phase}get endsAt(){return this._transport.endsAt}get status(){return this._transport.status}get region(){return this._transport.region}onPhase(e){return e(this._transport.phase),this._transport.on("phase",e)}onDiagnostic(e){return this._transport.on("diagnostic",e)}onActivation(e){return this._activation.onActivation(e)}onStats(e){return this._transport.on("stats",e)}whenLive(e){return on(this,e)}on(e,t){if(e!=="generationTick")throw new Error(`[urun] unknown session event ${String(e)}`);return this._generationTickHandlers.add(t),this._generationTickStop||(this._generationTickStop=ps(this.doc("control"),n=>{for(let s of Array.from(this._generationTickHandlers))try{s(n)}catch(i){console.warn("[urun] generationTick handler failed:",i)}})),()=>{this._generationTickHandlers.delete(t),this._generationTickHandlers.size===0&&(this._generationTickStop?.(),this._generationTickStop=null)}}get recordings(){if(this._recordingsAccessor)return this._recordingsAccessor;let e=this._recordingsAuth;if(!e)throw new Error("[urun] session.recordings requires `functionsUrl` to be configured on the App()/Session.attach() options (the eensx /functions/v1 base URL).");let t=new at(e);return this._recordingsAccessor={list:n=>t.list(n??this._sessionId),get:n=>t.get(n),retain:(n,s)=>t.retain(n,s),pin:n=>t.pin(n),unpin:n=>t.unpin(n),permanent:n=>t.permanent(n),delete:n=>t.delete(n)},this._recordingsAccessor}get artifacts(){return this._artifactsAccessor?this._artifactsAccessor:(this._requireArtifactsAuth(),this._artifactsAccessor={list:e=>new Je(this._requireArtifactsAuth()).list(e??this._sessionId),getDownloadUrl:(e,t)=>new Je(this._requireArtifactsAuth()).getDownloadUrl(e,t??this._sessionId)},this._artifactsAccessor)}setArtifactsAuth(e){this._artifactsAuth=e}_requireArtifactsAuth(){let e=this._artifactsAuth;if(!e)throw new Error("[urun] session.artifacts requires a session-api `baseUrl` auth bag.");return e}setSessionId(e){if(e===this._sessionId)return;this._multiplexer.rewriteSessionChannels?.call(this._multiplexer,this._sessionId,e),this._sessionId=e;for(let n of this._docs.values())n.setSessionId(e)}setEndHandler(e){this._endHandler=e}setCancelHandler(e){this._cancelHandler=e}stream(e){let t=this._streams.get(e);return t||(t=new uo(e,this._transport,this._streamData,()=>this.doc("control"),()=>{this._autoTouch(),this._activation.unwatch(e)}),this._streams.set(e,t),this._activation.watch(e,t)),t}doc(e){let t=this._docs.get(e);return t||(t=new ls(e,this._sessionId,Im.has(e)?null:this._docConnector.connect),this._docs.set(e,t)),t}get presence(){return this._presence||(this._presence=Cd(this.doc("control").awareness)),this._presence}touch(){this._activity?.touch()}_autoTouch(){this._activityMode!=="explicit"&&this._activity?.touch()}activity(){this._activity?.touch()}get presenceTracker(){return this._presenceTracker}connectDocs(e){this._docConnector.setTarget(e)}setDocTransport(e){let t=ds(e.wsUrl),n=typeof e.token=="function"?"<token-supplier>":e.token??"",s=`${t}\0${n}\0${this._sessionId}`;s!==this._docEndpointKey&&(this._docEndpointKey=s,this.connectDocs(Td({serverUrl:t,sessionId:this._sessionId,token:e.token,WebSocketPolyfill:e.webSocket,resolveServerUrl:e.resolveServerUrl})))}useStreamDataTransport(e){if(this._streams.size>0)throw new Error("[urun] useStreamDataTransport must be called before opening any stream");this._streamData=e}sendImage(e){return this.request({reference_image:{value:e}})}sendImageLegacyDesired(e){this.doc("control").set({desired:{reference_image:{value:e}}})}request(e,t={}){let n=co(),s=new AbortController;t.signal&&(t.signal.aborted?s.abort(t.signal.reason):t.signal.addEventListener("abort",()=>s.abort(t.signal.reason),{once:!0}));let i=null;if(typeof t.timeout=="number"&&t.timeout>=0){let c=t.timeout;i=setTimeout(()=>s.abort(new yt(c,n)),c)}let o=this._consumeResponse(n,e,!1,s.signal);o.start();let a=this._presenceTracker?.workBegin();return o.body.finally(()=>{i&&clearTimeout(i),a?.()})}_consumeResponse(e,t,n,s,i){this._autoTouch(),this._presenceTracker?.consumerRead();let o=this.doc(xm),a=Lm(e);return Om(o,e,t,a,this._streamData.consumerId,n,()=>this.stream(a),s,c=>(this._activeRequests.add(c),()=>this._activeRequests.delete(c)),i??po)}requestStream(e,t={}){let n=co();return this._consumeResponse(n,e,!0,t.signal,t.docSyncTimeout).deltas}complete(e,t={}){let n=co(),s=this._consumeResponse(n,e,!1,t.signal,t.docSyncTimeout);return s.start(),s.body}recover(){this._transport.recover();for(let e of this._docs.values())e.ensureConnected();for(let e of Array.from(this._recoveryHooks))try{e()}catch(t){console.warn("[urun] session recovery hook failed:",t)}}onRecovery(e){return this._recoveryHooks.add(e),()=>this._recoveryHooks.delete(e)}onDisconnect(e){return this._disconnectHooks.add(e),()=>this._disconnectHooks.delete(e)}negotiateMediaTransport(e={}){this._dialNegotiationStarted||(this._dialNegotiationStarted=!0,this._dialNegotiation=jd(this._transport,this._sessionId,{allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback,onOverrideTrack:t=>this.stream("video")._setOverrideTrack(t),onOverrideAudioTrack:t=>this.stream("audio")._setOverrideTrack(t),audioPlayout:this._transport.audioPlayoutOptions,audioUplink:this._transport.wtMicUplinkSeam,videoUplink:this._transport.wtCamUplinkSeam,dataUplink:this._transport.wtDataUplinkSeam}))}get mediaTransport(){return this._dialNegotiation?.activeTransport()??null}end(){return this._endPromise?this._endPromise:this._endHandler?(this._endPromise=this._endHandler().then(e=>(this.detach(e.status==="paused"?e.reason:void 0),e),e=>{throw this.disconnect(),e}),this._endPromise):Promise.reject(new Ae)}cancel(){if(this._cancelPromise)return this._cancelPromise;if(!this._cancelHandler)return Promise.reject(new Ae);let e=this._cancelHandler().then(t=>(this.disconnect(),t));return this._cancelPromise=e,e.catch(()=>{this._cancelPromise===e&&(this._cancelPromise=void 0)}),e}disconnect(){this.detach()}detach(e){let t=Array.from(this._disconnectHooks);this._disconnectHooks.clear();for(let s of t)try{s()}catch{}this._lifecycleUnsub?.(),this._lifecycleUnsub=null,this._dialNegotiation?.dispose(),this._dialNegotiation=null,this._activity?.dispose(),this._activity=null,this._presenceTracker?.dispose(),this._presenceTracker=null,this._activation.dispose(),this._generationTickStop?.(),this._generationTickStop=null,this._generationTickHandlers.clear(),this._recoveryHooks.clear();let n=Array.from(this._activeRequests);this._activeRequests.clear();for(let s of n)try{s(new Tt)}catch{}for(let s of this._docs.values())s.dispose();this._docs.clear();for(let s of this._streams.values())s.dispose();this._streams.clear(),this._transport.disconnect(e)}};function Bd(r){return`urun:session:v2:${r.orgId}:${r.app}:${r.functionName}`}function ho(){try{return globalThis.sessionStorage??null}catch{return null}}function fo(r){let e=ho();if(!e)return null;try{let t=e.getItem(r);if(!t)return null;let n=JSON.parse(t);return typeof n?.sessionId!="string"||n.sessionId.length===0?null:{sessionId:n.sessionId}}catch{return null}}function mo(r,e){let t=ho();if(t)try{t.setItem(r,JSON.stringify({sessionId:e.sessionId}))}catch{}}function Ps(r){let e=ho();if(e)try{e.removeItem(r)}catch{}}var Hd=new Set(["paused","acquiring","live"]),Nm=new Set(["24h","keep"]);function Vd(r){if(typeof r!="string"||r.length===0)return null;let e=new Date(r);return Number.isFinite(e.getTime())?e:null}function Fm(r){if(typeof r?.id!="string"||r.id.length===0)throw new _e("[urun] session list returned a row with no id \u2014 the control plane and this SDK disagree on the response shape",{code:"invalid_list_row"});if(typeof r.state!="string"||!Hd.has(r.state))throw new _e(`[urun] session ${r.id} reported an unrecognized state ${JSON.stringify(r.state)} \u2014 this @urun-sh/core build knows only ${[...Hd].join(", ")}. The SDK may be out of date for this control plane. NOTE: there is no terminal session state; a word like "closed" or "ended" arriving here is a server-side bug.`,{code:"unknown_session_state"});let e=!1;return typeof r.recordings_expired=="boolean"?e=r.recordings_expired:console.warn(`[urun] session ${r.id} list row has no recordings_expired (or a non-boolean value) \u2014 this control plane predates it; treating the session as not-expired`),{id:r.id,label:typeof r.label=="string"&&r.label.length>0?r.label:null,state:r.state,app:typeof r.app=="string"?r.app:"",functionName:typeof r.function=="string"?r.function:"",createdAt:Vd(r.created_at),lastActiveAt:Vd(r.last_active_at),archived:r.archived===!0,preview:typeof r.preview=="string"&&r.preview.length>0?r.preview:null,recordingsExpired:e,retention:Nm.has(r.retention)?r.retention:(r.retention!==void 0&&console.warn(`[urun] session ${r.id} reported an unrecognized retention ${JSON.stringify(r.retention)} \u2014 defaulting to '24h'`),"24h")}}var mr=class{_request;_app;constructor(e,t){this._app=e,this._request=t}async list(e={}){let{rows:t,nextCursor:n}=await Vo({...this._request,app:e.app??this._app,functionName:e.functionName,includeArchived:e.includeArchived,limit:e.limit,cursor:e.cursor});return{sessions:t.map(Fm),nextCursor:n}}async end(e){await zo({...this._request,sessionId:e})}async archive(e){await Fs({...this._request,sessionId:e,archived:!0})}async unarchive(e){await Fs({...this._request,sessionId:e,archived:!1})}};var Wm=new Set(["then","catch","finally","toJSON",Symbol.toPrimitive]);function zd(r,e){return new mr(r,{baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,orgId:e.orgId,jwt:e.jwt,getAccessToken:e.getAccessToken,authProvider:e.authProvider})}function Gd(r,e){if(typeof e.orgId!="string"||e.orgId.trim().length===0)throw new Error("[urun] App() requires a non-empty orgId \u2014 pass your org id (e.g. from a NEXT_PUBLIC_* deployment env var, threaded through <UrunProvider orgId>). It is sent as the X-Tenant-Id header on every request and selects the JWKS your JWT is verified against.");return new Proxy({},{get(t,n){if(!(Wm.has(n)||typeof n!="string"))return(s,i)=>{let o=s??{},a=Bd({orgId:e.orgId,app:r,functionName:n}),c=!i?.sessionId&&!e.sessionKey&&!!i?.label,u,d=()=>`s_${Date.now()}_${Math.random().toString(36).slice(2)}`,l=d(),p=e.jwt,f=e.getAccessToken?async R=>{let x=await e.getAccessToken(R);return x&&(p=x),x}:void 0,h={...e,getAccessToken:f},m=new wt,g=new ir({url:"",orgId:e.orgId,jwt:e.jwt,authProvider:e.authProvider,sessionId:l,audioPlayout:e.audioPlayout,videoPlayout:e.videoPlayout,sessionStats:e.sessionStats,diagnosticSink:e.diagnosticSink}),_=new fr(l,m,g,lo(h),Cr(h),{activity:i?.activity}),v,y=!1,S=!1,w,b,L=new Promise(R=>{b=R}),q,W=R=>{let x=R.sessionId?"session":"ticket";w&&!(w==="teardown"&&q==="ticket"&&x==="session")||(w="teardown",q=x,kr({baseUrl:R.baseUrl,requestId:R.requestId,...R.sessionId?{sessionId:R.sessionId}:{},orgId:e.orgId,jwt:p,authProvider:e.authProvider}))},B=R=>{w||(w="abandon",kr({baseUrl:R.baseUrl,requestId:R.requestId,...R.sessionId?{sessionId:R.sessionId}:{},orgId:e.orgId,jwt:p,authProvider:e.authProvider,...R.sessionId?{}:{reason:"client_abandoned"}}))},ee=R=>{let x=R.sessionId||!u?R:{...R,sessionId:u};v=x,b({status:"ready",handle:x}),(S||w==="teardown")&&W(x)};_.setEndHandler(async()=>{let R=v?{status:"ready",handle:v}:await L;if(R.status==="unavailable")throw new Ae("[urun] session allocation failed before a releasable request was created",{cause:R.cause});let x=v??R.handle;return Ps(a),w==="teardown"?x.sessionId?{status:"paused",sessionId:x.sessionId,reason:"client_ended"}:{status:"canceled",requestId:x.requestId}:(w="end",x.sessionId?Us({baseUrl:x.baseUrl,sessionId:x.sessionId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}):Os({baseUrl:x.baseUrl,requestId:x.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider}))}),_.setCancelHandler(async()=>{let R=v?{status:"ready",handle:v}:await L;if(R.status==="unavailable")throw new Ae("[urun] session allocation failed before a cancellable request was created",{cause:R.cause});let x=v??R.handle;if(x.sessionId)throw new ne(`[urun] cancel() is for a queued admission request, but this call already has session ${x.sessionId} \u2014 use end() to park a live session (it releases the compute and the session stays listed and attachable)`,{sessionId:x.sessionId,code:"cancel_on_live_session"});w="end";try{let F=await Os({baseUrl:x.baseUrl,requestId:x.requestId,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider});return Ps(a),F}catch(F){throw w==="end"&&(w=void 0),F}});let re=async R=>{let x,F=i?.sessionId??e.sessionKey??u,K=F===void 0&&!c?fo(a)?.sessionId:void 0,M=F??K,N=(le,Ge)=>Ho({baseUrl:e.baseUrl,fallbackUrls:e.fallbackUrls,app:r,functionName:n,orgId:e.orgId,jwt:e.jwt,getAccessToken:f,authProvider:e.authProvider,idempotencyKey:le,sessionKey:Ge,label:i?.label,priority:e.priority,onAdmission:Ke=>{g.reportAdmission(Ke),Ke.sessionId&&!u&&(u=Ke.sessionId,x=Ke.sessionId,v&&v.sessionId!==Ke.sessionId&&ee({...v,sessionId:Ke.sessionId}),y||(e.sessionKey||mo(a,{sessionId:Ke.sessionId}),_.setSessionId(Ke.sessionId)))},onRequest:ee}),U;try{U=await N(R,M)}catch(le){if(K===void 0||!(le instanceof H)||le.code!=="session_name_not_yours")throw le;fo(a)?.sessionId===K&&Ps(a),U=await N(d(),void 0)}let O=f?await f()??void 0:e.jwt;if(x&&x!==U.sessionId)throw v&&v.sessionId!==U.sessionId&&ee({...v,sessionId:U.sessionId}),new H(`Gateway contract violation: admission minted session ${x} but allocation completed as ${U.sessionId} \u2014 the same durable object must carry the same id from admission through allocation.`,{code:"admission_session_id_mismatch"});return u=U.sessionId,v&&v.sessionId!==U.sessionId&&ee({...v,sessionId:U.sessionId}),y||(e.sessionKey||mo(a,{sessionId:U.sessionId}),_.setSessionId(U.sessionId),_.setArtifactsAuth(Cr({...h,baseUrl:U.baseUrl})),g.setEndsAt(U.endsAt),g.seedRegion(Ws(U.response))),{url:U.wsUrl,sessionId:U.sessionId,jwt:O,iceServers:U.response.ice_servers,endsAt:U.endsAt}},ge,xe=f?async()=>await f()??ge:()=>ge,je=()=>{let R=g.connectedUrl;return R?ds(R):void 0};if(g.setConnectionResolver(async()=>{let R=await re(d());return ge=R.jwt,R}),g.on("connected",()=>{g.multiplexer&&m.setTarget(g.multiplexer);let R=g.connectedUrl;R&&_.setDocTransport({wsUrl:R,token:xe,resolveServerUrl:je})}),(async R=>{let x;try{x=await re(R)}catch(F){if(y){b({status:"unavailable",cause:F});return}console.error(`[urun] Failed to create session for ${n}:`,F),v&&B(v);let K=F instanceof Error?F:new Error(String(F)),M=F instanceof H?F.httpStatus:void 0,N=F instanceof H?F.code:void 0,U=F instanceof H?F.retryAfterSeconds:void 0;g.reportAllocationFailure(K,M,N,U),b({status:"unavailable",cause:F});return}y||(g.setAuth({jwt:x.jwt,authProvider:e.authProvider,orgId:e.orgId}),g.setConnection({url:x.url,sessionId:x.sessionId,iceServers:x.iceServers}),tt()&&await tr(),ge=x.jwt,_.setDocTransport({wsUrl:x.url,token:xe,resolveServerUrl:je}),await g.connect({app:r,functionName:n,args:o}),_.negotiateMediaTransport({allowWebTransport:e.allowWebTransport,allowWebRtcFallback:e.allowWebRtcFallback}))})(l).catch(R=>{console.error(`[urun] Failed to connect session for ${n}:`,R)}),e.releaseOnLeave!==!1){let R=gs(()=>{if(y=!0,g.leaveLeg())return;if(g.connectedUrl!==null){g.disconnect();return}g.disconnect();let N=v;N?W(N):S=!0});_.onDisconnect(R);let x,F,K=!1,M=()=>{K||(K=!0,x?.(),F?.())};L.then(N=>{N.status!=="ready"||K||(x=_s(()=>v!==void 0))}),F=_.onPhase(N=>{let U=N?.name;(U==="paused"||U==="error")&&M()}),K&&F(),_.onDisconnect(M)}return _}}})}var go="https://api.urun.sh",_o="URUN_DEV";function jm(){if(typeof process>"u")return!1;let r=process.env?.[_o];if(typeof r!="string")return!1;let e=r.trim().toLowerCase();return e==="1"||e==="true"}var rt=class extends Error{status;constructor(e,t){super(e),this.name="ClientTokenError",this.status=t}};async function Kd(r,e={}){if(!r)throw new rt("[urun] createClientToken requires an org API key");let t=e.fetch??globalThis.fetch,n=Y(e.baseUrl??go),s={};e.expiresIn!==void 0&&(s.expires_in=e.expiresIn),e.allowedFunctions!==void 0&&(s.allowed_functions=e.allowedFunctions),e.allowedOrigins!==void 0&&(s.allowed_origins=e.allowedOrigins),e.maxSessionS!==void 0&&(s.max_session_s=e.maxSessionS),e.subject!==void 0&&(s.subject=e.subject),e.metadata!==void 0&&(s.metadata=e.metadata),(e.dev??jm())&&(s.dev=!0);let i;try{i=await t(`${n}/api/client-tokens`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${r}`},body:JSON.stringify(s)})}catch(p){throw new rt(`[urun] client token mint request failed: ${p instanceof Error?p.message:String(p)}`)}let o={};try{o=await i.json()}catch{}if(!i.ok){let p=typeof o.message=="string"?o.message:`HTTP ${i.status}`;throw new rt(`[urun] client token mint failed: ${p}`,i.status)}let a=typeof o.token=="string"?o.token:"",c=typeof o.org_id=="string"?o.org_id:"",u=typeof o.expires_at=="string"?Date.parse(o.expires_at):Number.NaN,d=typeof o.expires_in=="number"?o.expires_in:void 0;if(!a)throw new rt("[urun] client token mint returned no token (control-plane contract violation)",i.status);let l=Number.isFinite(u)?new Date(u):new Date(Date.now()+(d??60)*1e3);return{token:a,expiresAt:l,orgId:c}}var Yd=3e4,Qd="stream:",vo=class{_ws;_multiplexer;_pendingRpc=new Map;_rpcId=0;constructor(e,t){this._ws=e,this._multiplexer=t,this._ws.addEventListener("message",n=>{let s;try{s=JSON.parse(typeof n.data=="string"?n.data:"")}catch{return}if(s.rpcId&&this._pendingRpc.has(s.rpcId)){let i=this._pendingRpc.get(s.rpcId);this._pendingRpc.delete(s.rpcId),clearTimeout(i.timer),s.error?i.reject(new Error(s.error)):i.resolve(s.result)}})}async get(e){return this._sendRpc("store.get",{key:e})}async has(e){return await this._sendRpc("store.has",{key:e})}on(e,t){let n=`${Qd}${e}`;return this._multiplexer.on(n,s=>{t(s)})}emit(e,t){let n=`${Qd}${e}`,s=typeof t=="object"&&t!==null&&!Array.isArray(t)?t:{data:t};this._multiplexer.emit(n,s)}_getInternals(){return{multiplexer:this._multiplexer,ws:this._ws}}_sendRpc(e,t){return new Promise((n,s)=>{if(!this._ws||this._ws.readyState!==WebSocket.OPEN){s(new Error("WebSocket not open"));return}let i=String(++this._rpcId),o=setTimeout(()=>{this._pendingRpc.has(i)&&(this._pendingRpc.delete(i),s(new Error(`RPC request "${e}" timed out after ${Yd}ms`)))},Yd);this._pendingRpc.set(i,{resolve:n,reject:s,timer:o}),this._ws.send(JSON.stringify({rpcId:i,type:e,...t}))})}};function Jd(r){let n=`${r.baseUrl.replace(/\/$/,"").replace(/^http/,"ws")}/store/${encodeURIComponent(r.orgId)}`,s=new WebSocket(n);(r.jwt||r.apiKey)&&s.addEventListener("open",()=>{s.send(JSON.stringify({type:"auth",orgId:r.orgId,jwt:r.jwt,authProvider:r.authProvider,apiKey:r.apiKey}))});let i=new vt(s);return new vo(s,i)}var qm='video/mp4; codecs="avc1.42E01E"';function Xd(r,e){let t=e?.codec??qm,n=document.createElement("video");n.muted=!0,n.playsInline=!0;let s=new MediaSource,i=URL.createObjectURL(s);n.src=i,s.addEventListener("sourceopen",()=>{let p;try{p=s.addSourceBuffer(t)}catch(g){throw g instanceof DOMException&&g.name==="NotSupportedError"?new Error(`Codec not supported: "${t}". Ensure the codec string matches the fMP4 container format. Common values: video/mp4; codecs="avc1.42E01E" (H.264 Baseline), video/mp4; codecs="avc1.4D401F" (H.264 Main).`):g}let f=r.getReader();function h(){return p.updating?new Promise(g=>{p.addEventListener("updateend",()=>g(),{once:!0})}):Promise.resolve()}async function m(){try{for(;;){let{done:g,value:_}=await f.read();if(g){await h(),s.readyState==="open"&&s.endOfStream();return}await h();try{p.appendBuffer(_)}catch(v){if(v instanceof DOMException&&v.name==="QuotaExceededError"){let y=p.buffered;if(y.length>0){let S=y.start(y.length-1);p.remove(0,S),await h(),p.appendBuffer(_)}else throw v}else throw v}}}catch{if(s.readyState==="open")try{s.endOfStream("decode")}catch{}}}m()}),n.play().catch(()=>{});let o=n,a=o.captureStream??o.mozCaptureStream;if(!a)throw new Error("captureStream() is not supported in this browser. videoStream() requires HTMLMediaElement.captureStream() support.");let c=a.call(n),u=c.getTracks(),d=0,l=u.length;if(l===0)n.addEventListener("emptied",()=>{URL.revokeObjectURL(i)},{once:!0});else for(let p of u)p.addEventListener("ended",()=>{d++,d>=l&&URL.revokeObjectURL(i)});return c}function Zd(r){return r.status.startsWith("pending_")}var _t=class extends Error{status;code;constructor(e,t){super(e),this.name="CreditsError",this.status=t.status,this.code=t.code,t.cause!==void 0&&(this.cause=t.cause),Object.setPrototypeOf(this,new.target.prototype)}},gr=class extends _t{constructor(e="[urun] credits: unauthorized",t="unauthorized"){super(e,{status:401,code:t}),this.name="CreditsUnauthorizedError",Object.setPrototypeOf(this,new.target.prototype)}};function $m(r,e,t){let n=t||e||`HTTP ${r}`;return r===401?new gr(n,e??"unauthorized"):new _t(n,{status:r,code:e??`http_${r}`})}var en=class{constructor(e){this._options=e;this._base=`${e.functionsUrl.replace(/\/+$/,"")}/credits`}_options;_base;async getBalance(){let e=await this._request("GET","/balance");if(!e||typeof e!="object"||typeof e.org_id!="string")throw new _t("[urun] credits: balance response missing org_id",{status:0,code:"bad_response"});return e}async getLedger(e={}){let n=(await this._request("GET","/ledger",{params:e.limit!==void 0?{limit:String(e.limit)}:void 0})).entries;return Array.isArray(n)?n:[]}async _request(e,t,n={}){let s=this._buildUrl(t,n.params),i=await this._resolveToken(),o=await this._fetch(s,e,i);if(o.status===401&&this._options.getAccessToken){let a=await this._options.getAccessToken({forceRefresh:!0,reason:"unauthorized"});a&&a!==i&&(i=a,o=await this._fetch(s,e,i))}if(!o.ok){let{code:a,message:c}=await this._readError(o);throw $m(o.status,a,c)}return this._readJson(o)}_buildUrl(e,t){let n=`${this._base}${e}`,s=Object.entries(t??{}).filter(([,i])=>i!=null&&i!=="").map(([i,o])=>`${encodeURIComponent(i)}=${encodeURIComponent(o)}`).join("&");return s&&(n+=`?${s}`),n}_fetch(e,t,n){let s={Authorization:`Bearer ${n}`,apikey:n,Accept:"application/json","X-Tenant-Id":this._options.orgId};return this._options.authProvider&&(s["X-Auth-Provider"]=this._options.authProvider),fetch(e,{method:t,headers:s})}async _resolveToken(){if(this._options.getAccessToken){let t=await this._options.getAccessToken();if(t)return t}let e=this._options.jwt??this._options.apiKey;if(!e)throw new gr("[urun] credits: no credential \u2014 provide one of apiKey, jwt, or getAccessToken");return e}async _readJson(e){try{return await e.json()}catch{return{}}}async _readError(e){try{let n=(await e.json()).error;if(n&&typeof n=="object"){let{code:s,message:i}=n;return{code:typeof s=="string"?s:void 0,message:typeof i=="string"?i:`HTTP ${e.status}`}}}catch{}return{message:`HTTP ${e.status}`}}};function eu(r){return new en(r)}var tn=class extends Error{constructor(){super("no getUserMedia in this environment \u2014 in headless/Node consumers, inject a media source via new CaptureController({ getUserMedia }) (e.g. a wrtc/werift capture)"),this.name="CaptureUnavailableError",Object.setPrototypeOf(this,new.target.prototype)}};function tu(r){let e=[];return r.audio&&e.push("audio"),r.video&&e.push("video"),e.join("+")}function Bm(r,e){return e==="audio"?r.getAudioTracks():r.getVideoTracks()}function Hm(r,e){let t=r.getTracks();if(t.length===1&&t[0]===e)return r;try{return new MediaStream([e])}catch{return r}}function wo(r,e){for(let t of[...r.lostListeners])try{t(e)}catch{}}var rn=class{claims=new Map;injectedGetUserMedia;queue=Promise.resolve();constructor(e){this.injectedGetUserMedia=e?.getUserMedia}claim(e,t){return this.enqueue(async()=>{let n=this.claims.get(e);n&&(this.claims.delete(e),n.released=!0,n.track=null,n.stream=null,wo(n,new Error(`${e} capture claim superseded by a newer claim`)));let s=this.createState(e,t);return this.claims.set(e,s),await this.converge(s),s.claim})}idle(){return this.queue.then(()=>{})}enqueue(e){let t=this.queue.then(e);return this.queue=t.then(()=>{},()=>{}),t}resolveGetUserMedia(){if(this.injectedGetUserMedia)return this.injectedGetUserMedia;let e=typeof navigator<"u"?navigator.mediaDevices:void 0;if(!e?.getUserMedia)throw new tn;return t=>e.getUserMedia(t)}async converge(e){for(let o of this.claims.values())o.track&&(o.track.stop(),o.track=null,o.stream=null);if(this.claims.size===0)return;let t=this.resolveGetUserMedia(),n={audio:this.claims.get("audio")?.constraints??!1,video:this.claims.get("video")?.constraints??!1},s;try{s=await t(n)}catch(o){let a=`one-capture getUserMedia(${tu(n)}) failed`,c=o instanceof Error?o.message:String(o);for(let u of[...this.claims.values()])if(this.claims.delete(u.kind),u.released=!0,u!==e){let d=new Error(`${a} \u2014 ${u.kind} capture lost: ${c||o}`);d.cause=o,wo(u,d)}throw o}let i=[...this.claims.values()].sort((o,a)=>o===e?1:a===e?-1:0);for(let o of i){let a=Bm(s,o.kind)[0]??null;if(o.released){a?.stop();continue}if(!a){this.claims.delete(o.kind),o.released=!0;let c=Object.assign(new Error(`one-capture getUserMedia(${tu(n)}) returned no ${o.kind} track`),{name:"NotFoundError"});if(o===e)throw c;wo(o,c);continue}if(o.track=a,o.stream=Hm(s,a),o!==e)for(let c of[...o.trackListeners])try{c(a,o.stream)}catch{}}}createState(e,t){let n=this,s={kind:e,constraints:t,track:null,stream:null,released:!1,trackListeners:new Set,lostListeners:new Set,claim:{kind:e,get track(){return s.track},get stream(){return s.stream},update(i){return n.enqueue(async()=>{if(s.released)throw new Error(`${e} capture claim already released`);if(s.constraints=i,await n.converge(s),!s.track)throw new Error(`${e} capture update yielded no track`);return s.track})},release(){s.released||(s.released=!0,n.claims.get(e)===s&&n.claims.delete(e),s.track?.stop(),s.track=null,s.stream=null)},onTrack(i){return s.trackListeners.add(i),()=>s.trackListeners.delete(i)},onLost(i){return s.lostListeners.add(i),()=>s.lostListeners.delete(i)}}};return s}},Vm=null;function ru(){return Vm??=new rn}var yo="input",nu=30;function su(r){let e=r.now??Date.now,t=r.field??yo,n=1e3/Math.max(r.hz??30,.001),s=new Set,i=0,o=0,a=0,c=0,u,d=null,l=!1,p=()=>{if(l)return;u=e(),c+=1;let h={keys:[...s],buttons:i,pointer:{x:o,y:a},seq:c,at:u};try{r.awareness.setLocalStateField(t,h)}catch{}},f=()=>{if(l)return;let h=e();if(u===void 0||h-u>=n){d&&(clearTimeout(d),d=null),p();return}if(d)return;let m=Math.max(n-(h-u),0);d=setTimeout(()=>{d=null,p()},m),d.unref?.()};return{keyDown(h){let m=String(h).toLowerCase();s.has(m)||(s.add(m),f())},keyUp(h){let m=String(h).toLowerCase();s.delete(m)&&f()},setButtons(h){let m=Number.isFinite(h)?Number(h):0;m!==i&&(i=m,f())},movePointer(h,m){let g=Number.isFinite(h)?Number(h):0,_=Number.isFinite(m)?Number(m):0;g===0&&_===0||(o+=g,a+=_,f())},heldKeys(){return[...s]},clear(){l||(s.clear(),i=0,d&&(clearTimeout(d),d=null),p())},dispose(){if(l)return;let h=s.size>0||i!==0;s.clear(),i=0,d&&(clearTimeout(d),d=null),h&&p(),l=!0}}}var au=1024,cu=.92,du=262144,uu=256e3,bo=[.9,.8,.7,.6,.5],iu=.8,zm=8;function Ds(r,e,t){if(!(r>0)||!(e>0))throw new Error(`reference image has no pixels (${r}x${e})`);let n=Math.min(1,t/Math.max(r,e));return{width:Math.max(1,Math.round(r*n)),height:Math.max(1,Math.round(e*n))}}async function Gm(r){if(typeof createImageBitmap!="function")throw new Error("this browser cannot decode images for reference capture (createImageBitmap unavailable)");return await createImageBitmap(r,{imageOrientation:"from-image"})}async function lu(r,e,t){let n=await new Promise(s=>{r.toBlob(s,e,e==="image/jpeg"?t:void 0)});if(!n)throw new Error(`could not encode the reference image as ${e}`);return n}function ou(r,e){console.warn(`[urun] reference image over the 256000-byte data-channel message budget (media/Chrome maxMessageSize 262144 would drop it SILENTLY): ${r} -> ${e} bytes`)}async function So(r,e,t,n,s){let i=document.createElement("canvas");i.width=e,i.height=t;let o=i.getContext("2d");if(!o)throw new Error("could not prepare the reference image (no 2d canvas context)");return n==="image/jpeg"&&(o.fillStyle="#fff",o.fillRect(0,0,e,t)),o.drawImage(r,0,0,e,t),await lu(i,n,s)}async function Km(r,e,t,n){let{width:s,height:i}=e,o=await So(r,s,i,t,n);if(o.size<=256e3)return{blob:o,width:s,height:i};if(t==="image/jpeg"){for(let c of bo)if(!(c>=n)&&(o=await So(r,s,i,t,c),o.size<=256e3))return ou(`quality ${n} -> ${c}`,o.size),{blob:o,width:s,height:i}}let a=t==="image/jpeg"?bo[bo.length-1]:n;for(let c=0;c<zm;c++)if(s=Math.max(16,Math.round(s*iu)),i=Math.max(16,Math.round(i*iu)),o=await So(r,s,i,t,a),o.size<=256e3)return ou(`downscaled to ${s}x${i} @ q${a}`,o.size),{blob:o,width:s,height:i};throw new Error(`this image cannot be sent: even at ${s}x${i} it is over the 256000-byte limit for one message. Try a smaller or less detailed picture.`)}async function pu(r,e){let{maxSize:t=1024,type:n="image/jpeg",quality:s=.92,source:i}=e,o=await Gm(r);try{let a=Ds(o.width,o.height,t),c=await Km(o,a,n,s);return{bytes:new Uint8Array(await c.blob.arrayBuffer()),type:n,width:c.width,height:c.height,source:i}}finally{o.close()}}function hu(r){let e=r instanceof Error?r.name:"",t=r instanceof Error?r.message:String(r);switch(e){case"NotAllowedError":case"SecurityError":return"Camera access is turned off for this site. Allow the camera in your browser settings, then try again.";case"NotFoundError":case"OverconstrainedError":return"No camera was found on this device. You can upload a photo instead.";case"NotReadableError":case"AbortError":return"The camera is being used by another app. Close it, then try again.";default:break}return/has not shown a frame/i.test(t)?"The camera is still starting. Wait for the picture to appear, then take the photo.":/secure|https/i.test(t)?"The camera only works over a secure (https) connection.":/decode|not settled|createImageBitmap|encode|image/i.test(t)?"That file couldn't be read as an image. Try a JPEG or PNG photo.":"The camera couldn't be started. Check that no other app is using it, then try again."}function fu(){return typeof navigator>"u"||typeof window>"u"||!window.isSecureContext?!1:typeof navigator.mediaDevices?.getUserMedia=="function"}async function mu(r,e){let t=r.videoWidth,n=r.videoHeight;if(!(t>0)||!(n>0))throw new Error("the camera has not shown a frame yet");let{maxSize:s=1024,type:i="image/jpeg",quality:o=.92}=e??{},a=Ds(t,n,s),c=document.createElement("canvas");c.width=a.width,c.height=a.height;let u=c.getContext("2d");if(!u)throw new Error("could not prepare the reference image (no 2d canvas context)");i==="image/jpeg"&&(u.fillStyle="#fff",u.fillRect(0,0,a.width,a.height)),u.drawImage(r,0,0,a.width,a.height);let d=await lu(c,i,o);return{bytes:new Uint8Array(await d.arrayBuffer()),type:i,width:a.width,height:a.height,source:"camera"}}var Ym=new Set(["w","a","s","d"]),_r=(r,e)=>Math.min(e,Math.max(-e,r));function gu(r={}){let{panPerPixel:e=9e-4,zoomPerSecond:t=.35,strafePerSecond:n=.18,decayTauMs:s=900,frameRelax:i=.06,maxPan:o=.12,maxLogZoom:a=.22}=r,c=0,u=0,d=0,l=null,p=new Set;return{pointerDelta(f,h){c=_r(c-f*e,o),u=_r(u-h*e,o)},keyDown(f){let h=f.toLowerCase();Ym.has(h)&&p.add(h)},keyUp(f){p.delete(f.toLowerCase())},clearKeys(){p.clear()},frameArrived(){let f=1-i;c*=f,u*=f,d*=f},tick(f){if(l===null){l=f;return}let h=Math.max(0,Math.min(100,f-l))/1e3;l=f,p.has("w")&&(d=_r(d+t*h,a)),p.has("s")&&(d=_r(d-t*h,a)),p.has("a")&&(c=_r(c+n*h,o)),p.has("d")&&(c=_r(c-n*h,o));let m=Math.exp(-h*1e3/s);c*=m,u*=m,d*=m},transform(){return{translateX:c,translateY:u,scale:Math.exp(d)}},isIdentity(f=5e-4){return Math.abs(c)<f&&Math.abs(u)<f&&Math.abs(d)<f},reset(){c=0,u=0,d=0,p.clear()}}}0&&(module.exports={ACTIVATION_COLD_BOOT_AFTER_MS,ACTIVATION_DEGRADED_AFTER_MS,ACTIVATION_HINT_PATH,ACTIVATION_STILL_AFTER_MS,ACTIVITY_DOM_EVENTS,ACTIVITY_FIELD,ACTIVITY_STAMP_MIN_INTERVAL_MS,ActivationMonitor,App,BACKOFF_BASE_MS,BACKOFF_MAX_ATTEMPTS,BACKOFF_MAX_MS,CaptureController,CaptureUnavailableError,ClientTokenError,CreditsClient,CreditsError,CreditsUnauthorizedError,DATA_CHANNEL_MESSAGE_CEILING,DEFAULT_DOC_SYNC_TIMEOUT_MS,DEFAULT_GATEWAY_URL,DEFAULT_PRODUCE_ACK_TIMEOUT_MS,DEFAULT_REFERENCE_JPEG_QUALITY,DEFAULT_REFERENCE_MAX_SIZE,DEFAULT_WHEN_LIVE_TIMEOUT_MS,DERIVED_LEG_SEP,DGRAM_HEADER_BYTES,FOCUS_FIELD,FOREGROUND_COALESCE_MS,FrameReassembler,GENERATION_TICK_EMIT_INTERVAL_MS,GENERATION_TICK_MAX_EXTRAPOLATION_MS,INPUT_PRESENCE_DEFAULT_HZ,INPUT_PRESENCE_FIELD,InvalidDurationError,LEGACY_ACTIVATION_HINT_PATH,PLATFORM_DOC_NAME,PermanentLockedError,PinRequiresActiveTempError,PresenceTracker,ProduceAckTimeoutError,RecordingNotFoundError,RecordingsClient,RecordingsError,RecordingsUnauthorizedError,RequestAbortError,RequestCancelledError,RequestDocSyncError,RequestError,RequestTimeoutError,RetainNotTempError,RuntimeArtifactNotFoundError,RuntimeArtifactsClient,RuntimeArtifactsError,RuntimeArtifactsUnauthorizedError,SIGNALING_PROTOCOL_VERSION,STREAM_END,Session,SessionAllocationError,SessionDirectory,SessionDirectoryError,SessionEndError,SessionEndUnavailableError,SessionFailedError,StreamDirectionConflict,TransportNegotiator,TransportSessionMismatchError,TransportSessionSignaling,URUN_DEV_ENV,USER_ACTIVITY_FIELD,USER_ACTIVITY_MIN_INTERVAL_MS,VISIBILITY_FIELD,WIRE_MESSAGE_BUDGET,WT_CONTROL_FRAME_MAX,WT_DATA_STREAM_VERSION,WebRtcSession,WebTransportSession,WtControlDecoder,WtDataStreamParser,activationHintFrom,cameraCaptureAvailable,captureStillFromVideo,computeBackoffDelay,consumeWtDataStreams,createActivityTracker,createCameraWarp,createClientToken,createCreditsClient,createInputPresencePublisher,createRecordingsClient,createRuntimeArtifactsClient,createStore,decodeStreamEnvelope,derivedLegName,derivedLegRole,describeSessionFailure,describeSessionPhase,encodeStreamEnvelope,encodeWtControlFrame,fitWithin,isDurationString,isPausedPhase,isPendingRecording,isRetryableSessionError,isWakingPhase,mediaRecorderChunkSource,normalizeReferenceImage,normalizeRetention,observeLeaveConfirm,observePageLifecycle,observePageTeardown,parseDgramHeader,prewake,referenceImageErrorMessage,releaseSessionBeacon,sessionDirectory,sessionFailureFromMediaError,sharedCaptureController,videoStream,watchGenerationTick,whenLive,writeDgramHeader});
|