PageSourceSearch

https://www.0101labs.ai/_next/static/chunks/2704-e73924b0517d3eaa.js

js 0101labs.ai collected 2026-10-04 05:28:43 UTC 58,261 bytes, 1 lines download raw bytes

1"use strict";(self.webpackChunk_N_E=self.webpackChunk_N_E||[]).push([[2704],{60429:e=>{var t,n="object"==typeof Reflect?Reflect:null,s=n&&"function"==typeof n.apply?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};t=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function r(){r.init.call(this)}e.exports=r,e.exports.once=function(e,t){return new Promise(function(n,s){var i;function r(n){e.removeListener(t,o),s(n)}function o(){"function"==typeof e.removeListener&&e.removeListener("error",r),n([].slice.call(arguments))}m(e,t,o,{once:!0}),"error"!==t&&(i={once:!0},"function"==typeof e.on&&m(e,"error",r,i))})},r.EventEmitter=r,r.prototype._events=void 0,r.prototype._eventsCount=0,r.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?r.defaultMaxListeners:e._maxListeners}function u(e,t,n,s){if(a(n),void 0===(r=e._events)?(r=e._events=Object.create(null),e._eventsCount=0):(void 0!==r.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),r=e._events),o=r[t]),void 0===o)o=r[t]=n,++e._eventsCount;else if("function"==typeof o?o=r[t]=s?[n,o]:[o,n]:s?o.unshift(n):o.push(n),(i=c(e))>0&&o.length>i&&!o.warned){o.warned=!0;var i,r,o,u=Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");u.name="MaxListenersExceededWarning",u.emitter=e,u.type=t,u.count=o.length,console&&console.warn&&console.warn(u)}return e}function l(){if(!this.fired)return(this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0==arguments.length)?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var s={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=l.bind(s);return i.listener=n,s.wrapFn=i,i}function h(e,t,n){var s=e._events;if(void 0===s)return[];var i=s[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):f(i,i.length)}function p(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function f(e,t){for(var n=Array(t),s=0;s<t;++s)n[s]=e[s];return n}function m(e,t,n,s){if("function"==typeof e.on)s.once?e.once(t,n):e.on(t,n);else if("function"==typeof e.addEventListener)e.addEventListener(t,function i(r){s.once&&e.removeEventListener(t,i),n(r)});else throw TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e)}Object.defineProperty(r,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||i(e))throw RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),r.init=function(){(void 0===this._events||this._events===Object.getPrototypeOf(this)._events)&&(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},r.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},r.prototype.getMaxListeners=function(){return c(this)},r.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,r=this._events;if(void 0!==r)i=i&&void 0===r.error;else if(!i)return!1;if(i){if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var o,a=Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=r[e];if(void 0===c)return!1;if("function"==typeof c)s(c,this,t);else for(var u=c.length,l=f(c,u),n=0;n<u;++n)s(l[n],this,t);return!0},r.prototype.addListener=function(e,t){return u(this,e,t,!1)},r.prototype.on=r.prototype.addListener,r.prototype.prependListener=function(e,t){return u(this,e,t,!0)},r.prototype.once=function(e,t){return a(t),this.on(e,d(this,e,t)),this},r.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,d(this,e,t)),this},r.prototype.removeListener=function(e,t){var n,s,i,r,o;
1if(a(t),void 0===(s=this._events)||void 0===(n=s[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,r=n.length-1;r>=0;r--)if(n[r]===t||n[r].listener===t){o=n[r].listener,i=r;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(s[e]=n[0]),void 0!==s.removeListener&&this.emit("removeListener",e,o||t)}return this},r.prototype.off=r.prototype.removeListener,r.prototype.removeAllListeners=function(e){var t,n,s;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0==arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0==arguments.length){var i,r=Object.keys(n);for(s=0;s<r.length;++s)"removeListener"!==(i=r[s])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(s=t.length-1;s>=0;s--)this.removeListener(e,t[s]);return this},r.prototype.listeners=function(e){return h(this,e,!0)},r.prototype.rawListeners=function(e){return h(this,e,!1)},r.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):p.call(e,t)},r.prototype.listenerCount=p,r.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},67401:(e,t,n)=>{n.d(t,{A:()=>d});var s=n(12115);let i=e=>e.replace(/([a-z0-9])([A-Z])/g,"$1-$2").toLowerCase(),r=e=>e.replace(/^([A-Z])|[\s-_]+(\w)/g,(e,t,n)=>n?n.toUpperCase():t.toLowerCase()),o=e=>{let t=r(e);return t.charAt(0).toUpperCase()+t.slice(1)},a=function(){for(var e=arguments.length,t=Array(e),n=0;n<e;n++)t[n]=arguments[n];return t.filter((e,t,n)=>!!e&&""!==e.trim()&&n.indexOf(e)===t).join(" ").trim()},c=e=>{for(let t in e)if(t.startsWith("aria-")||"role"===t||"title"===t)return!0};var u={xmlns:"http://www.w3.org/2000/svg",width:24,height:24,viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round",strokeLinejoin:"round"};let l=(0,s.forwardRef)((e,t)=>{let{color:n="currentColor",size:i=24,strokeWidth:r=2,absoluteStrokeWidth:o,className:l="",children:d,iconNode:h,...p}=e;return(0,s.createElement)("svg",{ref:t,...u,width:i,height:i,stroke:n,strokeWidth:o?24*Number(r)/Number(i):r,className:a("lucide",l),...!d&&!c(p)&&{"aria-hidden":"true"},...p},[...h.map(e=>{let[t,n]=e;return(0,s.createElement)(t,n)}),...Array.isArray(d)?d:[d]])}),d=(e,t)=>{let n=(0,s.forwardRef)((n,r)=>{let{className:c,...u}=n;return(0,s.createElement)(l,{ref:r,iconNode:t,className:a("lucide-".concat(i(o(e))),"lucide-".concat(e),c),...u})});return n.displayName=o(e),n}},87364:(e,t,n)=>{n.d(t,{A:()=>s});let s=(0,n(67401).A)("arrow-left",[["path",{d:"m12 19-7-7 7-7",key:"1l729n"}],["path",{d:"M19 12H5",key:"x3x0zl"}]])},66889:(e,t,n)=>{n.d(t,{A:()=>s});let s=(0,n(67401).A)("clock",[["path",{d:"M12 6v6l4 2",key:"mmk7yg"}],["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}]])},48617:(e,t,n)=>{n.d(t,{A:()=>s});let s=(0,n(67401).A)("info",[["circle",{cx:"12",cy:"12",r:"10",key:"1mglay"}],["path",{d:"M12 16v-4",key:"1dtifu"}],["path",{d:"M12 8h.01",key:"e9boi3"}]])},63348:(e,t,n)=>{n.d(t,{A:()=>s});let s=(0,n(67401).A)("message-square",[["path",{d:"M22 17a2 2 0 0 1-2 2H6.828a2 2 0 0 0-1.414.586l-2.202 2.202A.71.71 0 0 1 2 21.286V5a2 2 0 0 1 2-2h16a2 2 0 0 1 2 2z",key:"18887p"}]])},7156:(e,t,n)=>{n.d(t,{A:()=>s});let s=(0,n(67401).A)("mic-off",[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M15 9.34V5a3 3 0 0 0-5.68-1.33",key:"1gzdoj"}],["path",{d:"M16.95 16.95A7 7 0 0 1 5 12v-2",key:"cqa7eg"}],["path",{d:"M18.89 13.23A7 7 0 0 0 19 12v-2",key:"16hl24"}],["path",{d:"m2 2 20 20",key:"1ooewy"}],["path",{d:"M9 9v3a3 3 0 0 0 5.12 2.12",key:"r2i35w"}]])},26164:(e,t,n)=>{n.d(t,{A:()=>s});let s=(0,n(67401).A)("mic",[["path",{d:"M12 19v3",key:"npa21l"}],["path",{d:"M19 10v2a7 7 0 0 1-14 0v-2",key:"1vc78b"}],["rect",{x:"9",y:"2",width:"6",height:"13",rx:"3",key:"s6n7sd"}]])},73519:(e,t,n)=>{n.d(t,{A:()=>s});let s=(0,n(67401).A)("phone-off",[["path",{d:"M10.1 13.9a14 14 0 0 0 3.732 2.668 1 1 0 0 0 1.213-.303l.355-.465A2 2 
10 0 1 17 15h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2 18 18 0 0 1-12.728-5.272",key:"1wngk7"}],["path",{d:"M22 2 2 22",key:"y4kqgn"}],["path",{d:"M4.76 13.582A18 18 0 0 1 2 4a2 2 0 0 1 2-2h3a2 2 0 0 1 2 2v3a2 2 0 0 1-.8 1.6l-.468.351a1 1 0 0 0-.292 1.233 14 14 0 0 0 .244.473",key:"10hv5p"}]])},28283:(e,t,n)=>{n.d(t,{A:()=>s});let s=(0,n(67401).A)("send",[["path",{d:"M14.536 21.686a.5.5 0 0 0 .937-.024l6.5-19a.496.496 0 0 0-.635-.635l-19 6.5a.5.5 0 0 0-.024.937l7.93 3.18a2 2 0 0 1 1.112 1.11z",key:"1ffxy3"}],["path",{d:"m21.854 2.147-10.94 10.939",key:"12cjpa"}]])},40767:(e,t,n)=>{n.d(t,{A:()=>s});let s=(0,n(67401).A)("x",[["path",{d:"M18 6 6 18",key:"1bl5f8"}],["path",{d:"m6 6 12 12",key:"d8bk6v"}]])},76046:(e,t,n)=>{var s=n(66658);n.o(s,"useParams")&&n.d(t,{useParams:function(){return s.useParams}}),n.o(s,"usePathname")&&n.d(t,{usePathname:function(){return s.usePathname}}),n.o(s,"useRouter")&&n.d(t,{useRouter:function(){return s.useRouter}}),n.o(s,"useSearchParams")&&n.d(t,{useSearchParams:function(){return s.useSearchParams}})},66231:(e,t,n)=>{n.d(t,{Oz:()=>c,_N:()=>p,i5:()=>es,b9:()=>a,Yj:()=>l,hm:()=>f,y4:()=>m});var s,i,r,o,a,c,u,l,d,h,p,f,m,v=n(87648),S=n(60429);function g(){}function y(){y.init.call(this)}function k(e){return void 0===e._maxListeners?y.defaultMaxListeners:e._maxListeners}function _(e,t,n,s){var i,r,o;if("function"!=typeof n)throw TypeError('"listener" argument must be a function');if((r=e._events)?(r.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),r=e._events),o=r[t]):(r=e._events=new g,e._eventsCount=0),o){if("function"==typeof o?o=r[t]=s?[n,o]:[o,n]:s?o.unshift(n):o.push(n),!o.warned&&(i=k(e))&&i>0&&o.length>i){o.warned=!0;var a=Error("Possible EventEmitter memory leak detected. "+o.length+" "+t+" listeners added. Use emitter.setMaxListeners() to increase limit");a.name="MaxListenersExceededWarning",a.emitter=e,a.type=t,a.count=o.length,"function"==typeof console.warn?console.warn(a):console.log(a)}}else o=r[t]=n,++e._eventsCount;return e}function E(e,t,n){var s=!1;function i(){e.removeListener(t,i),s||(s=!0,n.apply(e,arguments))}return i.listener=n,i}function T(e){var t=this._events;if(t){var n=t[e];if("function"==typeof n)return 1;if(n)return n.length}return 0}function C(e,t){for(var n=Array(t);t--;)n[t]=e[t];return n}g.prototype=Object.create(null),y.EventEmitter=y,y.usingDomains=!1,y.prototype.domain=void 0,y.prototype._events=void 0,y.prototype._maxListeners=void 0,y.defaultMaxListeners=10,y.init=function(){this.domain=null,y.usingDomains&&(void 0).active,this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=new g,this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},y.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||isNaN(e))throw TypeError('"n" argument must be a positive number');return this._maxListeners=e,this},y.prototype.getMaxListeners=function(){return k(this)},y.prototype.emit=function(e){var t,n,s,i,r,o,a,c="error"===e;if(o=this._events)c=c&&null==o.error;else if(!c)return!1;if(a=this.domain,c){if(t=arguments[1],!a){if(t instanceof Error)throw t;var u=Error('Uncaught, unspecified "error" event. ('+t+")");throw u.context=t,u}return t||(t=Error('Uncaught, unspecified "error" event')),t.domainEmitter=this,t.domain=a,t.domainThrown=!1,a.emit("error",t),!1}if(!(n=o[e]))return!1;var l="function"==typeof n;switch(s=arguments.length){case 1:(function(e,t,n){if(t)e.call(n);else for(var s=e.length,i=C(e,s),r=0;r<s;++r)i[r].call(n)})(n,l,this);break;case 2:(function(e,t,n,s){if(t)e.call(n,s);else for(var i=e.length,r=C(e,i),o=0;o<i;++o)r[o].call(n,s)})(n,l,this,arguments[1]);break;case 3:(function(e,t,n,s,i){if(t)e.call(n,s,i);else for(var r=e.length,o=C(e,r),a=0;a<r;++a)o[a].call(n,s,i)})(n,l,this,arguments[1],arguments[2]);break;case 4:(function(e,t,n,s,i,r){if(t)e.call(n,s,i,r);else for(var o=e.length,a=C(e,o),c=0;c<o;++c)a[c].call(n,s,i,r)})(n,l,this,arguments[1],arguments[2],arguments[3]);break;default:for(i=Array(s-1),r=1;r<s;r++)i[r-1]=arguments[r];(function(e,t,n,s){if(t)e.apply(n,s);else for(var i=e.length,r=C(e,i),o=0;o<i;++o)r[o].apply(n,s)})(n,l,this,i)}return!0},y.prototype.addListener=function(e,t){return _(this,e,t,!1)},y.prototype.on=y.prototype.addListener,y.prototype.prependListener=function(e,t){return _(this,e,t,!0)},y.prototype.once=function(e,t){if("function"!=typeof t)throw TypeError('"listener" argument must be a function');return this.on(e,E(this,e,t)),this},y.prototype.prependOnceListener=function(e,t){if("function"!=typeof t)throw TypeError('"listener" argument must be a function');return this.prependListener(e,E(this,e,t)),this},y.prototype.removeListener=function(e,t){var n,s,i,r,o;
1if("function"!=typeof t)throw TypeError('"listener" argument must be a function');if(!(s=this._events)||!(n=s[e]))return this;if(n===t||n.listener&&n.listener===t)0==--this._eventsCount?this._events=new g:(delete s[e],s.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,r=n.length;r-- >0;)if(n[r]===t||n[r].listener&&n[r].listener===t){o=n[r].listener,i=r;break}if(i<0)return this;if(1===n.length){if(n[0]=void 0,0==--this._eventsCount)return this._events=new g,this;delete s[e]}else!function(e,t){for(var n=t,s=n+1,i=e.length;s<i;n+=1,s+=1)e[n]=e[s];e.pop()}(n,i);s.removeListener&&this.emit("removeListener",e,o||t)}return this},y.prototype.off=function(e,t){return this.removeListener(e,t)},y.prototype.removeAllListeners=function(e){var t,n;if(!(n=this._events))return this;if(!n.removeListener)return 0==arguments.length?(this._events=new g,this._eventsCount=0):n[e]&&(0==--this._eventsCount?this._events=new g:delete n[e]),this;if(0==arguments.length){for(var s,i=Object.keys(n),r=0;r<i.length;++r)"removeListener"!==(s=i[r])&&this.removeAllListeners(s);return this.removeAllListeners("removeListener"),this._events=new g,this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(t)do this.removeListener(e,t[t.length-1]);while(t[0]);return this},y.prototype.listeners=function(e){var t,n=this._events;return n&&(t=n[e])?"function"==typeof t?[t.listener||t]:function(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(t):[]},y.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):T.call(e,t)},y.prototype.listenerCount=T,y.prototype.eventNames=function(){return this._eventsCount>0?Reflect.ownKeys(this._events):[]};class A extends y{}!function(e){e.Issue="issue",e.NetworkScoresUpdated="network-scores-updated",e.StatsParsingFinished="stats-parsing-finished"}(s||(s={})),function(e){e.Network="network",e.CPU="cpu",e.Server="server",e.Stream="stream"}(i||(i={})),function(e){e.OutboundNetworkQuality="outbound-network-quality",e.InboundNetworkQuality="inbound-network-quality",e.OutboundNetworkMediaLatency="outbound-network-media-latency",e.InboundNetworkMediaLatency="inbound-network-media-latency",e.NetworkMediaSyncFailure="network-media-sync-failure",e.OutboundNetworkThroughput="outbound-network-throughput",e.InboundNetworkThroughput="inbound-network-throughput",e.EncoderCPUThrottling="encoder-cpu-throttling",e.DecoderCPUThrottling="decoder-cpu-throttling",e.ServerIssue="server-issue",e.UnknownVideoDecoderIssue="unknown-video-decoder",e.LowInboundMOS="low-inbound-mean-opinion-score",e.LowOutboundMOS="low-outbound-mean-opinion-score",e.FrozenVideoTrack="frozen-video-track",e.MissingVideoStreamData="missing-video-stream-data",e.MissingAudioStreamData="missing-audio-stream-data"}(r||(r={})),function(e){e[e.BAD=2.1]="BAD",e[e.POOR=2.6]="POOR",e[e.FAIR=3.1]="FAIR",e[e.GOOD=3.8]="GOOD",e[e.EXCELLENT=4.3]="EXCELLENT"}(o||(o={}));class N extends y{static STATS_REPORT_READY_EVENT="stats-report-ready";static STATS_REPORTS_PARSED="stats-reports-parsed";isStopped=!1;reportTimer;getStatsInterval;compositeStatsParser;constructor(e){super(),this.compositeStatsParser=e.compositeStatsParser,this.getStatsInterval=e.getStatsInterval??1e4}get isRunning(){return!!this.reportTimer&&!this.isStopped}startReporting(){if(this.reportTimer)return;let e=()=>setTimeout(()=>{this.isStopped?this.reportTimer=void 0:this.parseReports().finally(()=>{this.reportTimer=e()})},this.getStatsInterval);this.isStopped=!1,this.reportTimer=e()}stopReporting(){this.isStopped=!0,this.reportTimer&&(clearTimeout(this.reportTimer),this.reportTimer=void 0)}async parseReports(){let e=Date.now(),t=await this.compositeStatsParser.parse(),n=Date.now()-e;this.emit(N.STATS_REPORTS_PARSED,{timeTaken:n,reportItems:t}),t.forEach(e=>{this.emit(N.STATS_REPORT_READY_EVENT,e)})}}let w=(()=>{let e=new Map;return t=>{let{taskId:n,delayMs:s,maxJitterMs:i,callback:r}=t,o=Math.ceil(Math.random()*(i||0)),a=e.get(n);a&&clearTimeout(a);let c=setTimeout(()=>{r(),e.delete(n)},s+o);e.set(n,c)}})();class b{#e={};
1calculate(e){let{connection:{id:t}}=e,{mos:n,stats:s}=this.calculateOutboundScore(e)||{},{mos:i,stats:r}=this.calculateInboundScore(e)||{};return this.#e[t]=e,w({taskId:t,delayMs:35e3,callback:()=>delete this.#e[t]}),{outbound:n,inbound:i,connectionId:t,statsSamples:{inboundStatsSample:r,outboundStatsSample:s}}}calculateOutboundScore(e){let t=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!t.length)return;let n=this.#e[e.connection.id];if(!n)return;let s=[...n.remote?.audio.inbound||[],...n.remote?.video.inbound||[]],{packetsSent:i}=e.connection,r=n.connection.packetsSent,o=t.reduce((e,t)=>{let n=s.find(e=>e.ssrc===t.ssrc);return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(n?.packetsLost||0)}},{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,u=c/t.length,l=i-r,d=o.packetsLost-o.lastPacketsLost,h=l&&d?Math.round(100*d/(l+d)):0;return{mos:this.calculateMOS({avgJitter:u,rtt:a,packetsLoss:h}),stats:{avgJitter:u,rtt:a,packetsLoss:h}}}calculateInboundScore(e){let t=[...e.audio?.inbound,...e.video?.inbound];if(!t.length)return;let n=this.#e[e.connection.id];if(!n)return;let s=[...n.video?.inbound,...n.audio?.inbound],{packetsReceived:i}=e.connection,r=n.connection.packetsReceived,o=t.reduce((e,t)=>{let n=s.find(e=>e.ssrc===t.ssrc);return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(n?.packetsLost||0)}},{sumJitter:0,packetsLost:0,lastPacketsLost:0}),a=1e3*e.connection.currentRoundTripTime||0,{sumJitter:c}=o,u=c/t.length,l=i-r,d=o.packetsLost-o.lastPacketsLost,h=l&&d?Math.round(100*d/(l+d)):0;return{mos:this.calculateMOS({avgJitter:u,rtt:a,packetsLoss:h}),stats:{avgJitter:u,rtt:a,packetsLoss:h}}}calculateMOS({avgJitter:e,rtt:t,packetsLoss:n}){let s=t+2*e+10,i=s<160?93.2-s/40:93.2-s/120-10;return 1+.035*(i-=2.5*n)+7e-6*i*(i-60)*(100-i)}}class I{#t=new Map;#n;#s;constructor(e={}){this.#n=e.statsCleanupTtlMs??35e3,this.#s=e.maxParsedStatsStorageSize??5}detect(e,t){let n={...e,networkScores:{...t,statsSamples:t?.statsSamples||{}}},s=this.performDetection(n);return this.setLastProcessedStats(e.connection.id,n),this.performPrevStatsCleanup({connectionId:e.connection.id}),s}performPrevStatsCleanup(e){let{connectionId:t,cleanupCallback:n}=e;this.#t.has(t)&&w({taskId:t,delayMs:this.#n,callback:()=>{this.deleteLastProcessedStats(t),"function"==typeof n&&n()}})}setLastProcessedStats(e,t){if(!e||t.connection.id!==e)return;let n=this.#t.get(e)??[];n.push(t),n.length>this.#s&&n.shift(),this.#t.set(e,n)}getLastProcessedStats(e){let t=this.#t.get(e);return t?.[t.length-1]}getAllLastProcessedStats(e){return this.#t.get(e)??[]}deleteLastProcessedStats(e){this.#t.delete(e)}}class P extends I{#i;constructor(e={}){super(e),this.#i=e.availableOutgoingBitrateThreshold??1e5}performDetection(e){let t=[],{availableOutgoingBitrate:n}=e.connection;if(void 0===n)return t;let s=e.audio.outbound.reduce((e,t)=>e+t.targetBitrate,0),o=e.video.outbound.reduce((e,t)=>e+t.bitrate,0);return(s||o)&&(s>n||o>
10&&n<this.#i)&&t.push({statsSample:{availableOutgoingBitrate:n,videoStreamsTotalBitrate:o,audioStreamsTotalTargetBitrate:s},type:i.Network,reason:r.OutboundNetworkThroughput}),t}}class D extends I{#r;#o;#a;#c;constructor(e={}){super(),this.#r=e.highPacketLossThresholdPct??5,this.#o=e.highJitterThreshold??200,this.#a=e.highJitterBufferDelayThresholdMs??500,this.#c=e.highRttThresholdMs??250}performDetection(e){return this.processData(e)}processData(e){let t=[],n=[...e.audio?.inbound,...e.video?.inbound];if(!n.length)return t;let s=this.getLastProcessedStats(e.connection.id);if(!s)return t;let o=[...s.video?.inbound,...s.audio?.inbound],{packetsReceived:a}=e.connection,c=s.connection.packetsReceived,u=n.reduce((e,t)=>{let n=o.find(e=>e.ssrc===t.ssrc),s=n?.jitterBufferDelay||0,i=n?.jitterBufferEmittedCount||0,r=t.jitterBufferDelay-s,a=t.jitterBufferEmittedCount-i;return{sumJitter:e.sumJitter+t.jitter,sumJitterBufferDelayMs:e.sumJitterBufferDelayMs+(r&&a?1e3*r/a:0),packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(n?.packetsLost||0)}},{sumJitter:0,sumJitterBufferDelayMs:0,packetsLost:0,lastPacketsLost:0}),l=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d,sumJitterBufferDelayMs:h}=u,p=d/n.length,f=h/n.length,m=a-c,v=u.packetsLost-u.lastPacketsLost,S=m&&v?Math.round(100*v/(m+v)):0,g=S>this.#r,y=p>=this.#o,k=l>=this.#c,_=f>this.#a,E={rtt:l,packetLossPct:S,avgJitter:p,avgJitterBufferDelay:f};return(y||g)&&t.push({statsSample:E,type:i.Network,reason:r.InboundNetworkQuality,iceCandidate:e.connection.local.id}),!k||y||g||t.push({statsSample:E,type:i.Server,reason:r.ServerIssue,iceCandidate:e.connection.remote.id}),g&&y&&t.push({statsSample:E,type:i.Network,reason:r.InboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),y&&_&&t.push({statsSample:E,type:i.Network,reason:r.NetworkMediaSyncFailure,iceCandidate:e.connection.local.id}),t}}class R extends I{#u;constructor(e={}){super(),this.#u=e.correctedSamplesThresholdPct??5}performDetection(e){return this.processData(e)}processData(e){let t=e.audio.inbound,n=[],s=this.getLastProcessedStats(e.connection.id)?.audio.inbound;return s&&t.forEach(e=>{let t=s.find(t=>t.ssrc===e.ssrc);if(!t)return;let o=e.track.insertedSamplesForDeceleration+e.track.removedSamplesForAcceleration,a=t.track.insertedSamplesForDeceleration+t.track.removedSamplesForAcceleration;if(o===a)return;let c=Math.round(100*(o-a)/(e.track.totalSamplesReceived-t.track.totalSamplesReceived));c>this.#u&&n.push({statsSample:{correctedSamplesPct:c},type:i.Network,reason:r.NetworkMediaSyncFailure,ssrc:e.ssrc})}),n}}class L extends I{#r;#o;constructor(e={}){super(),this.#r=e.highPacketLossThresholdPct??5,this.#o=e.highJitterThreshold??200}performDetection(e){return this.processData(e)}processData(e){let t=[],n=[...e.remote?.audio.inbound||[],...e.remote?.video.inbound||[]];if(!n.length)return t;let s=this.getLastProcessedStats(e.connection.id);if(!s)return t;let o=[...s.remote?.audio.inbound||[],...s.remote?.video.inbound||[]],{packetsSent:a}=e.connection,c=s.connection.packetsSent,u=n.reduce((e,t)=>{let n=o.find(e=>e.ssrc===t.ssrc);return{sumJitter:e.sumJitter+t.jitter,packetsLost:e.packetsLost+t.packetsLost,lastPacketsLost:e.lastPacketsLost+(n?.packetsLost||0)}},{sumJitter:0,packetsLost:0,lastPacketsLost:0}),l=1e3*e.connection.currentRoundTripTime||0,{sumJitter:d}=u,h=d/n.length,p=a-c,f=u.packetsLost-u.lastPacketsLost,m=p&&f?Math.round(100*f/(p+f)):0,v=m>this.#r,S=h>=this.#o,g={rtt:l,avgJitter:h,packetLossPct:m};return v&&S&&t.push({statsSample:g,type:i.Network,reason:r.OutboundNetworkMediaLatency,iceCandidate:e.connection.local.id}),(!v&&S||S||v)&&t.push({statsSample:g,type:i.Network,reason:r.OutboundNetworkQuality,iceCandidate:e.connection.local.id}),t}}class O extends I{performDetection(e){return this.processData(e)}processData(e){let t=e.video.outbound.filter(e=>"none"!==e.qualityLimitationReason),n=[],s=this.getLastProcessedStats(e.connection.id)?.video.outbound;return s&&t.forEach(e=>{let t=s.find(t=>t.ssrc===e.ssrc);if(!t)return;let o={qualityLimitationReason:e.qualityLimitationReason};e.framesSent>t.framesSent||("cpu"===e.qualityLimitationReason&&n.push({statsSample:o,type:i.CPU,reason:r.EncoderCPUThrottling,ssrc:e.ssrc}),"bandwidth"===e.qualityLimitationReason&&n.push({statsSample:o,type:i.Network,reason:r.OutboundNetworkThroughput,ssrc:e.ssrc}))}),n}}class x extends I{UNKNOWN_DECODER="unknown";#l={};performDetection(e){return this.processData(e)}
1performPrevStatsCleanup(e){let{connectionId:t,cleanupCallback:n}=e;super.performPrevStatsCleanup({...e,cleanupCallback:()=>{delete this.#l[t],"function"==typeof n&&n()}})}processData(e){let t=[],{id:n}=e.connection,s=this.getLastProcessedStats(n)?.video.inbound;return e.video.inbound.forEach(e=>{let{decoderImplementation:o,ssrc:a}=e;if(s?.find(e=>e.ssrc===a)){if(o===this.UNKNOWN_DECODER){if(!this.hadLastDecoderWithIssue(n,a)){this.setLastDecoderWithIssue(n,a,this.UNKNOWN_DECODER);let s={mimeType:e.mimeType,decoderImplementation:o};t.push({ssrc:a,statsSample:s,type:i.Stream,reason:r.UnknownVideoDecoderIssue,trackIdentifier:e.track.trackIdentifier})}}else this.setLastDecoderWithIssue(n,a,void 0)}}),t}setLastDecoderWithIssue(e,t,n){let s=this.#l[e]??{};void 0===n?delete s[t]:s[t]=n,this.#l[e]=s}hadLastDecoderWithIssue(e,t){let n=this.#l[e];return(n&&n[t])===this.UNKNOWN_DECODER}}let M=e=>e.reduce((e,t)=>e+t,0)/e.length,U=(e,t,n=30)=>{let s=[];for(let n=1;n<t.length-1;n+=1){let i=t[n]?.video?.inbound.find(t=>t.ssrc===e);if(!i)continue;let r=t[n-1]?.video?.inbound?.find(t=>t.ssrc===e);if(!i||!r)continue;let o=i.timestamp-r.timestamp,a=i.framesDecoded-r.framesDecoded;if(a>0){let e=o/a;s.push(e)}}return!(s.length<=1)&&(e=>Math.sqrt(((e,t)=>t.reduce((t,n)=>t+(n-e)**2,0)/t.length)(M(e),e)))(s)>n},V=(e,t)=>{for(let n=1;n<t.length;n+=1){let s=t[n].video.inbound.find(t=>t.ssrc===e);if(!s)continue;let i=t[n-1].video.inbound.find(t=>t.ssrc===e),r=s.frameWidth!==i?.frameWidth,o=s.frameHeight!==i?.frameHeight;if(r||o)return!0}return!1};class W extends I{#d;#h;#p;constructor(e={}){super(),this.#d=e.avgFreezeDurationThresholdMs??1e3,this.#h=e.frozenDurationThresholdPct??30,this.#p=e.minMosQuality??o.BAD}performDetection(e){let t=e.networkScores.inbound;return void 0!==t&&t<=this.#p?[]:this.processData(e)}processData(e){let t=[],n=this.getAllLastProcessedStats(e.connection.id);if(0===n.length)return[];let s=e.video.inbound.map(t=>{let s=n[n.length-1].video.inbound.find(e=>e.ssrc===t.ssrc);if(!s||V(t.ssrc,[n[n.length-1],e])||U(t.ssrc,n))return;let i=t.freezeCount-(s.freezeCount??0),r=1e3*(t.totalFreezesDuration-(s.totalFreezesDuration??0)),o=i>0?r/i:0,a=r/(t.timestamp-s.timestamp)*100;return a>this.#h||o>this.#d?{ssrc:t.ssrc,avgFreezeDurationMs:o,frozenDurationPct:a}:void 0}).filter(e=>void 0!==e);return s.length>0&&(t.push({type:i.Stream,reason:r.FrozenVideoTrack,statsSample:{ssrcs:s.map(e=>e.ssrc)}}),this.deleteLastProcessedStats(e.connection.id)),t}}class K extends I{#f;#m;#p;constructor(e={}){super(e),this.#f=e.volatilityThreshold??8,this.#m=e.affectedStreamsPercentThreshold??30,this.#p=e.minMosQuality??o.BAD}performDetection(e){return[...this.getAllLastProcessedStats(e.connection.id),e].find(e=>void 0!==e.networkScores.inbound&&e.networkScores.inbound<=this.#p)?[]:this.processData(e)}processData(e){let t=[],n=[...this.getAllLastProcessedStats(e.connection.id),e],s=e.video.inbound.map(e=>{if(n.length<5||V(e.ssrc,n))return;let t=[];for(let s=0;s<n.length-1;s+=1){let i=n[s].video.inbound.find(t=>t.ssrc===e.ssrc);void 0!==i?.framesPerSecond&&t.push(i.framesPerSecond)}if(t.length<5||U(e.ssrc,n))return;let s=(e=>{if(0===e.length)throw Error("Cannot calculate volatility for empty array");let t=M(e);return e.reduce((e,n)=>e+Math.abs(n-t),0)/e.length*100/t})(t);return s>this.#f?{ssrc:e.ssrc,allFps:t,volatility:s}:void 0}).filter(e=>!!e);if(0===s.length)return t;let o=s.length/(e.video.inbound.length/100);return o>this.#m&&(t.push({type:i.CPU,reason:r.DecoderCPUThrottling,statsSample:{affectedStreamsPercent:o,throtthedStreams:s}}),this.deleteLastProcessedStats(e.connection.id)),t}}let j=e=>"closed"===e.iceConnectionState||"closed"===e.connectionState,J=(e,t,n)=>8*((e,t,n)=>{if(!t)return 0;let s=e[n],i=t[n];if(null==s||null==i)return 0;let r=Math.floor(e.timestamp)-Math.floor(t.timestamp);return 0===r?0:(Number(s)-Number(i))/r*1e3})(e,t,n);class Q{connections=[];statsParser;constructor(e){this.statsParser=e.statsParser}listConnections(){return[...this.connections]}addPeerConnection(e){this.connections.push({id:e.id??String(Date.now()+Math.random().toString(32)),pc:e.pc})}removePeerConnection(e){let t=this.connections.findIndex(({pc:t})=>t===e.pc);t>=0&&this.removeConnectionsByIndexes([t])}async parse(){let e=[],t=this.connections.map(async(t,n)=>{if(!j(t.pc))return this.statsParser.parse(t);e.unshift(n)});return e.length&&this.removeConnectionsByIndexes(e),(await Promise.all(t)).filter(e=>void 0!==e)}
1removeConnectionsByIndexes(e){e.forEach(e=>{this.connections.splice(e,1)})}}class B{prevStats=new Map;allowedReportTypes=new Set(["candidate-pair","inbound-rtp","outbound-rtp","remote-outbound-rtp","remote-inbound-rtp","track","transport"]);ignoreSSRCList;logger;constructor(e){this.ignoreSSRCList=e.ignoreSSRCList??[],this.logger=e.logger}get previouslyParsedStatsConnectionsIds(){return[...this.prevStats.keys()]}async parse(e){if(!j(e.pc))return this.getConnectionStats(e);this.logger.debug("Skip stats parsing. Connection is closed.",{connection:e})}async getConnectionStats(e){let{pc:t,id:n}=e;try{let s=Date.now(),i=t.getReceivers().filter(e=>e.track?.enabled),r=t.getSenders().filter(e=>e.track?.enabled),o=await Promise.all(i.map(e=>e.getStats())),a=await Promise.all(r.map(e=>e.getStats()));return{id:n,stats:this.mapReportsStats([...o,...a],e),timeTaken:Date.now()-s}}catch(e){return void this.logger.error("Failed to get stats for PC",{id:n,pc:t,error:e})}}mapReportsStats(e,t){let n={audio:{inbound:[],outbound:[]},video:{inbound:[],outbound:[]},connection:{},remote:{video:{inbound:[],outbound:[]},audio:{inbound:[],outbound:[]}}};e.forEach(e=>{e.forEach(t=>{this.allowedReportTypes.has(t.type)&&this.updateMappedStatsWithReportItemData(t,n,e)})});let{id:s}=t,i=this.prevStats.get(s);return i&&this.propagateStatsWithRateValues(n,i.stats),this.prevStats.set(s,{stats:n,ts:Date.now()}),w({taskId:s,delayMs:35e3,callback:()=>this.prevStats.delete(s)}),n}updateMappedStatsWithReportItemData(e,t,n){let s=e.type;if("candidate-pair"===s&&"succeeded"===e.state&&e.nominated)return void(t.connection=this.prepareConnectionStats(e,n));let i=this.getMediaType(e);if(!i)return;let r=e.ssrc;if(!r||!this.ignoreSSRCList.includes(r)){if("outbound-rtp"!==s){if("inbound-rtp"!==s)"remote-outbound-rtp"!==s?"remote-inbound-rtp"===s&&(this.mapConnectionStatsIfNecessary(t,e,n),t.remote[i].inbound.push({...e})):t.remote[i].outbound.push({...e});else{let s=n.get(e.trackId)||n.get(e.mediaSourceId)||{};this.mapConnectionStatsIfNecessary(t,e,n);let r={...e,track:{...s}};t[i].inbound.push(r)}}else{let s=n.get(e.trackId)||n.get(e.mediaSourceId)||{},r={...e,track:{...s}};t[i].outbound.push(r)}}}getMediaType(e){let t=e.mediaType||e.kind;if(!["audio","video"].includes(t)){let{id:t}=e;if(!t)return;return String(t).includes("Video")?"video":String(t).includes("Audio")?"audio":void 0}return t}propagateStatsWithRateValues(e,t){e.audio.inbound.forEach(e=>{let n=t.audio.inbound.find(({id:t})=>t===e.id);e.bitrate=J(e,n,"bytesReceived"),e.packetRate=J(e,n,"packetsReceived")}),e.audio.outbound.forEach(e=>{let n=t.audio.outbound.find(({id:t})=>t===e.id);e.bitrate=J(e,n,"bytesSent"),e.packetRate=J(e,n,"packetsSent")}),e.video.inbound.forEach(e=>{let n=t.video.inbound.find(({id:t})=>t===e.id);e.bitrate=J(e,n,"bytesReceived"),e.packetRate=J(e,n,"packetsReceived")}),e.video.outbound.forEach(e=>{let n=t.video.outbound.find(({id:t})=>t===e.id);e.bitrate=J(e,n,"bytesSent"),e.packetRate=J(e,n,"packetsSent")})}mapConnectionStatsIfNecessary(e,t,n){if(e.connection.id||!t.transportId)return;let s=n.get(t.transportId);if(s&&s.selectedCandidatePairId){let t=n.get(s.selectedCandidatePairId);e.connection=this.prepareConnectionStats(t,n)}}prepareConnectionStats(e,t){if(!e||!t)return{};let n={...e};if(n.remoteCandidateId){let e=t.get(n.remoteCandidateId);n.remote={...e}}if(n.localCandidateId){let e=t.get(n.localCandidateId);n.local={...e}}return n}}class G extends I{#v=new Map;#S;#g;constructor(e={}){super(),this.#S=e.timeoutMs??15e3,this.#g=e.steps??3}performDetection(e){return this.processData(e)}processData(e){let t=[],n=[...this.getAllLastProcessedStats(e.connection.id),e];if(n.length<this.#g)return t;let s=n.slice(-this.#g),o=s.map(e=>e.video.inbound),a=s.map(e=>e.audio.inbound);return t.push(...this.detectMissingData(a,i.Stream,r.MissingAudioStreamData)),t.push(...this.detectMissingData(o,i.Stream,r.MissingVideoStreamData)),new Set(this.#v.keys()).forEach(e=>{let t=this.#v.get(e);t&&Date.now()-t>this.#S&&this.removeMarkedIssue(e)}),t}detectMissingData(e,t,n){let s=[],i=e.pop(),r=G.mapStatsByTrackId(e);
1return i.forEach(e=>{let i=e.track.trackIdentifier,o=r.get(i);if(!Array.isArray(o)||0===o.length||e.track.detached||e.track.ended)return;if(!G.isAllBytesReceivedDidntChange(e.bytesReceived,o))return void this.removeMarkedIssue(i);if(!this.markIssue(i))return;let a={bytesReceived:e.bytesReceived};s.push({type:t,reason:n,statsSample:a,trackIdentifier:i})}),s}static mapStatsByTrackId(e){let t=new Map;return e.forEach(e=>{e.forEach(e=>{let n=t.get(e.track.trackIdentifier)||[];n.push(e),t.set(e.track.trackIdentifier,n)})}),t}static isAllBytesReceivedDidntChange(e,t){for(let n=0;n<t.length;n+=1)if(t[n].bytesReceived!==e)return!1;return!0}markIssue(e){let t=Date.now(),n=this.#v.get(e);return(!n||t-n>this.#S)&&(this.#v.set(e,t),!0)}removeMarkedIssue(e){this.#v.delete(e)}}class z{eventEmitter;#y=!1;detectors=[];networkScoresCalculator;statsReporter;compositeStatsParser;logger;autoAddPeerConnections;constructor(e){this.logger=e.logger??{debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}},this.eventEmitter=e.issueEmitter??new A,e.onIssues&&this.eventEmitter.on(s.Issue,e.onIssues),e.onNetworkScoresUpdated&&this.eventEmitter.on(s.NetworkScoresUpdated,e.onNetworkScoresUpdated),this.detectors=e.detectors??[new O,new D,new L,new R,new P,new x,new W,new K,new G],this.networkScoresCalculator=e.networkScoresCalculator??new b,this.compositeStatsParser=e.compositeStatsParser??new Q({statsParser:new B({ignoreSSRCList:e.ignoreSSRCList,logger:this.logger})}),this.statsReporter=e.statsReporter??new N({compositeStatsParser:this.compositeStatsParser,getStatsInterval:e.getStatsInterval??5e3}),window.wid=this,this.autoAddPeerConnections=e.autoAddPeerConnections??!0,this.autoAddPeerConnections&&this.wrapRTCPeerConnection(),this.statsReporter.on(N.STATS_REPORT_READY_EVENT,e=>{let t=this.calculateNetworkScores(e.stats);this.detectIssues({data:e.stats},t)}),this.statsReporter.on(N.STATS_REPORTS_PARSED,t=>{let n={timeTaken:t.timeTaken,ts:Date.now()};e.onStats&&e.onStats(t.reportItems),this.eventEmitter.emit(s.StatsParsingFinished,n)})}watchNewPeerConnections(){if(!this.autoAddPeerConnections)throw Error("Auto add peer connections was disabled in the constructor.");this.#y?this.logger.warn("WebRTCIssueDetector is already started. Skip processing"):(this.logger.info("Start watching peer connections"),this.#y=!0,this.statsReporter.startReporting())}stopWatchingNewPeerConnections(){this.#y?(this.logger.info("Stop watching peer connections"),this.#y=!1,this.statsReporter.stopReporting()):this.logger.warn("WebRTCIssueDetector is already stopped. Skip processing")}handleNewPeerConnection(e,t){this.#y||!this.autoAddPeerConnections?(this.#y||!1!==this.autoAddPeerConnections||(this.logger.info("Starting stats reporting for new peer connection"),this.#y=!0,this.statsReporter.startReporting()),this.logger.debug("Handling new peer connection",e),this.compositeStatsParser.addPeerConnection({pc:e,id:t})):this.logger.debug("Skip handling new peer connection. Detector is not running",e)}emitIssues(e){this.eventEmitter.emit(s.Issue,e)}detectIssues({data:e},t){let n=this.detectors.reduce((n,s)=>[...n,...s.detect(e,t)],[]);n.length>0&&this.emitIssues(n)}calculateNetworkScores(e){let t=this.networkScoresCalculator.calculate(e);return this.eventEmitter.emit(s.NetworkScoresUpdated,t),t}wrapRTCPeerConnection(){if(!window.RTCPeerConnection)return void this.logger.warn("No RTCPeerConnection found in browser window. Skipping");let e=window.RTCPeerConnection,t=e=>this.handleNewPeerConnection(e);function n(n){let s=new e(n);return t(s),s}n.prototype=e.prototype,window.RTCPeerConnection=n}}function F(e,t,n,s){return new(n||(n=Promise))(function(i,r){function o(e){try{c(s.next(e))}catch(e){r(e)}}function a(e){try{c(s.throw(e))}catch(e){r(e)}}function c(e){var t;e.done?i(e.value):((t=e.value)instanceof n?t:new n(function(e){e(t)})).then(o,a)}c((s=s.apply(e,t||[])).next())})}"function"==typeof SuppressedError&&SuppressedError,function(e){e.SESSION_STATE_CHANGED="session.state_changed",e.SESSION_STREAM_READY="session.stream_ready",e.SESSION_CONNECTION_QUALITY_CHANGED="session.connection_quality_changed",e.SESSION_DISCONNECTED="session.disconnected"}(a||(a={})),function(e){e.SESSION_UPDATED="session.updated",e.SESSION_STATE_UPDATED="session.state_updated",e.USER_SPEAK_STARTED="user.speak_started",e.USER_SPEAK_ENDED="user.speak_ended",e.USER_TRANSCRIPTION="user.transcription",e.AVATAR_TRANSCRIPTION="avatar.transcription",e.AVATAR_SPEAK_STARTED="avatar.speak_started",e.AVATAR_SPEAK_ENDED="avatar.speak_ended"}(c||(c={}));let q=e=>{if("event_type"in e)switch(e.event_type){case c.USER_SPEAK_STARTED:{let t={event_id:e.event_id,event_type:e.event_type};return[c.USER_SPEAK_STARTED,t]}case c.USER_SPEAK_ENDED:{let t={event_id:e.event_id,event_type:e.event_type};return[c.USER_SPEAK_ENDED,t]}case c.USER_TRANSCRIPTION:{let t={event_id:e.event_id,event_type:e.event_type,text:e.text};return[c.USER_TRANSCRIPTION,t]}case c.AVATAR_SPEAK_STARTED:{let t={event_id:e.event_id,event_type:e.event_type};return[c.AVATAR_SPEAK_STARTED,t]}case c.AVATAR_SPEAK_ENDED:{let t={event_id:e.event_id,event_type:e.event_type};return[c.AVATAR_SPEAK_ENDED,t]}case c.AVATAR_TRANSCRIPTION:{let t={event_id:e.event_id,event_type:e.event_type,text:e.text};return[c.AVATAR_TRANSCRIPTION,t]}default:console.warn("New unsupported event type")}return null};!function(e){e.SESSION_UPDATE="session.update",e.SESSION_STOP="session.stop",e.AVATAR_INTERRUPT="avatar.interrupt",e.AVATAR_SPEAK_TEXT="avatar.speak_text",e.AVATAR_SPEAK_RESPONSE="avatar.speak_response",e.AVATAR_SPEAK_AUDIO="avatar.speak_audio",e.AVATAR_START_LISTENING="avatar.start_listening",e.AVATAR_STOP_LISTENING="avatar.stop_listening"}(u||(u={})),function(e){e.INACTIVE="INACTIVE",e.CONNECTING="CONNECTING",e.CONNECTED="CONNECTED",e.DISCONNECTING="DISCONNECTING",e.DISCONNECTED="DISCONNECTED"}(l||(l={})),function(e){e.UNKNOWN_REASON="UNKNOWN_REASON",e.CLIENT_INITIATED="CLIENT_INITIATED",e.SESSION_START_FAILED="SESSION_START_FAILED"}(d||(d={})),function(e){e.af="af",e.sq="sq",e.am="am",e.ar="ar",e.hy="hy",e.as="as",e.ast="ast",e.az="az",e.ba="ba",e.eu="eu",e.be="be",e.bn="bn",e.bs="bs",e.br="br",e.bg="bg",e.my="my",e.ca="ca",e.ceb="ceb",e.zh="zh",e.hr="hr",e.cs="cs",e.da="da",e.nl="nl",e.en="en",e.et="et",e.fo="fo",e.fi="fi",e.fr="fr",e.fy="fy",e.ff="ff",e.gd="gd",e.gl="gl",e.lg="lg",e.ka="ka",e.de="de",e.el="el",e.gu="gu",e.ht="ht",e.ha="ha",e.haw="haw",e.he="he",e.hi="hi",e.hu="hu",e.is="is",e.ig="ig",e.ilo="ilo",e.id="id",e.ga="ga",e.it="it",e.ja="ja",e.jv="jv",e.kn="kn",e.kk="kk",e.km="km",e.ko="ko",e.lo="lo",e.la="la",e.lv="lv",e.lb="lb",e.ln="ln",e.lt="lt",e.mk="mk",e.mg="mg",e.ms="ms",e.ml="ml",e.mt="mt",e.mi="mi",e.mr="mr",e.mo="mo",e.mn="mn",e.ne="ne",e.no="no",e.nn="nn",e.oc="oc",e.or="or",e.pa="pa",e.ps="ps",e.fa="fa",e.pl="pl",e.pt="pt",e.ro="ro",e.ru="ru",e.sa="sa",e.sr="sr",e.sn="sn",e.sd="sd",e.
1si="si",e.sk="sk",e.sl="sl",e.so="so",e.es="es",e.su="su",e.sw="sw",e.ss="ss",e.sv="sv",e.tl="tl",e.tg="tg",e.ta="ta",e.tt="tt",e.te="te",e.th="th",e.bo="bo",e.tn="tn",e.tr="tr",e.tk="tk",e.uk="uk",e.ur="ur",e.uz="uz",e.vi="vi",e.cy="cy",e.wo="wo",e.xh="xh",e.yi="yi",e.yo="yo",e.zu="zu"}(h||(h={})),function(e){e.UNKNOWN="UNKNOWN",e.GOOD="GOOD",e.BAD="BAD"}(p||(p={}));class H{constructor(e){this._connectionQuality=p.UNKNOWN,this.onConnectionQualityChanged=e}get connectionQuality(){return this._connectionQuality}handleStatsChanged(){let e=this.calculateConnectionQuality();e!==this._connectionQuality&&(this._connectionQuality=e,this.onConnectionQualityChanged(e))}start(e){this.stop(!0),this._start(e)}stop(e=!1){this._stop(),this._connectionQuality=p.UNKNOWN,e||this.onConnectionQualityChanged(p.UNKNOWN)}}class Y extends H{constructor(){super(...arguments),this.room=null,this.liveKitConnectionQuality=v._N.Unknown,this.liveKitConnectionState=null,this.handleConnectionQualityChanged=e=>{this.liveKitConnectionQuality=e,this.handleStatsChanged()},this.handleConnectionStateChanged=e=>{this.liveKitConnectionState=e,this.handleStatsChanged()}}_start(e){this.room=e,this.room.localParticipant.on(v.YI.ConnectionQualityChanged,this.handleConnectionQualityChanged),this.room.on(v.u9.ConnectionStateChanged,this.handleConnectionStateChanged)}_stop(){this.room&&(this.room.localParticipant.off(v.YI.ConnectionQualityChanged,this.handleConnectionQualityChanged),this.room.off(v.u9.ConnectionStateChanged,this.handleConnectionStateChanged))}calculateConnectionQuality(){return[v._N.Lost,v._N.Poor].includes(this.liveKitConnectionQuality)||this.liveKitConnectionState&&[v.KN.Disconnected,v.KN.Reconnecting,v.KN.SignalReconnecting].includes(this.liveKitConnectionState)?p.BAD:p.GOOD}}class X extends H{constructor(){super(...arguments),this.issueDetector=null,this.mosScores=null}_start(e){this.issueDetector=new z({autoAddPeerConnections:!1,getStatsInterval:3e3,onNetworkScoresUpdated:e=>{this.mosScores=e,this.handleStatsChanged()}}),this.issueDetector.handleNewPeerConnection(e)}_stop(){this.issueDetector&&(this.issueDetector.stopWatchingNewPeerConnections(),this.issueDetector=null),this.mosScores=null}calculateConnectionQuality(){return this.mosScores&&(this.mosScores.inbound||this.mosScores.outbound)?this.mosScores.inbound&&this.mosScores.inbound<3||this.mosScores.outbound&&this.mosScores.outbound<3?p.BAD:p.GOOD:p.UNKNOWN}}let $=function(...e){class t extends H{constructor(t){super(t),this.childTrackers=e.map(({getParams:e,TrackerClass:t})=>({tracker:new t(()=>this.handleStatsChanged()),getParams:e}))}calculateConnectionQuality(){let e=this.childTrackers.map(({tracker:e})=>e.connectionQuality);return e.some(e=>e===p.BAD)?p.BAD:e.every(e=>e===p.UNKNOWN)?p.UNKNOWN:p.GOOD}_start(e){this.childTrackers.forEach(({tracker:t,getParams:n})=>t.start(n(e)))}_stop(){this.childTrackers.forEach(({tracker:e})=>e.stop(!0))}}return t}({TrackerClass:Y,getParams:e=>e},{TrackerClass:X,getParams:e=>{var t;return(null===(t=e.engine.pcManager)||void 0===t?void 0:t.subscriber)._pc}});!function(e){e.MUTED="MUTED",e.UNMUTED="UNMUTED",e.STATE_CHANGED="STATE_CHANGED"}(f||(f={})),function(e){e.INACTIVE="INACTIVE",e.STARTING="STARTING",e.ACTIVE="ACTIVE"}(m||(m={}));class Z extends S.EventEmitter{constructor(e){super(),this._state=m.INACTIVE,this.track=null,this.room=e}get isConnected(){return this.room.state!==v.KN.Disconnected&&this.room.state!==v.KN.Connecting}get state(){return this._state}get isMuted(){var e,t;return null===(t=null===(e=this.track)||void 0===e?void 0:e.isMuted)||void 0===t||t}start(){return F(this,arguments,void 0,function*(e={}){if(!this.isConnected){console.warn("Voice chat can only be started when session is active");return}if(this._state!==m.INACTIVE){console.warn("Voice chat is already started");return}this.state=m.STARTING;let{defaultMuted:t,deviceId:n}=e;this.track=yield(0,v.rV)({echoCancellation:!0,noiseSuppression:!0,autoGainControl:!0,deviceId:n}),t?(yield this.track.mute(),this.emit(f.MUTED)):this.emit(f.UNMUTED),yield this.room.localParticipant.publishTrack(this.track),this.track.on(v.GI.Muted,()=>
1{this.emit(f.MUTED)}),this.track.on(v.GI.Unmuted,()=>{this.emit(f.UNMUTED)}),this.state=m.ACTIVE})}stop(){this.room.localParticipant.getTrackPublications().forEach(e=>{e.track&&e.track.kind===v.CC.Kind.Audio&&e.track.stop()}),this.track&&(this.track.removeAllListeners(),this.track.stop(),this.track=null),this.state=m.INACTIVE}mute(){return F(this,void 0,void 0,function*(){if(this.state!==m.ACTIVE){console.warn("Voice chat can only be muted when active");return}this.track&&this.track.mute()})}unmute(){return F(this,void 0,void 0,function*(){if(this.state!==m.ACTIVE){console.warn("Voice chat can only be unmuted when active");return}this.track&&this.track.unmute()})}setDevice(e){return F(this,void 0,void 0,function*(){return this.state!==m.ACTIVE?(console.warn("Voice chat device can only be set when active"),!1):!!this.track&&this.track.setDeviceId(e)})}set state(e){this._state!==e&&(this._state=e,this.emit(f.STATE_CHANGED,e))}}let ee="https://api.liveavatar.com";class et extends Error{constructor(e,t,n){super(e),this.status=null,this.errorCode=null!=t?t:500,this.status=null!=n?n:null}}class en{constructor(e,t=ee){this.sessionToken=e,this.apiUrl=null!=t?t:ee}request(e,t){return F(this,void 0,void 0,function*(){try{let n=yield fetch(`${this.apiUrl}${e}`,Object.assign(Object.assign({},t),{credentials:"include",headers:Object.assign({Authorization:`Bearer ${this.sessionToken}`,"Content-Type":"application/json"},t.headers)}));if(!n.ok){let e=yield n.json();throw new et(e.message||`API request failed with status ${n.status}`,e.code,n.status)}let s=yield n.json();if(1e3!==s.code)throw new et(s.message||"API request failed");return s.data}catch(e){if(e instanceof et)throw e;throw new et("API request failed")}})}startSession(){return F(this,void 0,void 0,function*(){return yield this.request("/v1/sessions/start",{method:"POST"})})}stopSession(){return F(this,void 0,void 0,function*(){return yield this.request("/v1/sessions/stop",{method:"POST"})})}keepAlive(){return F(this,void 0,void 0,function*(){return yield this.request("/v1/sessions/keep-alive",{method:"POST"})})}}class es extends S.EventEmitter{constructor(e,t){super(),this.connectionQualityIndicator=new $(e=>this.emit(a.SESSION_CONNECTION_QUALITY_CHANGED,e)),this._sessionInfo=null,this._sessionEventSocket=null,this._state=l.INACTIVE,this._remoteAudioTrack=null,this._remoteVideoTrack=null,this.config=null!=t?t:{},this.sessionClient=new en(e,this.config.apiUrl),this.room=new v.Wv({adaptiveStream:!!(0,v.P6)()&&{pauseVideoInBackground:!1},dynacast:(0,v.qi)(),videoCaptureDefaults:{resolution:v.gF.h720.resolution}}),this._voiceChat=new Z(this.room)}get state(){return this._state}get connectionQuality(){return this.connectionQualityIndicator.connectionQuality}get voiceChat(){return this._voiceChat}get maxSessionDuration(){var e,t;return null!==(t=null===(e=this._sessionInfo)||void 0===e?void 0:e.max_session_duration)&&void 0!==t?t:null}start(){return F(this,void 0,void 0,function*(){if(this.state!==l.INACTIVE){console.warn("Session is already started");return}try{this.state=l.CONNECTING,this._sessionInfo=yield this.sessionClient.startSession();let e=this._sessionInfo.livekit_url,t=this._sessionInfo.livekit_client_token,n=this._sessionInfo.ws_url;e&&t&&(this.trackEvents(),yield this.room.connect(e,t),this.connectionQualityIndicator.start(this.room)),n&&(yield this.connectWebSocket(n),this.setupWebSocketManagement()),yield this.configureSession(),this.state=l.CONNECTED}catch(e){throw console.error("Session start failed:",e),this.cleanup(),this.postStop(d.SESSION_START_FAILED),e}})}stop(){return F(this,void 0,void 0,function*(){this.assertConnected()&&(this.state=l.DISCONNECTING,this.cleanup(),this.postStop(d.CLIENT_INITIATED))})}keepAlive(){return F(this,void 0,void 0,function*(){if(this.assertConnected())try{this.sessionClient.keepAlive()}catch(e){throw console.error("Session keep alive error on server:",e),e}})}attach(e){if(!this._remoteVideoTrack||!this._remoteAudioTrack){console.warn("Stream is not yet ready");return}this._remoteVideoTrack.attach(e),this._remoteAudioTrack.attach(e)}message(e){if(!this.assertConnected())return;let t={event_type:u.AVATAR_SPEAK_RESPONSE,text:e};this.sendCommandEvent(t)}repeat(e){if(!this.assertConnected())return;let t={event_type:u.AVATAR_SPEAK_TEXT,text:e};this.sendCommandEvent(t)}repeatAudio(e){if(!this.assertConnected())return;if(!this._sessionEventSocket){console.warn("Cannot repeat audio. Please check you're using a supported mode.");return}let t={event_type:u.AVATAR_SPEAK_AUDIO,audio:e};this.sendCommandEvent(t)}startListening(){if(!this.assertConnected())return;let e={event_type:u.AVATAR_START_LISTENING};this.sendCommandEvent(e)}stopListening(){if(!this.assertConnected())return;let e={event_type:u.AVATAR_STOP_LISTENING};this.sendCommandEvent(e)}interrupt(){if(!this.assertConnected())return;let e={event_type:u.AVATAR_INTERRUPT};this.sendCommandEvent(e)}trackEvents(){let e=new MediaStream;this.room.on(v.u9.TrackSubscribed,(t,n,s)=>{if("heygen"===s.identity&&("video"===t.kind||"audio"===t.kind)){"video"===t.kind?this._remoteVideoTrack=t:this._remoteAudioTrack=t,e.addTrack(t.mediaStreamTrack);let n=e.getVideoTracks().length>0,s=e.getAudioTracks().length>0;
1n&&s&&this.emit(a.SESSION_STREAM_READY)}}),this.room.on(v.u9.DataReceived,(e,t,n,s)=>{if("agent-response"!==s)return;let i=null;try{let t=new TextDecoder().decode(e);i=JSON.parse(t)}catch(e){console.error(e)}if(!i)return;let r=q(i);if(r){let[e,...t]=r;this.emit(e,...t)}}),this.room.on(v.u9.ParticipantConnected,e=>{console.warn("participantConnected",e)}),this.room.on(v.u9.TrackUnsubscribed,t=>{console.warn("trackUnsubscribed",t);let n=t.mediaStreamTrack;n&&e.removeTrack(n)}),this.room.on(v.u9.Disconnected,()=>{this.handleRoomDisconnect()})}connectWebSocket(e){return F(this,void 0,void 0,function*(){return new Promise((t,n)=>{this._sessionEventSocket=new WebSocket(e),this._sessionEventSocket.onopen=()=>{t()}})})}setupWebSocketManagement(){this._sessionEventSocket&&(this._sessionEventSocket.onmessage=e=>{this.handleWebSocketMessage(e)},this._sessionEventSocket.onerror=e=>{console.error("WebSocket error:",e)},this._sessionEventSocket.onclose=e=>{console.warn("WebSocket closed - code:",e.code,"reason:",e.reason,"wasClean:",e.wasClean),this.handleWebSocketDisconnect()})}handleWebSocketMessage(e){let t=null;try{t=JSON.parse(e.data)}catch(e){console.error("Failed to parse WebSocket message:",e);return}if(!t)return;let{type:n,event_id:s}=t;"agent.speak_started"===n?this.emit(c.AVATAR_SPEAK_STARTED,{event_type:c.AVATAR_SPEAK_STARTED,event_id:s}):"agent.speak_ended"===n&&this.emit(c.AVATAR_SPEAK_ENDED,{event_type:c.AVATAR_SPEAK_ENDED,event_id:s})}handleWebSocketDisconnect(){this.state!==l.DISCONNECTING&&this.state!==l.DISCONNECTED&&(this._sessionEventSocket&&this._sessionEventSocket.readyState===WebSocket.OPEN&&this._sessionEventSocket.close(),this._sessionEventSocket=null,this.cleanup(),this.postStop(d.UNKNOWN_REASON))}configureSession(){return F(this,void 0,void 0,function*(){this.config.voiceChat&&(yield this.voiceChat.start("boolean"==typeof this.config.voiceChat?{}:this.config.voiceChat))})}set state(e){this._state!==e&&(this._state=e,this.emit(a.SESSION_STATE_CHANGED,e))}cleanup(){return F(this,void 0,void 0,function*(){this.connectionQualityIndicator.stop(),this.voiceChat.stop(),this._remoteAudioTrack&&this._remoteAudioTrack.stop(),this._remoteVideoTrack&&this._remoteVideoTrack.stop(),this._remoteAudioTrack=null,this._remoteVideoTrack=null,this.room.localParticipant.removeAllListeners(),this.room.removeAllListeners(),this._sessionEventSocket&&(this._sessionEventSocket.onopen=null,this._sessionEventSocket.onmessage=null,this._sessionEventSocket.onerror=null,this._sessionEventSocket.onclose=null,(this._sessionEventSocket.readyState===WebSocket.OPEN||this._sessionEventSocket.readyState===WebSocket.CONNECTING)&&this._sessionEventSocket.close(),this._sessionEventSocket=null),"connected"===this.room.state&&this.room.disconnect(),yield this.sessionClient.stopSession()})}postStop(e){this.state=l.DISCONNECTED,this.emit(a.SESSION_DISCONNECTED,e)}handleRoomDisconnect(){this.cleanup(),this.postStop(d.UNKNOWN_REASON)}sendCommandEvent(e){if(this._sessionEventSocket&&this._sessionEventSocket.readyState===WebSocket.OPEN)this.sendCommandEventToWebSocket(e);else if("connected"===this.room.state){let t=new TextEncoder().encode(JSON.stringify(e));this.room.localParticipant.publishData(t,{reliable:!0,topic:"agent-control"})}else console.warn("No active connection to send command event")}generateEventId(){return"undefined"!=typeof crypto&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=16*Math.random()|0;return("x"===e?t:3&t|8).toString(16)})}sendCommandEventToWebSocket(e){if(!this._sessionEventSocket||this._sessionEventSocket.readyState!==WebSocket.OPEN){console.warn("WebSocket not open to send command event");return}let t=e.event_type,n=this.generateEventId();switch(t){case u.AVATAR_SPEAK_AUDIO:for(let t of function(e){let t=e.length,n=[];for(let s=0;s<t;s+=960)n.push(e.slice(s,s+960));return n}(e.audio))this._sessionEventSocket.send(JSON.stringify({type:"agent.speak",event_id:n,audio:t}));this._sessionEventSocket.send(JSON.stringify({type:"agent.speak_end",event_id:n}));return;case u.AVATAR_INTERRUPT:this._sessionEventSocket.send(JSON.stringify({type:"agent.interrupt",event_id:n}));return;case u.AVATAR_START_LISTENING:this._sessionEventSocket.send(JSON.stringify({type:"agent.start_listening",event_id:n}));return;case u.AVATAR_STOP_LISTENING:this._sessionEventSocket.send(JSON.stringify({type:"agent.stop_listening",event_id:n}));return;default:console.warn("Unsupported command event type:",t)}}assertConnected(){return this.state===l.CONNECTED||(console.warn("Session is not connected"),!1)}}}
1,28633:(e,t,n)=>{n.d(t,{N:()=>y});var s=n(95155),i=n(12115),r=n(64710),o=n(99234),a=n(35403),c=n(39656),u=n(92804),l=n(27249);function d(e,t){if("function"==typeof e)return e(t);null!=e&&(e.current=t)}class h extends i.Component{getSnapshotBeforeUpdate(e){let t=this.props.childRef.current;if(t&&e.isPresent&&!this.props.isPresent){let e=t.offsetParent,n=(0,u.s)(e)&&e.offsetWidth||0,s=this.props.sizeRef.current;s.height=t.offsetHeight||0,s.width=t.offsetWidth||0,s.top=t.offsetTop,s.left=t.offsetLeft,s.right=n-s.width-s.left}return null}componentDidUpdate(){}render(){return this.props.children}}function p(e){let{children:t,isPresent:n,anchorX:r,root:o}=e,a=(0,i.useId)(),c=(0,i.useRef)(null),u=(0,i.useRef)({width:0,height:0,top:0,left:0,right:0}),{nonce:p}=(0,i.useContext)(l.Q),f=function(...e){return i.useCallback(function(...e){return t=>{let n=!1,s=e.map(e=>{let s=d(e,t);return n||"function"!=typeof s||(n=!0),s});if(n)return()=>{for(let t=0;t<s.length;t++){let n=s[t];"function"==typeof n?n():d(e[t],null)}}}}(...e),e)}(c,null==t?void 0:t.ref);return(0,i.useInsertionEffect)(()=>{let{width:e,height:t,top:s,left:i,right:l}=u.current;if(n||!c.current||!e||!t)return;c.current.dataset.motionPopId=a;let d=document.createElement("style");p&&(d.nonce=p);let h=null!=o?o:document.head;return h.appendChild(d),d.sheet&&d.sheet.insertRule('\n          [data-motion-pop-id="'.concat(a,'"] {\n            position: absolute !important;\n            width: ').concat(e,"px !important;\n            height: ").concat(t,"px !important;\n            ").concat("left"===r?"left: ".concat(i):"right: ".concat(l),"px !important;\n            top: ").concat(s,"px !important;\n          }\n        ")),()=>{h.contains(d)&&h.removeChild(d)}},[n]),(0,s.jsx)(h,{isPresent:n,childRef:c,sizeRef:u,children:i.cloneElement(t,{ref:f})})}let f=e=>{let{children:t,initial:n,isPresent:r,onExitComplete:a,custom:u,presenceAffectsLayout:l,mode:d,anchorX:h,root:f}=e,v=(0,o.M)(m),S=(0,i.useId)(),g=!0,y=(0,i.useMemo)(()=>(g=!1,{id:S,initial:n,isPresent:r,custom:u,onExitComplete:e=>
1{for(let t of(v.set(e,!0),v.values()))if(!t)return;a&&a()},register:e=>(v.set(e,!1),()=>v.delete(e))}),[r,v,a]);return l&&g&&(y={...y}),(0,i.useMemo)(()=>{v.forEach((e,t)=>v.set(t,!1))},[r]),i.useEffect(()=>{r||v.size||!a||a()},[r]),"popLayout"===d&&(t=(0,s.jsx)(p,{isPresent:r,anchorX:h,root:f,children:t})),(0,s.jsx)(c.t.Provider,{value:y,children:t})};function m(){return new Map}var v=n(85087);let S=e=>e.key||"";function g(e){let t=[];return i.Children.forEach(e,e=>{(0,i.isValidElement)(e)&&t.push(e)}),t}let y=e=>{let{children:t,custom:n,initial:c=!0,onExitComplete:u,presenceAffectsLayout:l=!0,mode:d="sync",propagate:h=!1,anchorX:p="left",root:m}=e,[y,k]=(0,v.xQ)(h),_=(0,i.useMemo)(()=>g(t),[t]),E=h&&!y?[]:_.map(S),T=(0,i.useRef)(!0),C=(0,i.useRef)(_),A=(0,o.M)(()=>new Map),[N,w]=(0,i.useState)(_),[b,I]=(0,i.useState)(_);(0,a.E)(()=>{T.current=!1,C.current=_;for(let e=0;e<b.length;e++){let t=S(b[e]);E.includes(t)?A.delete(t):!0!==A.get(t)&&A.set(t,!1)}},[b,E.length,E.join("-")]);let P=[];if(_!==N){let e=[..._];for(let t=0;t<b.length;t++){let n=b[t],s=S(n);E.includes(s)||(e.splice(t,0,n),P.push(n))}return"wait"===d&&P.length&&(e=P),I(g(e)),w(_),null}let{forceRender:D}=(0,i.useContext)(r.L);return(0,s.jsx)(s.Fragment,{children:b.map(e=>{let t=S(e),i=(!h||!!y)&&(_===b||E.includes(t));return(0,s.jsx)(f,{isPresent:i,initial:(!T.current||!!c)&&void 0,custom:n,presenceAffectsLayout:l,mode:d,root:m,onExitComplete:i?void 0:()=>{if(!A.has(t))return;A.set(t,!0);let e=!0;A.forEach(t=>{t||(e=!1)}),e&&(null==D||D(),I(C.current),h&&(null==k||k()),u&&u())},anchorX:p,children:e},t)})})}}}]);

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.