pinecall 0.8.15 → 0.8.16

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,123 @@
1
+ var e=Object.create,t=Object.defineProperty,n=Object.getOwnPropertyDescriptor,r=Object.getOwnPropertyNames,i=Object.getPrototypeOf,a=Object.prototype.hasOwnProperty,o=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t),e=null),t.exports),s=(e,i,o,s)=>{if(i&&typeof i==`object`||typeof i==`function`)for(var c=r(i),l=0,u=c.length,d;l<u;l++)d=c[l],!a.call(e,d)&&d!==o&&t(e,d,{get:(e=>i[e]).bind(null,d),enumerable:!(s=n(i,d))||s.enumerable});return e},c=(n,r,o)=>(o=n==null?{}:e(i(n)),s(r||!n||!n.__esModule||!a.call(n,`default`)?t(o,`default`,{value:n,enumerable:!0}):o,n));(function(){let e=document.createElement(`link`).relList;if(e&&e.supports&&e.supports(`modulepreload`))return;for(let e of document.querySelectorAll(`link[rel="modulepreload"]`))n(e);new MutationObserver(e=>{for(let t of e)if(t.type===`childList`)for(let e of t.addedNodes)e.tagName===`LINK`&&e.rel===`modulepreload`&&n(e)}).observe(document,{childList:!0,subtree:!0});function t(e){let t={};return e.integrity&&(t.integrity=e.integrity),e.referrerPolicy&&(t.referrerPolicy=e.referrerPolicy),t.credentials=e.crossOrigin===`use-credentials`?`include`:e.crossOrigin===`anonymous`?`omit`:`same-origin`,t}function n(e){if(e.ep)return;e.ep=!0;let n=t(e);fetch(e.href,n)}})();var l=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.portal`),r=Symbol.for(`react.fragment`),i=Symbol.for(`react.strict_mode`),a=Symbol.for(`react.profiler`),o=Symbol.for(`react.consumer`),s=Symbol.for(`react.context`),c=Symbol.for(`react.forward_ref`),l=Symbol.for(`react.suspense`),u=Symbol.for(`react.memo`),d=Symbol.for(`react.lazy`),f=Symbol.for(`react.activity`),p=Symbol.iterator;function m(e){return typeof e!=`object`||!e?null:(e=p&&e[p]||e[`@@iterator`],typeof e==`function`?e:null)}var h={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},g=Object.assign,_={};function v(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}v.prototype.isReactComponent={},v.prototype.setState=function(e,t){if(typeof e!=`object`&&typeof e!=`function`&&e!=null)throw Error(`takes an object of state variables to update or a function which returns an object of state variables.`);this.updater.enqueueSetState(this,e,t,`setState`)},v.prototype.forceUpdate=function(e){this.updater.enqueueForceUpdate(this,e,`forceUpdate`)};function y(){}y.prototype=v.prototype;function b(e,t,n){this.props=e,this.context=t,this.refs=_,this.updater=n||h}var x=b.prototype=new y;x.constructor=b,g(x,v.prototype),x.isPureReactComponent=!0;var S=Array.isArray;function C(){}var w={H:null,A:null,T:null,S:null},T=Object.prototype.hasOwnProperty;function ee(e,n,r){var i=r.ref;return{$$typeof:t,type:e,key:n,ref:i===void 0?null:i,props:r}}function te(e,t){return ee(e.type,t,e.props)}function ne(e){return typeof e==`object`&&!!e&&e.$$typeof===t}function re(e){var t={"=":`=0`,":":`=2`};return`$`+e.replace(/[=:]/g,function(e){return t[e]})}var E=/\/+/g;function ie(e,t){return typeof e==`object`&&e&&e.key!=null?re(``+e.key):t.toString(36)}function D(e){switch(e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason;default:switch(typeof e.status==`string`?e.then(C,C):(e.status=`pending`,e.then(function(t){e.status===`pending`&&(e.status=`fulfilled`,e.value=t)},function(t){e.status===`pending`&&(e.status=`rejected`,e.reason=t)})),e.status){case`fulfilled`:return e.value;case`rejected`:throw e.reason}}throw e}function ae(e,r,i,a,o){var s=typeof e;(s===`undefined`||s===`boolean`)&&(e=null);var c=!1;if(e===null)c=!0;else switch(s){case`bigint`:case`string`:case`number`:c=!0;break;case`object`:switch(e.$$typeof){case t:case n:c=!0;break;case d:return c=e._init,ae(c(e._payload),r,i,a,o)}}if(c)return o=o(e),c=a===``?`.`+ie(e,0):a,S(o)?(i=``,c!=null&&(i=c.replace(E,`$&/`)+`/`),ae(o,r,i,``,function(e){return e})):o!=null&&(ne(o)&&(o=te(o,i+(o.key==null||e&&e.key===o.key?``:(``+o.key).replace(E,`$&/`)+`/`)+c)),r.push(o)),1;c=0;var l=a===``?`.`:a+`:`;if(S(e))for(var u=0;u<e.length;u++)a=e[u],s=l+ie(a,u),c+=ae(a,r,i,s,o);else if(u=m(e),typeof u==`function`)for(e=u.call(e),u=0;!(a=e.next()).done;)a=a.value,s=l+ie(a,u++),c+=ae(a,r,i,s,o);else if(s===`object`){if(typeof e.then==`function`)return ae(D(e),r,i,a,o);throw r=String(e),Error(`Objects are not valid as a React child (found: `+(r===`[object Object]`?`object with keys {`+Object.keys(e).join(`, `)+`}`:r)+`). If you meant to render a collection of children, use an array instead.`)}return c}function oe(e,t,n){if(e==null)return e;var r=[],i=0;return ae(e,r,``,``,function(e){return t.call(n,e,i++)}),r}function se(e){if(e._status===-1){var t=e._result;t=t(),t.then(function(t){(e._status===0||e._status===-1)&&(e._status=1,e._result=t)},function(t){(e._status===0||e._status===-1)&&(e._status=2,e._result=t)}),e._status===-1&&(e._status=0,e._result=t)}if(e._status===1)return e._result.default;throw e._result}var O=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)},ce={map:oe,forEach:function(e,t,n){oe(e,function(){t.apply(this,arguments)},n)},count:function(e){var t=0;return oe(e,function(){t++}),t},toArray:function(e){return oe(e,function(e){return e})||[]},only:function(e){if(!ne(e))throw Error(`React.Children.only expected to receive a single React element child.`);return e}};e.Activity=f,e.Children=ce,e.Component=v,e.Fragment=r,e.Profiler=a,e.PureComponent=b,e.StrictMode=i,e.Suspense=l,e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=w,e.__COMPILER_RUNTIME={__proto__:null,c:function(e){return w.H.useMemoCache(e)}},e.cache=function(e){return function(){return e.apply(null,arguments)}},e.cacheSignal=function(){return null},e.cloneElement=function(e,t,n){if(e==null)throw Error(`The argument must be a React element, but you passed `+e+`.`);var r=g({},e.props),i=e.key;if(t!=null)for(a in t.key!==void 0&&(i=``+t.key),t)!T.call(t,a)||a===`key`||a===`__self`||a===`__source`||a===`ref`&&t.ref===void 0||(r[a]=t[a]);var a=arguments.length-2;if(a===1)r.children=n;else if(1<a){for(var o=Array(a),s=0;s<a;s++)o[s]=arguments[s+2];r.children=o}return ee(e.type,i,r)},e.createContext=function(e){return e={$$typeof:s,_currentValue:e,_currentValue2:e,_threadCount:0,Provider:null,Consumer:null},e.Provider=e,e.Consumer={$$typeof:o,_context:e},e},e.createElement=function(e,t,n){var r,i={},a=null;if(t!=null)for(r in t.key!==void 0&&(a=``+t.key),t)T.call(t,r)&&r!==`key`&&r!==`__self`&&r!==`__source`&&(i[r]=t[r]);var o=arguments.length-2;if(o===1)i.children=n;else if(1<o){for(var s=Array(o),c=0;c<o;c++)s[c]=arguments[c+2];i.children=s}if(e&&e.defaultProps)for(r in o=e.defaultProps,o)i[r]===void 0&&(i[r]=o[r]);return ee(e,a,i)},e.createRef=function(){return{current:null}},e.forwardRef=function(e){return{$$typeof:c,render:e}},e.isValidElement=ne,e.lazy=function(e){return{$$typeof:d,_payload:{_status:-1,_result:e},_init:se}},e.memo=function(e,t){return{$$typeof:u,type:e,compare:t===void 0?null:t}},e.startTransition=function(e){var t=w.T,n={};w.T=n;try{var r=e(),i=w.S;i!==null&&i(n,r),typeof r==`object`&&r&&typeof r.then==`function`&&r.then(C,O)}catch(e){O(e)}finally{t!==null&&n.types!==null&&(t.types=n.types),w.T=t}},e.unstable_useCacheRefresh=function(){return w.H.useCacheRefresh()},e.use=function(e){return w.H.use(e)},e.useActionState=function(e,t,n){return w.H.useActionState(e,t,n)},e.useCallback=function(e,t){return w.H.useCallback(e,t)},e.useContext=function(e){return w.H.useContext(e)},e.useDebugValue=function(){},e.useDeferredValue=function(e,t){return w.H.useDeferredValue(e,t)},e.useEffect=function(e,t){return w.H.useEffect(e,t)},e.useEffectEvent=function(e){return w.H.useEffectEvent(e)},e.useId=function(){return w.H.useId()},e.useImperativeHandle=function(e,t,n){return w.H.useImperativeHandle(e,t,n)},e.useInsertionEffect=function(e,t){return w.H.useInsertionEffect(e,t)},e.useLayoutEffect=function(e,t){return w.H.useLayoutEffect(e,t)},e.useMemo=function(e,t){return w.H.useMemo(e,t)},e.useOptimistic=function(e,t){return w.H.useOptimistic(e,t)},e.useReducer=function(e,t,n){return w.H.useReducer(e,t,n)},e.useRef=function(e){return w.H.useRef(e)},e.useState=function(e){return w.H.useState(e)},e.useSyncExternalStore=function(e,t,n){return w.H.useSyncExternalStore(e,t,n)},e.useTransition=function(){return w.H.useTransition()},e.version=`19.2.8`})),u=o(((e,t)=>{t.exports=l()})),d=o((e=>{function t(e,t){var n=e.length;e.push(t);a:for(;0<n;){var r=n-1>>>1,a=e[r];if(0<i(a,t))e[r]=t,e[n]=a,n=r;else break a}}function n(e){return e.length===0?null:e[0]}function r(e){if(e.length===0)return null;var t=e[0],n=e.pop();if(n!==t){e[0]=n;a:for(var r=0,a=e.length,o=a>>>1;r<o;){var s=2*(r+1)-1,c=e[s],l=s+1,u=e[l];if(0>i(c,n))l<a&&0>i(u,c)?(e[r]=u,e[l]=n,r=l):(e[r]=c,e[s]=n,r=s);else if(l<a&&0>i(u,n))e[r]=u,e[l]=n,r=l;else break a}}return t}function i(e,t){var n=e.sortIndex-t.sortIndex;return n===0?e.id-t.id:n}if(e.unstable_now=void 0,typeof performance==`object`&&typeof performance.now==`function`){var a=performance;e.unstable_now=function(){return a.now()}}else{var o=Date,s=o.now();e.unstable_now=function(){return o.now()-s}}var c=[],l=[],u=1,d=null,f=3,p=!1,m=!1,h=!1,g=!1,_=typeof setTimeout==`function`?setTimeout:null,v=typeof clearTimeout==`function`?clearTimeout:null,y=typeof setImmediate<`u`?setImmediate:null;function b(e){for(var i=n(l);i!==null;){if(i.callback===null)r(l);else if(i.startTime<=e)r(l),i.sortIndex=i.expirationTime,t(c,i);else break;i=n(l)}}function x(e){if(h=!1,b(e),!m){if(n(c)!==null)m=!0,S||(S=!0,ne());else{var t=n(l);t!==null&&ie(x,t.startTime-e)}}}var S=!1,C=-1,w=5,T=-1;function ee(){return g?!0:!(e.unstable_now()-T<w)}function te(){if(g=!1,S){var t=e.unstable_now();T=t;var i=!0;try{a:{m=!1,h&&(h=!1,v(C),C=-1),p=!0;var a=f;try{b:{for(b(t),d=n(c);d!==null&&!(d.expirationTime>t&&ee());){var o=d.callback;if(typeof o==`function`){d.callback=null,f=d.priorityLevel;var s=o(d.expirationTime<=t);if(t=e.unstable_now(),typeof s==`function`){d.callback=s,b(t),i=!0;break b}d===n(c)&&r(c),b(t)}else r(c);d=n(c)}if(d!==null)i=!0;else{var u=n(l);u!==null&&ie(x,u.startTime-t),i=!1}}break a}finally{d=null,f=a,p=!1}i=void 0}}finally{i?ne():S=!1}}}var ne;if(typeof y==`function`)ne=function(){y(te)};else if(typeof MessageChannel<`u`){var re=new MessageChannel,E=re.port2;re.port1.onmessage=te,ne=function(){E.postMessage(null)}}else ne=function(){_(te,0)};function ie(t,n){C=_(function(){t(e.unstable_now())},n)}e.unstable_IdlePriority=5,e.unstable_ImmediatePriority=1,e.unstable_LowPriority=4,e.unstable_NormalPriority=3,e.unstable_Profiling=null,e.unstable_UserBlockingPriority=2,e.unstable_cancelCallback=function(e){e.callback=null},e.unstable_forceFrameRate=function(e){0>e||125<e?console.error(`forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported`):w=0<e?Math.floor(1e3/e):5},e.unstable_getCurrentPriorityLevel=function(){return f},e.unstable_next=function(e){switch(f){case 1:case 2:case 3:var t=3;break;default:t=f}var n=f;f=t;try{return e()}finally{f=n}},e.unstable_requestPaint=function(){g=!0},e.unstable_runWithPriority=function(e,t){switch(e){case 1:case 2:case 3:case 4:case 5:break;default:e=3}var n=f;f=e;try{return t()}finally{f=n}},e.unstable_scheduleCallback=function(r,i,a){var o=e.unstable_now();switch(typeof a==`object`&&a?(a=a.delay,a=typeof a==`number`&&0<a?o+a:o):a=o,r){case 1:var s=-1;break;case 2:s=250;break;case 5:s=1073741823;break;case 4:s=1e4;break;default:s=5e3}return s=a+s,r={id:u++,callback:i,priorityLevel:r,startTime:a,expirationTime:s,sortIndex:-1},a>o?(r.sortIndex=a,t(l,r),n(c)===null&&r===n(l)&&(h?(v(C),C=-1):h=!0,ie(x,a-o))):(r.sortIndex=s,t(c,r),m||p||(m=!0,S||(S=!0,ne()))),r},e.unstable_shouldYield=ee,e.unstable_wrapCallback=function(e){var t=f;return function(){var n=f;f=t;try{return e.apply(this,arguments)}finally{f=n}}}})),f=o(((e,t)=>{t.exports=d()})),p=o((e=>{var t=u();function n(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function r(){}var i={d:{f:r,r:function(){throw Error(n(522))},D:r,C:r,L:r,m:r,X:r,S:r,M:r},p:0,findDOMNode:null},a=Symbol.for(`react.portal`);function o(e,t,n){var r=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:a,key:r==null?null:``+r,children:e,containerInfo:t,implementation:n}}var s=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function c(e,t){if(e===`font`)return``;if(typeof t==`string`)return t===`use-credentials`?t:``}e.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=i,e.createPortal=function(e,t){var r=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!t||t.nodeType!==1&&t.nodeType!==9&&t.nodeType!==11)throw Error(n(299));return o(e,t,null,r)},e.flushSync=function(e){var t=s.T,n=i.p;try{if(s.T=null,i.p=2,e)return e()}finally{s.T=t,i.p=n,i.d.f()}},e.preconnect=function(e,t){typeof e==`string`&&(t?(t=t.crossOrigin,t=typeof t==`string`?t===`use-credentials`?t:``:void 0):t=null,i.d.C(e,t))},e.prefetchDNS=function(e){typeof e==`string`&&i.d.D(e)},e.preinit=function(e,t){if(typeof e==`string`&&t&&typeof t.as==`string`){var n=t.as,r=c(n,t.crossOrigin),a=typeof t.integrity==`string`?t.integrity:void 0,o=typeof t.fetchPriority==`string`?t.fetchPriority:void 0;n===`style`?i.d.S(e,typeof t.precedence==`string`?t.precedence:void 0,{crossOrigin:r,integrity:a,fetchPriority:o}):n===`script`&&i.d.X(e,{crossOrigin:r,integrity:a,fetchPriority:o,nonce:typeof t.nonce==`string`?t.nonce:void 0})}},e.preinitModule=function(e,t){if(typeof e==`string`){if(typeof t==`object`&&t){if(t.as==null||t.as===`script`){var n=c(t.as,t.crossOrigin);i.d.M(e,{crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0})}}else t??i.d.M(e)}},e.preload=function(e,t){if(typeof e==`string`&&typeof t==`object`&&t&&typeof t.as==`string`){var n=t.as,r=c(n,t.crossOrigin);i.d.L(e,n,{crossOrigin:r,integrity:typeof t.integrity==`string`?t.integrity:void 0,nonce:typeof t.nonce==`string`?t.nonce:void 0,type:typeof t.type==`string`?t.type:void 0,fetchPriority:typeof t.fetchPriority==`string`?t.fetchPriority:void 0,referrerPolicy:typeof t.referrerPolicy==`string`?t.referrerPolicy:void 0,imageSrcSet:typeof t.imageSrcSet==`string`?t.imageSrcSet:void 0,imageSizes:typeof t.imageSizes==`string`?t.imageSizes:void 0,media:typeof t.media==`string`?t.media:void 0})}},e.preloadModule=function(e,t){if(typeof e==`string`){if(t){var n=c(t.as,t.crossOrigin);i.d.m(e,{as:typeof t.as==`string`&&t.as!==`script`?t.as:void 0,crossOrigin:n,integrity:typeof t.integrity==`string`?t.integrity:void 0})}else i.d.m(e)}},e.requestFormReset=function(e){i.d.r(e)},e.unstable_batchedUpdates=function(e,t){return e(t)},e.useFormState=function(e,t,n){return s.H.useFormState(e,t,n)},e.useFormStatus=function(){return s.H.useHostTransitionStatus()},e.version=`19.2.8`})),m=o(((e,t)=>{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=p()})),h=o((e=>{var t=f(),n=u(),r=m();function i(e){var t=`https://react.dev/errors/`+e;if(1<arguments.length){t+=`?args[]=`+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+=`&args[]=`+encodeURIComponent(arguments[n])}return`Minified React error #`+e+`; visit `+t+` for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`}function a(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function o(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,t.flags&4098&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function s(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function c(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function l(e){if(o(e)!==e)throw Error(i(188))}function d(e){var t=e.alternate;if(!t){if(t=o(e),t===null)throw Error(i(188));return t===e?e:null}for(var n=e,r=t;;){var a=n.return;if(a===null)break;var s=a.alternate;if(s===null){if(r=a.return,r!==null){n=r;continue}break}if(a.child===s.child){for(s=a.child;s;){if(s===n)return l(a),e;if(s===r)return l(a),t;s=s.sibling}throw Error(i(188))}if(n.return!==r.return)n=a,r=s;else{for(var c=!1,u=a.child;u;){if(u===n){c=!0,n=a,r=s;break}if(u===r){c=!0,r=a,n=s;break}u=u.sibling}if(!c){for(u=s.child;u;){if(u===n){c=!0,n=s,r=a;break}if(u===r){c=!0,r=s,n=a;break}u=u.sibling}if(!c)throw Error(i(189))}}if(n.alternate!==r)throw Error(i(190))}if(n.tag!==3)throw Error(i(188));return n.stateNode.current===n?e:t}function p(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=p(e),t!==null)return t;e=e.sibling}return null}var h=Object.assign,g=Symbol.for(`react.element`),_=Symbol.for(`react.transitional.element`),v=Symbol.for(`react.portal`),y=Symbol.for(`react.fragment`),b=Symbol.for(`react.strict_mode`),x=Symbol.for(`react.profiler`),S=Symbol.for(`react.consumer`),C=Symbol.for(`react.context`),w=Symbol.for(`react.forward_ref`),T=Symbol.for(`react.suspense`),ee=Symbol.for(`react.suspense_list`),te=Symbol.for(`react.memo`),ne=Symbol.for(`react.lazy`),re=Symbol.for(`react.activity`),E=Symbol.for(`react.memo_cache_sentinel`),ie=Symbol.iterator;function D(e){return typeof e!=`object`||!e?null:(e=ie&&e[ie]||e[`@@iterator`],typeof e==`function`?e:null)}var ae=Symbol.for(`react.client.reference`);function oe(e){if(e==null)return null;if(typeof e==`function`)return e.$$typeof===ae?null:e.displayName||e.name||null;if(typeof e==`string`)return e;switch(e){case y:return`Fragment`;case x:return`Profiler`;case b:return`StrictMode`;case T:return`Suspense`;case ee:return`SuspenseList`;case re:return`Activity`}if(typeof e==`object`)switch(e.$$typeof){case v:return`Portal`;case C:return e.displayName||`Context`;case S:return(e._context.displayName||`Context`)+`.Consumer`;case w:var t=e.render;return e=e.displayName,e||=(e=t.displayName||t.name||``,e===``?`ForwardRef`:`ForwardRef(`+e+`)`),e;case te:return t=e.displayName||null,t===null?oe(e.type)||`Memo`:t;case ne:t=e._payload,e=e._init;try{return oe(e(t))}catch{}}return null}var se=Array.isArray,O=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,ce=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,le={pending:!1,data:null,method:null,action:null},ue=[],de=-1;function fe(e){return{current:e}}function pe(e){0>de||(e.current=ue[de],ue[de]=null,de--)}function me(e,t){de++,ue[de]=e.current,e.current=t}var he=fe(null),ge=fe(null),_e=fe(null),ve=fe(null);function ye(e,t){switch(me(_e,t),me(ge,e),me(he,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?cf(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=cf(t),e=lf(t,e);else switch(e){case`svg`:e=1;break;case`math`:e=2;break;default:e=0}}pe(he),me(he,e)}function be(){pe(he),pe(ge),pe(_e)}function xe(e){e.memoizedState!==null&&me(ve,e);var t=he.current,n=lf(t,e.type);t!==n&&(me(ge,e),me(he,n))}function Se(e){ge.current===e&&(pe(he),pe(ge)),ve.current===e&&(pe(ve),mp._currentValue=le)}var Ce,we;function Te(e){if(Ce===void 0)try{throw Error()}catch(e){var t=e.stack.trim().match(/\n( *(at )?)/);Ce=t&&t[1]||``,we=-1<e.stack.indexOf(`
2
+ at`)?` (<anonymous>)`:-1<e.stack.indexOf(`@`)?`@unknown:0:0`:``}return`
3
+ `+Ce+e+we}var Ee=!1;function De(e,t){if(!e||Ee)return``;Ee=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var r={DetermineComponentFrameRoot:function(){try{if(t){var n=function(){throw Error()};if(Object.defineProperty(n.prototype,"props",{set:function(){throw Error()}}),typeof Reflect==`object`&&Reflect.construct){try{Reflect.construct(n,[])}catch(e){var r=e}Reflect.construct(e,[],n)}else{try{n.call()}catch(e){r=e}e.call(n.prototype)}}else{try{throw Error()}catch(e){r=e}(n=e())&&typeof n.catch==`function`&&n.catch(function(){})}}catch(e){if(e&&r&&typeof e.stack==`string`)return[e.stack,r.stack]}return[null,null]}};r.DetermineComponentFrameRoot.displayName=`DetermineComponentFrameRoot`;var i=Object.getOwnPropertyDescriptor(r.DetermineComponentFrameRoot,`name`);i&&i.configurable&&Object.defineProperty(r.DetermineComponentFrameRoot,"name",{value:`DetermineComponentFrameRoot`});var a=r.DetermineComponentFrameRoot(),o=a[0],s=a[1];if(o&&s){var c=o.split(`
4
+ `),l=s.split(`
5
+ `);for(i=r=0;r<c.length&&!c[r].includes(`DetermineComponentFrameRoot`);)r++;for(;i<l.length&&!l[i].includes(`DetermineComponentFrameRoot`);)i++;if(r===c.length||i===l.length)for(r=c.length-1,i=l.length-1;1<=r&&0<=i&&c[r]!==l[i];)i--;for(;1<=r&&0<=i;r--,i--)if(c[r]!==l[i]){if(r!==1||i!==1)do if(r--,i--,0>i||c[r]!==l[i]){var u=`
6
+ `+c[r].replace(` at new `,` at `);return e.displayName&&u.includes(`<anonymous>`)&&(u=u.replace(`<anonymous>`,e.displayName)),u}while(1<=r&&0<=i);break}}}finally{Ee=!1,Error.prepareStackTrace=n}return(n=e?e.displayName||e.name:``)?Te(n):``}function Oe(e,t){switch(e.tag){case 26:case 27:case 5:return Te(e.type);case 16:return Te(`Lazy`);case 13:return e.child!==t&&t!==null?Te(`Suspense Fallback`):Te(`Suspense`);case 19:return Te(`SuspenseList`);case 0:case 15:return De(e.type,!1);case 11:return De(e.type.render,!1);case 1:return De(e.type,!0);case 31:return Te(`Activity`);default:return``}}function ke(e){try{var t=``,n=null;do t+=Oe(e,n),n=e,e=e.return;while(e);return t}catch(e){return`
7
+ Error generating stack: `+e.message+`
8
+ `+e.stack}}var Ae=Object.prototype.hasOwnProperty,je=t.unstable_scheduleCallback,Me=t.unstable_cancelCallback,Ne=t.unstable_shouldYield,Pe=t.unstable_requestPaint,Fe=t.unstable_now,Ie=t.unstable_getCurrentPriorityLevel,Le=t.unstable_ImmediatePriority,Re=t.unstable_UserBlockingPriority,ze=t.unstable_NormalPriority,Be=t.unstable_LowPriority,Ve=t.unstable_IdlePriority,He=t.log,Ue=t.unstable_setDisableYieldValue,We=null,Ge=null;function Ke(e){if(typeof He==`function`&&Ue(e),Ge&&typeof Ge.setStrictMode==`function`)try{Ge.setStrictMode(We,e)}catch{}}var qe=Math.clz32?Math.clz32:Xe,Je=Math.log,Ye=Math.LN2;function Xe(e){return e>>>=0,e===0?32:31-(Je(e)/Ye|0)|0}var Ze=256,Qe=262144,$e=4194304;function et(e){var t=e&42;if(t!==0)return t;switch(e&-e){case 1:return 1;case 2:return 2;case 4:return 4;case 8:return 8;case 16:return 16;case 32:return 32;case 64:return 64;case 128:return 128;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:return e&261888;case 262144:case 524288:case 1048576:case 2097152:return e&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return e&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return e}}function tt(e,t,n){var r=e.pendingLanes;if(r===0)return 0;var i=0,a=e.suspendedLanes,o=e.pingedLanes;e=e.warmLanes;var s=r&134217727;return s===0?(s=r&~a,s===0?o===0?n||(n=r&~e,n!==0&&(i=et(n))):i=et(o):i=et(s)):(r=s&~a,r===0?(o&=s,o===0?n||(n=s&~e,n!==0&&(i=et(n))):i=et(o)):i=et(r)),i===0?0:t!==0&&t!==i&&(t&a)===0&&(a=i&-i,n=t&-t,a>=n||a===32&&n&4194048)?t:i}function nt(e,t){return(e.pendingLanes&~(e.suspendedLanes&~e.pingedLanes)&t)===0}function rt(e,t){switch(e){case 1:case 2:case 4:case 8:case 64:return t+250;case 16:case 32:case 128:case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:return t+5e3;case 4194304:case 8388608:case 16777216:case 33554432:return-1;case 67108864:case 134217728:case 268435456:case 536870912:case 1073741824:return-1;default:return-1}}function it(){var e=$e;return $e<<=1,!($e&62914560)&&($e=4194304),e}function at(e){for(var t=[],n=0;31>n;n++)t.push(e);return t}function ot(e,t){e.pendingLanes|=t,t!==268435456&&(e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0)}function st(e,t,n,r,i,a){var o=e.pendingLanes;e.pendingLanes=n,e.suspendedLanes=0,e.pingedLanes=0,e.warmLanes=0,e.expiredLanes&=n,e.entangledLanes&=n,e.errorRecoveryDisabledLanes&=n,e.shellSuspendCounter=0;var s=e.entanglements,c=e.expirationTimes,l=e.hiddenUpdates;for(n=o&~n;0<n;){var u=31-qe(n),d=1<<u;s[u]=0,c[u]=-1;var f=l[u];if(f!==null)for(l[u]=null,u=0;u<f.length;u++){var p=f[u];p!==null&&(p.lane&=-536870913)}n&=~d}r!==0&&ct(e,r,0),a!==0&&i===0&&e.tag!==0&&(e.suspendedLanes|=a&~(o&~t))}function ct(e,t,n){e.pendingLanes|=t,e.suspendedLanes&=~t;var r=31-qe(t);e.entangledLanes|=t,e.entanglements[r]=e.entanglements[r]|1073741824|n&261930}function lt(e,t){var n=e.entangledLanes|=t;for(e=e.entanglements;n;){var r=31-qe(n),i=1<<r;i&t|e[r]&t&&(e[r]|=t),n&=~i}}function ut(e,t){var n=t&-t;return n=n&42?1:dt(n),(n&(e.suspendedLanes|t))===0?n:0}function dt(e){switch(e){case 2:e=1;break;case 8:e=4;break;case 32:e=16;break;case 256:case 512:case 1024:case 2048:case 4096:case 8192:case 16384:case 32768:case 65536:case 131072:case 262144:case 524288:case 1048576:case 2097152:case 4194304:case 8388608:case 16777216:case 33554432:e=128;break;case 268435456:e=134217728;break;default:e=0}return e}function ft(e){return e&=-e,2<e?8<e?e&134217727?32:268435456:8:2}function pt(){var e=ce.p;return e===0?(e=window.event,e===void 0?32:Dp(e.type)):e}function mt(e,t){var n=ce.p;try{return ce.p=e,t()}finally{ce.p=n}}var ht=Math.random().toString(36).slice(2),gt=`__reactFiber$`+ht,_t=`__reactProps$`+ht,vt=`__reactContainer$`+ht,yt=`__reactEvents$`+ht,bt=`__reactListeners$`+ht,xt=`__reactHandles$`+ht,St=`__reactResources$`+ht,Ct=`__reactMarker$`+ht;function wt(e){delete e[gt],delete e[_t],delete e[yt],delete e[bt],delete e[xt]}function Tt(e){var t=e[gt];if(t)return t;for(var n=e.parentNode;n;){if(t=n[vt]||n[gt]){if(n=t.alternate,t.child!==null||n!==null&&n.child!==null)for(e=jf(e);e!==null;){if(n=e[gt])return n;e=jf(e)}return t}e=n,n=e.parentNode}return null}function Et(e){if(e=e[gt]||e[vt]){var t=e.tag;if(t===5||t===6||t===13||t===31||t===26||t===27||t===3)return e}return null}function Dt(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e.stateNode;throw Error(i(33))}function Ot(e){var t=e[St];return t||=e[St]={hoistableStyles:new Map,hoistableScripts:new Map},t}function kt(e){e[Ct]=!0}var At=new Set,jt={};function Mt(e,t){Nt(e,t),Nt(e+`Capture`,t)}function Nt(e,t){for(jt[e]=t,e=0;e<t.length;e++)At.add(t[e])}var Pt=RegExp(`^[:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD][:A-Z_a-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD\\-.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040]*$`),Ft={},It={};function Lt(e){return Ae.call(It,e)?!0:Ae.call(Ft,e)?!1:Pt.test(e)?It[e]=!0:(Ft[e]=!0,!1)}function Rt(e,t,n){if(Lt(t)){if(n===null)e.removeAttribute(t);else{switch(typeof n){case`undefined`:case`function`:case`symbol`:e.removeAttribute(t);return;case`boolean`:var r=t.toLowerCase().slice(0,5);if(r!==`data-`&&r!==`aria-`){e.removeAttribute(t);return}}e.setAttribute(t,``+n)}}}function zt(e,t,n){if(n===null)e.removeAttribute(t);else{switch(typeof n){case`undefined`:case`function`:case`symbol`:case`boolean`:e.removeAttribute(t);return}e.setAttribute(t,``+n)}}function Bt(e,t,n,r){if(r===null)e.removeAttribute(n);else{switch(typeof r){case`undefined`:case`function`:case`symbol`:case`boolean`:e.removeAttribute(n);return}e.setAttributeNS(t,n,``+r)}}function Vt(e){switch(typeof e){case`bigint`:case`boolean`:case`number`:case`string`:case`undefined`:return e;case`object`:return e;default:return``}}function Ht(e){var t=e.type;return(e=e.nodeName)&&e.toLowerCase()===`input`&&(t===`checkbox`||t===`radio`)}function Ut(e,t,n){var r=Object.getOwnPropertyDescriptor(e.constructor.prototype,t);if(!e.hasOwnProperty(t)&&r!==void 0&&typeof r.get==`function`&&typeof r.set==`function`){var i=r.get,a=r.set;return Object.defineProperty(e,t,{configurable:!0,get:function(){return i.call(this)},set:function(e){n=``+e,a.call(this,e)}}),Object.defineProperty(e,t,{enumerable:r.enumerable}),{getValue:function(){return n},setValue:function(e){n=``+e},stopTracking:function(){e._valueTracker=null,delete e[t]}}}}function Wt(e){if(!e._valueTracker){var t=Ht(e)?`checked`:`value`;e._valueTracker=Ut(e,t,``+e[t])}}function Gt(e){if(!e)return!1;var t=e._valueTracker;if(!t)return!0;var n=t.getValue(),r=``;return e&&(r=Ht(e)?e.checked?`true`:`false`:e.value),e=r,e!==n&&(t.setValue(e),!0)}function Kt(e){if(e||=typeof document<`u`?document:void 0,e===void 0)return null;try{return e.activeElement||e.body}catch{return e.body}}var qt=/[\n"\\]/g;function Jt(e){return e.replace(qt,function(e){return`\\`+e.charCodeAt(0).toString(16)+` `})}function Yt(e,t,n,r,i,a,o,s){e.name=``,o!=null&&typeof o!=`function`&&typeof o!=`symbol`&&typeof o!=`boolean`?e.type=o:e.removeAttribute(`type`),t==null?o!==`submit`&&o!==`reset`||e.removeAttribute(`value`):o===`number`?(t===0&&e.value===``||e.value!=t)&&(e.value=``+Vt(t)):e.value!==``+Vt(t)&&(e.value=``+Vt(t)),t==null?n==null?r!=null&&e.removeAttribute(`value`):Zt(e,o,Vt(n)):Zt(e,o,Vt(t)),i==null&&a!=null&&(e.defaultChecked=!!a),i!=null&&(e.checked=i&&typeof i!=`function`&&typeof i!=`symbol`),s!=null&&typeof s!=`function`&&typeof s!=`symbol`&&typeof s!=`boolean`?e.name=``+Vt(s):e.removeAttribute(`name`)}function Xt(e,t,n,r,i,a,o,s){if(a!=null&&typeof a!=`function`&&typeof a!=`symbol`&&typeof a!=`boolean`&&(e.type=a),t!=null||n!=null){if(!(a!==`submit`&&a!==`reset`||t!=null)){Wt(e);return}n=n==null?``:``+Vt(n),t=t==null?n:``+Vt(t),s||t===e.value||(e.value=t),e.defaultValue=t}r??=i,r=typeof r!=`function`&&typeof r!=`symbol`&&!!r,e.checked=s?e.checked:!!r,e.defaultChecked=!!r,o!=null&&typeof o!=`function`&&typeof o!=`symbol`&&typeof o!=`boolean`&&(e.name=o),Wt(e)}function Zt(e,t,n){t===`number`&&Kt(e.ownerDocument)===e||e.defaultValue===``+n||(e.defaultValue=``+n)}function Qt(e,t,n,r){if(e=e.options,t){t={};for(var i=0;i<n.length;i++)t[`$`+n[i]]=!0;for(n=0;n<e.length;n++)i=t.hasOwnProperty(`$`+e[n].value),e[n].selected!==i&&(e[n].selected=i),i&&r&&(e[n].defaultSelected=!0)}else{for(n=``+Vt(n),t=null,i=0;i<e.length;i++){if(e[i].value===n){e[i].selected=!0,r&&(e[i].defaultSelected=!0);return}t!==null||e[i].disabled||(t=e[i])}t!==null&&(t.selected=!0)}}function $t(e,t,n){if(t!=null&&(t=``+Vt(t),t!==e.value&&(e.value=t),n==null)){e.defaultValue!==t&&(e.defaultValue=t);return}e.defaultValue=n==null?``:``+Vt(n)}function en(e,t,n,r){if(t==null){if(r!=null){if(n!=null)throw Error(i(92));if(se(r)){if(1<r.length)throw Error(i(93));r=r[0]}n=r}n??=``,t=n}n=Vt(t),e.defaultValue=n,r=e.textContent,r===n&&r!==``&&r!==null&&(e.value=r),Wt(e)}function tn(e,t){if(t){var n=e.firstChild;if(n&&n===e.lastChild&&n.nodeType===3){n.nodeValue=t;return}}e.textContent=t}var nn=new Set(`animationIterationCount aspectRatio borderImageOutset borderImageSlice borderImageWidth boxFlex boxFlexGroup boxOrdinalGroup columnCount columns flex flexGrow flexPositive flexShrink flexNegative flexOrder gridArea gridRow gridRowEnd gridRowSpan gridRowStart gridColumn gridColumnEnd gridColumnSpan gridColumnStart fontWeight lineClamp lineHeight opacity order orphans scale tabSize widows zIndex zoom fillOpacity floodOpacity stopOpacity strokeDasharray strokeDashoffset strokeMiterlimit strokeOpacity strokeWidth MozAnimationIterationCount MozBoxFlex MozBoxFlexGroup MozLineClamp msAnimationIterationCount msFlex msZoom msFlexGrow msFlexNegative msFlexOrder msFlexPositive msFlexShrink msGridColumn msGridColumnSpan msGridRow msGridRowSpan WebkitAnimationIterationCount WebkitBoxFlex WebKitBoxFlexGroup WebkitBoxOrdinalGroup WebkitColumnCount WebkitColumns WebkitFlex WebkitFlexGrow WebkitFlexPositive WebkitFlexShrink WebkitLineClamp`.split(` `));function rn(e,t,n){var r=t.indexOf(`--`)===0;n==null||typeof n==`boolean`||n===``?r?e.setProperty(t,``):t===`float`?e.cssFloat=``:e[t]=``:r?e.setProperty(t,n):typeof n!=`number`||n===0||nn.has(t)?t===`float`?e.cssFloat=n:e[t]=(``+n).trim():e[t]=n+`px`}function an(e,t,n){if(t!=null&&typeof t!=`object`)throw Error(i(62));if(e=e.style,n!=null){for(var r in n)!n.hasOwnProperty(r)||t!=null&&t.hasOwnProperty(r)||(r.indexOf(`--`)===0?e.setProperty(r,``):r===`float`?e.cssFloat=``:e[r]=``);for(var a in t)r=t[a],t.hasOwnProperty(a)&&n[a]!==r&&rn(e,a,r)}else for(var o in t)t.hasOwnProperty(o)&&rn(e,o,t[o])}function on(e){if(e.indexOf(`-`)===-1)return!1;switch(e){case`annotation-xml`:case`color-profile`:case`font-face`:case`font-face-src`:case`font-face-uri`:case`font-face-format`:case`font-face-name`:case`missing-glyph`:return!1;default:return!0}}var sn=new Map([[`acceptCharset`,`accept-charset`],[`htmlFor`,`for`],[`httpEquiv`,`http-equiv`],[`crossOrigin`,`crossorigin`],[`accentHeight`,`accent-height`],[`alignmentBaseline`,`alignment-baseline`],[`arabicForm`,`arabic-form`],[`baselineShift`,`baseline-shift`],[`capHeight`,`cap-height`],[`clipPath`,`clip-path`],[`clipRule`,`clip-rule`],[`colorInterpolation`,`color-interpolation`],[`colorInterpolationFilters`,`color-interpolation-filters`],[`colorProfile`,`color-profile`],[`colorRendering`,`color-rendering`],[`dominantBaseline`,`dominant-baseline`],[`enableBackground`,`enable-background`],[`fillOpacity`,`fill-opacity`],[`fillRule`,`fill-rule`],[`floodColor`,`flood-color`],[`floodOpacity`,`flood-opacity`],[`fontFamily`,`font-family`],[`fontSize`,`font-size`],[`fontSizeAdjust`,`font-size-adjust`],[`fontStretch`,`font-stretch`],[`fontStyle`,`font-style`],[`fontVariant`,`font-variant`],[`fontWeight`,`font-weight`],[`glyphName`,`glyph-name`],[`glyphOrientationHorizontal`,`glyph-orientation-horizontal`],[`glyphOrientationVertical`,`glyph-orientation-vertical`],[`horizAdvX`,`horiz-adv-x`],[`horizOriginX`,`horiz-origin-x`],[`imageRendering`,`image-rendering`],[`letterSpacing`,`letter-spacing`],[`lightingColor`,`lighting-color`],[`markerEnd`,`marker-end`],[`markerMid`,`marker-mid`],[`markerStart`,`marker-start`],[`overlinePosition`,`overline-position`],[`overlineThickness`,`overline-thickness`],[`paintOrder`,`paint-order`],[`panose-1`,`panose-1`],[`pointerEvents`,`pointer-events`],[`renderingIntent`,`rendering-intent`],[`shapeRendering`,`shape-rendering`],[`stopColor`,`stop-color`],[`stopOpacity`,`stop-opacity`],[`strikethroughPosition`,`strikethrough-position`],[`strikethroughThickness`,`strikethrough-thickness`],[`strokeDasharray`,`stroke-dasharray`],[`strokeDashoffset`,`stroke-dashoffset`],[`strokeLinecap`,`stroke-linecap`],[`strokeLinejoin`,`stroke-linejoin`],[`strokeMiterlimit`,`stroke-miterlimit`],[`strokeOpacity`,`stroke-opacity`],[`strokeWidth`,`stroke-width`],[`textAnchor`,`text-anchor`],[`textDecoration`,`text-decoration`],[`textRendering`,`text-rendering`],[`transformOrigin`,`transform-origin`],[`underlinePosition`,`underline-position`],[`underlineThickness`,`underline-thickness`],[`unicodeBidi`,`unicode-bidi`],[`unicodeRange`,`unicode-range`],[`unitsPerEm`,`units-per-em`],[`vAlphabetic`,`v-alphabetic`],[`vHanging`,`v-hanging`],[`vIdeographic`,`v-ideographic`],[`vMathematical`,`v-mathematical`],[`vectorEffect`,`vector-effect`],[`vertAdvY`,`vert-adv-y`],[`vertOriginX`,`vert-origin-x`],[`vertOriginY`,`vert-origin-y`],[`wordSpacing`,`word-spacing`],[`writingMode`,`writing-mode`],[`xmlnsXlink`,`xmlns:xlink`],[`xHeight`,`x-height`]]),cn=/^[\u0000-\u001F ]*j[\r\n\t]*a[\r\n\t]*v[\r\n\t]*a[\r\n\t]*s[\r\n\t]*c[\r\n\t]*r[\r\n\t]*i[\r\n\t]*p[\r\n\t]*t[\r\n\t]*:/i;function ln(e){return cn.test(``+e)?`javascript:throw new Error('React has blocked a javascript: URL as a security precaution.')`:e}function un(){}var dn=null;function fn(e){return e=e.target||e.srcElement||window,e.correspondingUseElement&&(e=e.correspondingUseElement),e.nodeType===3?e.parentNode:e}var pn=null,mn=null;function hn(e){var t=Et(e);if(t&&(e=t.stateNode)){var n=e[_t]||null;a:switch(e=t.stateNode,t.type){case`input`:if(Yt(e,n.value,n.defaultValue,n.defaultValue,n.checked,n.defaultChecked,n.type,n.name),t=n.name,n.type===`radio`&&t!=null){for(n=e;n.parentNode;)n=n.parentNode;for(n=n.querySelectorAll(`input[name="`+Jt(``+t)+`"][type="radio"]`),t=0;t<n.length;t++){var r=n[t];if(r!==e&&r.form===e.form){var a=r[_t]||null;if(!a)throw Error(i(90));Yt(r,a.value,a.defaultValue,a.defaultValue,a.checked,a.defaultChecked,a.type,a.name)}}for(t=0;t<n.length;t++)r=n[t],r.form===e.form&&Gt(r)}break a;case`textarea`:$t(e,n.value,n.defaultValue);break a;case`select`:t=n.value,t!=null&&Qt(e,!!n.multiple,t,!1)}}}var gn=!1;function _n(e,t,n){if(gn)return e(t,n);gn=!0;try{return e(t)}finally{if(gn=!1,(pn!==null||mn!==null)&&(Lu(),pn&&(t=pn,e=mn,mn=pn=null,hn(t),e)))for(t=0;t<e.length;t++)hn(e[t])}}function vn(e,t){var n=e.stateNode;if(n===null)return null;var r=n[_t]||null;if(r===null)return null;n=r[t];a:switch(t){case`onClick`:case`onClickCapture`:case`onDoubleClick`:case`onDoubleClickCapture`:case`onMouseDown`:case`onMouseDownCapture`:case`onMouseMove`:case`onMouseMoveCapture`:case`onMouseUp`:case`onMouseUpCapture`:case`onMouseEnter`:(r=!r.disabled)||(e=e.type,r=e!==`button`&&e!==`input`&&e!==`select`&&e!==`textarea`),e=!r;break a;default:e=!1}if(e)return null;if(n&&typeof n!=`function`)throw Error(i(231,t,typeof n));return n}var yn=!(typeof window>`u`||window.document===void 0||window.document.createElement===void 0),bn=!1;if(yn)try{var xn={};Object.defineProperty(xn,"passive",{get:function(){bn=!0}}),window.addEventListener(`test`,xn,xn),window.removeEventListener(`test`,xn,xn)}catch{bn=!1}var Sn=null,Cn=null,wn=null;function Tn(){if(wn)return wn;var e,t=Cn,n=t.length,r,i=`value`in Sn?Sn.value:Sn.textContent,a=i.length;for(e=0;e<n&&t[e]===i[e];e++);var o=n-e;for(r=1;r<=o&&t[n-r]===i[a-r];r++);return wn=i.slice(e,1<r?1-r:void 0)}function En(e){var t=e.keyCode;return`charCode`in e?(e=e.charCode,e===0&&t===13&&(e=13)):e=t,e===10&&(e=13),32<=e||e===13?e:0}function Dn(){return!0}function On(){return!1}function kn(e){function t(t,n,r,i,a){for(var o in this._reactName=t,this._targetInst=r,this.type=n,this.nativeEvent=i,this.target=a,this.currentTarget=null,e)e.hasOwnProperty(o)&&(t=e[o],this[o]=t?t(i):i[o]);return this.isDefaultPrevented=(i.defaultPrevented==null?!1===i.returnValue:i.defaultPrevented)?Dn:On,this.isPropagationStopped=On,this}return h(t.prototype,{preventDefault:function(){this.defaultPrevented=!0;var e=this.nativeEvent;e&&(e.preventDefault?e.preventDefault():typeof e.returnValue!=`unknown`&&(e.returnValue=!1),this.isDefaultPrevented=Dn)},stopPropagation:function(){var e=this.nativeEvent;e&&(e.stopPropagation?e.stopPropagation():typeof e.cancelBubble!=`unknown`&&(e.cancelBubble=!0),this.isPropagationStopped=Dn)},persist:function(){},isPersistent:Dn}),t}var An={eventPhase:0,bubbles:0,cancelable:0,timeStamp:function(e){return e.timeStamp||Date.now()},defaultPrevented:0,isTrusted:0},jn=kn(An),Mn=h({},An,{view:0,detail:0}),Nn=kn(Mn),Pn,Fn,In,Ln=h({},Mn,{screenX:0,screenY:0,clientX:0,clientY:0,pageX:0,pageY:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,getModifierState:Jn,button:0,buttons:0,relatedTarget:function(e){return e.relatedTarget===void 0?e.fromElement===e.srcElement?e.toElement:e.fromElement:e.relatedTarget},movementX:function(e){return`movementX`in e?e.movementX:(e!==In&&(In&&e.type===`mousemove`?(Pn=e.screenX-In.screenX,Fn=e.screenY-In.screenY):Fn=Pn=0,In=e),Pn)},movementY:function(e){return`movementY`in e?e.movementY:Fn}}),Rn=kn(Ln),zn=kn(h({},Ln,{dataTransfer:0})),Bn=kn(h({},Mn,{relatedTarget:0})),Vn=kn(h({},An,{animationName:0,elapsedTime:0,pseudoElement:0})),Hn=kn(h({},An,{clipboardData:function(e){return`clipboardData`in e?e.clipboardData:window.clipboardData}})),Un=kn(h({},An,{data:0})),Wn={Esc:`Escape`,Spacebar:` `,Left:`ArrowLeft`,Up:`ArrowUp`,Right:`ArrowRight`,Down:`ArrowDown`,Del:`Delete`,Win:`OS`,Menu:`ContextMenu`,Apps:`ContextMenu`,Scroll:`ScrollLock`,MozPrintableKey:`Unidentified`},Gn={8:`Backspace`,9:`Tab`,12:`Clear`,13:`Enter`,16:`Shift`,17:`Control`,18:`Alt`,19:`Pause`,20:`CapsLock`,27:`Escape`,32:` `,33:`PageUp`,34:`PageDown`,35:`End`,36:`Home`,37:`ArrowLeft`,38:`ArrowUp`,39:`ArrowRight`,40:`ArrowDown`,45:`Insert`,46:`Delete`,112:`F1`,113:`F2`,114:`F3`,115:`F4`,116:`F5`,117:`F6`,118:`F7`,119:`F8`,120:`F9`,121:`F10`,122:`F11`,123:`F12`,144:`NumLock`,145:`ScrollLock`,224:`Meta`},Kn={Alt:`altKey`,Control:`ctrlKey`,Meta:`metaKey`,Shift:`shiftKey`};function qn(e){var t=this.nativeEvent;return t.getModifierState?t.getModifierState(e):(e=Kn[e])?!!t[e]:!1}function Jn(){return qn}var Yn=kn(h({},Mn,{key:function(e){if(e.key){var t=Wn[e.key]||e.key;if(t!==`Unidentified`)return t}return e.type===`keypress`?(e=En(e),e===13?`Enter`:String.fromCharCode(e)):e.type===`keydown`||e.type===`keyup`?Gn[e.keyCode]||`Unidentified`:``},code:0,location:0,ctrlKey:0,shiftKey:0,altKey:0,metaKey:0,repeat:0,locale:0,getModifierState:Jn,charCode:function(e){return e.type===`keypress`?En(e):0},keyCode:function(e){return e.type===`keydown`||e.type===`keyup`?e.keyCode:0},which:function(e){return e.type===`keypress`?En(e):e.type===`keydown`||e.type===`keyup`?e.keyCode:0}})),Xn=kn(h({},Ln,{pointerId:0,width:0,height:0,pressure:0,tangentialPressure:0,tiltX:0,tiltY:0,twist:0,pointerType:0,isPrimary:0})),Zn=kn(h({},Mn,{touches:0,targetTouches:0,changedTouches:0,altKey:0,metaKey:0,ctrlKey:0,shiftKey:0,getModifierState:Jn})),Qn=kn(h({},An,{propertyName:0,elapsedTime:0,pseudoElement:0})),$n=kn(h({},Ln,{deltaX:function(e){return`deltaX`in e?e.deltaX:`wheelDeltaX`in e?-e.wheelDeltaX:0},deltaY:function(e){return`deltaY`in e?e.deltaY:`wheelDeltaY`in e?-e.wheelDeltaY:`wheelDelta`in e?-e.wheelDelta:0},deltaZ:0,deltaMode:0})),er=kn(h({},An,{newState:0,oldState:0})),tr=[9,13,27,32],nr=yn&&`CompositionEvent`in window,rr=null;yn&&`documentMode`in document&&(rr=document.documentMode);var ir=yn&&`TextEvent`in window&&!rr,ar=yn&&(!nr||rr&&8<rr&&11>=rr),or=` `,sr=!1;function cr(e,t){switch(e){case`keyup`:return tr.indexOf(t.keyCode)!==-1;case`keydown`:return t.keyCode!==229;case`keypress`:case`mousedown`:case`focusout`:return!0;default:return!1}}function lr(e){return e=e.detail,typeof e==`object`&&`data`in e?e.data:null}var ur=!1;function dr(e,t){switch(e){case`compositionend`:return lr(t);case`keypress`:return t.which===32?(sr=!0,or):null;case`textInput`:return e=t.data,e===or&&sr?null:e;default:return null}}function fr(e,t){if(ur)return e===`compositionend`||!nr&&cr(e,t)?(e=Tn(),wn=Cn=Sn=null,ur=!1,e):null;switch(e){case`paste`:return null;case`keypress`:if(!(t.ctrlKey||t.altKey||t.metaKey)||t.ctrlKey&&t.altKey){if(t.char&&1<t.char.length)return t.char;if(t.which)return String.fromCharCode(t.which)}return null;case`compositionend`:return ar&&t.locale!==`ko`?null:t.data;default:return null}}var pr={color:!0,date:!0,datetime:!0,"datetime-local":!0,email:!0,month:!0,number:!0,password:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0};function mr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t===`input`?!!pr[e.type]:t===`textarea`}function hr(e,t,n,r){pn?mn?mn.push(r):mn=[r]:pn=r,t=Gd(t,`onChange`),0<t.length&&(n=new jn(`onChange`,`change`,null,n,r),e.push({event:n,listeners:t}))}var gr=null,_r=null;function vr(e){Ld(e,0)}function yr(e){if(Gt(Dt(e)))return e}function br(e,t){if(e===`change`)return t}var xr=!1;if(yn){var Sr;if(yn){var Cr=`oninput`in document;if(!Cr){var wr=document.createElement(`div`);wr.setAttribute(`oninput`,`return;`),Cr=typeof wr.oninput==`function`}Sr=Cr}else Sr=!1;xr=Sr&&(!document.documentMode||9<document.documentMode)}function Tr(){gr&&(gr.detachEvent(`onpropertychange`,Er),_r=gr=null)}function Er(e){if(e.propertyName===`value`&&yr(_r)){var t=[];hr(t,_r,e,fn(e)),_n(vr,t)}}function Dr(e,t,n){e===`focusin`?(Tr(),gr=t,_r=n,gr.attachEvent(`onpropertychange`,Er)):e===`focusout`&&Tr()}function Or(e){if(e===`selectionchange`||e===`keyup`||e===`keydown`)return yr(_r)}function kr(e,t){if(e===`click`)return yr(t)}function Ar(e,t){if(e===`input`||e===`change`)return yr(t)}function jr(e,t){return e===t&&(e!==0||1/e==1/t)||e!==e&&t!==t}var Mr=typeof Object.is==`function`?Object.is:jr;function Nr(e,t){if(Mr(e,t))return!0;if(typeof e!=`object`||!e||typeof t!=`object`||!t)return!1;var n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(r=0;r<n.length;r++){var i=n[r];if(!Ae.call(t,i)||!Mr(e[i],t[i]))return!1}return!0}function Pr(e){for(;e&&e.firstChild;)e=e.firstChild;return e}function Fr(e,t){var n=Pr(e);e=0;for(var r;n;){if(n.nodeType===3){if(r=e+n.textContent.length,e<=t&&r>=t)return{node:n,offset:t-e};e=r}a:{for(;n;){if(n.nextSibling){n=n.nextSibling;break a}n=n.parentNode}n=void 0}n=Pr(n)}}function Ir(e,t){return e&&t?e===t?!0:e&&e.nodeType===3?!1:t&&t.nodeType===3?Ir(e,t.parentNode):`contains`in e?e.contains(t):e.compareDocumentPosition?!!(e.compareDocumentPosition(t)&16):!1:!1}function Lr(e){e=e!=null&&e.ownerDocument!=null&&e.ownerDocument.defaultView!=null?e.ownerDocument.defaultView:window;for(var t=Kt(e.document);t instanceof e.HTMLIFrameElement;){try{var n=typeof t.contentWindow.location.href==`string`}catch{n=!1}if(n)e=t.contentWindow;else break;t=Kt(e.document)}return t}function Rr(e){var t=e&&e.nodeName&&e.nodeName.toLowerCase();return t&&(t===`input`&&(e.type===`text`||e.type===`search`||e.type===`tel`||e.type===`url`||e.type===`password`)||t===`textarea`||e.contentEditable===`true`)}var zr=yn&&`documentMode`in document&&11>=document.documentMode,Br=null,Vr=null,Hr=null,Ur=!1;function Wr(e,t,n){var r=n.window===n?n.document:n.nodeType===9?n:n.ownerDocument;Ur||Br==null||Br!==Kt(r)||(r=Br,`selectionStart`in r&&Rr(r)?r={start:r.selectionStart,end:r.selectionEnd}:(r=(r.ownerDocument&&r.ownerDocument.defaultView||window).getSelection(),r={anchorNode:r.anchorNode,anchorOffset:r.anchorOffset,focusNode:r.focusNode,focusOffset:r.focusOffset}),Hr&&Nr(Hr,r)||(Hr=r,r=Gd(Vr,`onSelect`),0<r.length&&(t=new jn(`onSelect`,`select`,null,t,n),e.push({event:t,listeners:r}),t.target=Br)))}function Gr(e,t){var n={};return n[e.toLowerCase()]=t.toLowerCase(),n[`Webkit`+e]=`webkit`+t,n[`Moz`+e]=`moz`+t,n}var Kr={animationend:Gr(`Animation`,`AnimationEnd`),animationiteration:Gr(`Animation`,`AnimationIteration`),animationstart:Gr(`Animation`,`AnimationStart`),transitionrun:Gr(`Transition`,`TransitionRun`),transitionstart:Gr(`Transition`,`TransitionStart`),transitioncancel:Gr(`Transition`,`TransitionCancel`),transitionend:Gr(`Transition`,`TransitionEnd`)},qr={},Jr={};yn&&(Jr=document.createElement(`div`).style,`AnimationEvent`in window||(delete Kr.animationend.animation,delete Kr.animationiteration.animation,delete Kr.animationstart.animation),`TransitionEvent`in window||delete Kr.transitionend.transition);function Yr(e){if(qr[e])return qr[e];if(!Kr[e])return e;var t=Kr[e],n;for(n in t)if(t.hasOwnProperty(n)&&n in Jr)return qr[e]=t[n];return e}var Xr=Yr(`animationend`),Zr=Yr(`animationiteration`),Qr=Yr(`animationstart`),$r=Yr(`transitionrun`),ei=Yr(`transitionstart`),ti=Yr(`transitioncancel`),ni=Yr(`transitionend`),ri=new Map,ii=`abort auxClick beforeToggle cancel canPlay canPlayThrough click close contextMenu copy cut drag dragEnd dragEnter dragExit dragLeave dragOver dragStart drop durationChange emptied encrypted ended error gotPointerCapture input invalid keyDown keyPress keyUp load loadedData loadedMetadata loadStart lostPointerCapture mouseDown mouseMove mouseOut mouseOver mouseUp paste pause play playing pointerCancel pointerDown pointerMove pointerOut pointerOver pointerUp progress rateChange reset resize seeked seeking stalled submit suspend timeUpdate touchCancel touchEnd touchStart volumeChange scroll toggle touchMove waiting wheel`.split(` `);ii.push(`scrollEnd`);function ai(e,t){ri.set(e,t),Mt(t,[e])}var oi=typeof reportError==`function`?reportError:function(e){if(typeof window==`object`&&typeof window.ErrorEvent==`function`){var t=new window.ErrorEvent(`error`,{bubbles:!0,cancelable:!0,message:typeof e==`object`&&e&&typeof e.message==`string`?String(e.message):String(e),error:e});if(!window.dispatchEvent(t))return}else if(typeof process==`object`&&typeof process.emit==`function`){process.emit(`uncaughtException`,e);return}console.error(e)},si=[],ci=0,li=0;function ui(){for(var e=ci,t=li=ci=0;t<e;){var n=si[t];si[t++]=null;var r=si[t];si[t++]=null;var i=si[t];si[t++]=null;var a=si[t];if(si[t++]=null,r!==null&&i!==null){var o=r.pending;o===null?i.next=i:(i.next=o.next,o.next=i),r.pending=i}a!==0&&mi(n,i,a)}}function di(e,t,n,r){si[ci++]=e,si[ci++]=t,si[ci++]=n,si[ci++]=r,li|=r,e.lanes|=r,e=e.alternate,e!==null&&(e.lanes|=r)}function fi(e,t,n,r){return di(e,t,n,r),hi(e)}function pi(e,t){return di(e,null,null,t),hi(e)}function mi(e,t,n){e.lanes|=n;var r=e.alternate;r!==null&&(r.lanes|=n);for(var i=!1,a=e.return;a!==null;)a.childLanes|=n,r=a.alternate,r!==null&&(r.childLanes|=n),a.tag===22&&(e=a.stateNode,e===null||e._visibility&1||(i=!0)),e=a,a=a.return;return e.tag===3?(a=e.stateNode,i&&t!==null&&(i=31-qe(n),e=a.hiddenUpdates,r=e[i],r===null?e[i]=[t]:r.push(t),t.lane=n|536870912),a):null}function hi(e){if(50<Ou)throw Ou=0,ku=null,Error(i(185));for(var t=e.return;t!==null;)e=t,t=e.return;return e.tag===3?e.stateNode:null}var gi={};function _i(e,t,n,r){this.tag=e,this.key=n,this.sibling=this.child=this.return=this.stateNode=this.type=this.elementType=null,this.index=0,this.refCleanup=this.ref=null,this.pendingProps=t,this.dependencies=this.memoizedState=this.updateQueue=this.memoizedProps=null,this.mode=r,this.subtreeFlags=this.flags=0,this.deletions=null,this.childLanes=this.lanes=0,this.alternate=null}function vi(e,t,n,r){return new _i(e,t,n,r)}function yi(e){return e=e.prototype,!(!e||!e.isReactComponent)}function bi(e,t){var n=e.alternate;return n===null?(n=vi(e.tag,t,e.key,e.mode),n.elementType=e.elementType,n.type=e.type,n.stateNode=e.stateNode,n.alternate=e,e.alternate=n):(n.pendingProps=t,n.type=e.type,n.flags=0,n.subtreeFlags=0,n.deletions=null),n.flags=e.flags&65011712,n.childLanes=e.childLanes,n.lanes=e.lanes,n.child=e.child,n.memoizedProps=e.memoizedProps,n.memoizedState=e.memoizedState,n.updateQueue=e.updateQueue,t=e.dependencies,n.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext},n.sibling=e.sibling,n.index=e.index,n.ref=e.ref,n.refCleanup=e.refCleanup,n}function xi(e,t){e.flags&=65011714;var n=e.alternate;return n===null?(e.childLanes=0,e.lanes=t,e.child=null,e.subtreeFlags=0,e.memoizedProps=null,e.memoizedState=null,e.updateQueue=null,e.dependencies=null,e.stateNode=null):(e.childLanes=n.childLanes,e.lanes=n.lanes,e.child=n.child,e.subtreeFlags=0,e.deletions=null,e.memoizedProps=n.memoizedProps,e.memoizedState=n.memoizedState,e.updateQueue=n.updateQueue,e.type=n.type,t=n.dependencies,e.dependencies=t===null?null:{lanes:t.lanes,firstContext:t.firstContext}),e}function Si(e,t,n,r,a,o){var s=0;if(r=e,typeof e==`function`)yi(e)&&(s=1);else if(typeof e==`string`)s=cp(e,n,he.current)?26:e===`html`||e===`head`||e===`body`?27:5;else a:switch(e){case re:return e=vi(31,n,t,a),e.elementType=re,e.lanes=o,e;case y:return Ci(n.children,a,o,t);case b:s=8,a|=24;break;case x:return e=vi(12,n,t,a|2),e.elementType=x,e.lanes=o,e;case T:return e=vi(13,n,t,a),e.elementType=T,e.lanes=o,e;case ee:return e=vi(19,n,t,a),e.elementType=ee,e.lanes=o,e;default:if(typeof e==`object`&&e)switch(e.$$typeof){case C:s=10;break a;case S:s=9;break a;case w:s=11;break a;case te:s=14;break a;case ne:s=16,r=null;break a}s=29,n=Error(i(130,e===null?`null`:typeof e,``)),r=null}return t=vi(s,n,t,a),t.elementType=e,t.type=r,t.lanes=o,t}function Ci(e,t,n,r){return e=vi(7,e,r,t),e.lanes=n,e}function wi(e,t,n){return e=vi(6,e,null,t),e.lanes=n,e}function Ti(e){var t=vi(18,null,null,0);return t.stateNode=e,t}function Ei(e,t,n){return t=vi(4,e.children===null?[]:e.children,e.key,t),t.lanes=n,t.stateNode={containerInfo:e.containerInfo,pendingChildren:null,implementation:e.implementation},t}var Di=new WeakMap;function Oi(e,t){if(typeof e==`object`&&e){var n=Di.get(e);return n===void 0?(t={value:e,source:t,stack:ke(t)},Di.set(e,t),t):n}return{value:e,source:t,stack:ke(t)}}var ki=[],Ai=0,ji=null,Mi=0,Ni=[],Pi=0,Fi=null,Ii=1,Li=``;function Ri(e,t){ki[Ai++]=Mi,ki[Ai++]=ji,ji=e,Mi=t}function zi(e,t,n){Ni[Pi++]=Ii,Ni[Pi++]=Li,Ni[Pi++]=Fi,Fi=e;var r=Ii;e=Li;var i=32-qe(r)-1;r&=~(1<<i),n+=1;var a=32-qe(t)+i;if(30<a){var o=i-i%5;a=(r&(1<<o)-1).toString(32),r>>=o,i-=o,Ii=1<<32-qe(t)+i|n<<i|r,Li=a+e}else Ii=1<<a|n<<i|r,Li=e}function Bi(e){e.return!==null&&(Ri(e,1),zi(e,1,0))}function Vi(e){for(;e===ji;)ji=ki[--Ai],ki[Ai]=null,Mi=ki[--Ai],ki[Ai]=null;for(;e===Fi;)Fi=Ni[--Pi],Ni[Pi]=null,Li=Ni[--Pi],Ni[Pi]=null,Ii=Ni[--Pi],Ni[Pi]=null}function Hi(e,t){Ni[Pi++]=Ii,Ni[Pi++]=Li,Ni[Pi++]=Fi,Ii=t.id,Li=t.overflow,Fi=e}var Ui=null,k=null,Wi=!1,Gi=null,Ki=!1,qi=Error(i(519));function Ji(e){throw ea(Oi(Error(i(418,1<arguments.length&&arguments[1]!==void 0&&arguments[1]?`text`:`HTML`,``)),e)),qi}function Yi(e){var t=e.stateNode,n=e.type,r=e.memoizedProps;switch(t[gt]=e,t[_t]=r,n){case`dialog`:Rd(`cancel`,t),Rd(`close`,t);break;case`iframe`:case`object`:case`embed`:Rd(`load`,t);break;case`video`:case`audio`:for(n=0;n<Fd.length;n++)Rd(Fd[n],t);break;case`source`:Rd(`error`,t);break;case`img`:case`image`:case`link`:Rd(`error`,t),Rd(`load`,t);break;case`details`:Rd(`toggle`,t);break;case`input`:Rd(`invalid`,t),Xt(t,r.value,r.defaultValue,r.checked,r.defaultChecked,r.type,r.name,!0);break;case`select`:Rd(`invalid`,t);break;case`textarea`:Rd(`invalid`,t),en(t,r.value,r.defaultValue,r.children)}n=r.children,typeof n!=`string`&&typeof n!=`number`&&typeof n!=`bigint`||t.textContent===``+n||!0===r.suppressHydrationWarning||Zd(t.textContent,n)?(r.popover!=null&&(Rd(`beforetoggle`,t),Rd(`toggle`,t)),r.onScroll!=null&&Rd(`scroll`,t),r.onScrollEnd!=null&&Rd(`scrollend`,t),r.onClick!=null&&(t.onclick=un),t=!0):t=!1,t||Ji(e,!0)}function Xi(e){for(Ui=e.return;Ui;)switch(Ui.tag){case 5:case 31:case 13:Ki=!1;return;case 27:case 3:Ki=!0;return;default:Ui=Ui.return}}function Zi(e){if(e!==Ui)return!1;if(!Wi)return Xi(e),Wi=!0,!1;var t=e.tag,n;if((n=t!==3&&t!==27)&&((n=t===5)&&(n=e.type,n=n===`form`||n===`button`||uf(e.type,e.memoizedProps)),n=!n),n&&k&&Ji(e),Xi(e),t===13){if(e=e.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(317));k=Af(e)}else if(t===31){if(e=e.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(317));k=Af(e)}else t===27?(t=k,vf(e.type)?(e=kf,kf=null,k=e):k=t):k=Ui?Of(e.stateNode.nextSibling):null;return!0}function Qi(){k=Ui=null,Wi=!1}function $i(){var e=Gi;return e!==null&&(mu===null?mu=e:mu.push.apply(mu,e),Gi=null),e}function ea(e){Gi===null?Gi=[e]:Gi.push(e)}var ta=fe(null),na=null,ra=null;function ia(e,t,n){me(ta,t._currentValue),t._currentValue=n}function aa(e){e._currentValue=ta.current,pe(ta)}function oa(e,t,n){for(;e!==null;){var r=e.alternate;if((e.childLanes&t)===t?r!==null&&(r.childLanes&t)!==t&&(r.childLanes|=t):(e.childLanes|=t,r!==null&&(r.childLanes|=t)),e===n)break;e=e.return}}function sa(e,t,n,r){var a=e.child;for(a!==null&&(a.return=e);a!==null;){var o=a.dependencies;if(o!==null){var s=a.child;o=o.firstContext;a:for(;o!==null;){var c=o;o=a;for(var l=0;l<t.length;l++)if(c.context===t[l]){o.lanes|=n,c=o.alternate,c!==null&&(c.lanes|=n),oa(o.return,n,e),r||(s=null);break a}o=c.next}}else if(a.tag===18){if(s=a.return,s===null)throw Error(i(341));s.lanes|=n,o=s.alternate,o!==null&&(o.lanes|=n),oa(s,n,e),s=null}else s=a.child;if(s!==null)s.return=a;else for(s=a;s!==null;){if(s===e){s=null;break}if(a=s.sibling,a!==null){a.return=s.return,s=a;break}s=s.return}a=s}}function ca(e,t,n,r){e=null;for(var a=t,o=!1;a!==null;){if(!o){if(a.flags&524288)o=!0;else if(a.flags&262144)break}if(a.tag===10){var s=a.alternate;if(s===null)throw Error(i(387));if(s=s.memoizedProps,s!==null){var c=a.type;Mr(a.pendingProps.value,s.value)||(e===null?e=[c]:e.push(c))}}else if(a===ve.current){if(s=a.alternate,s===null)throw Error(i(387));s.memoizedState.memoizedState!==a.memoizedState.memoizedState&&(e===null?e=[mp]:e.push(mp))}a=a.return}e!==null&&sa(t,e,n,r),t.flags|=262144}function la(e){for(e=e.firstContext;e!==null;){if(!Mr(e.context._currentValue,e.memoizedValue))return!0;e=e.next}return!1}function ua(e){na=e,ra=null,e=e.dependencies,e!==null&&(e.firstContext=null)}function da(e){return pa(na,e)}function fa(e,t){return na===null&&ua(e),pa(e,t)}function pa(e,t){var n=t._currentValue;if(t={context:t,memoizedValue:n,next:null},ra===null){if(e===null)throw Error(i(308));ra=t,e.dependencies={lanes:0,firstContext:t},e.flags|=524288}else ra=ra.next=t;return n}var ma=typeof AbortController<`u`?AbortController:function(){var e=[],t=this.signal={aborted:!1,addEventListener:function(t,n){e.push(n)}};this.abort=function(){t.aborted=!0,e.forEach(function(e){return e()})}},ha=t.unstable_scheduleCallback,ga=t.unstable_NormalPriority,_a={$$typeof:C,Consumer:null,Provider:null,_currentValue:null,_currentValue2:null,_threadCount:0};function va(){return{controller:new ma,data:new Map,refCount:0}}function ya(e){e.refCount--,e.refCount===0&&ha(ga,function(){e.controller.abort()})}var ba=null,xa=0,Sa=0,Ca=null;function wa(e,t){if(ba===null){var n=ba=[];xa=0,Sa=kd(),Ca={status:`pending`,value:void 0,then:function(e){n.push(e)}}}return xa++,t.then(Ta,Ta),t}function Ta(){if(--xa===0&&ba!==null){Ca!==null&&(Ca.status=`fulfilled`);var e=ba;ba=null,Sa=0,Ca=null;for(var t=0;t<e.length;t++)(0,e[t])()}}function Ea(e,t){var n=[],r={status:`pending`,value:null,reason:null,then:function(e){n.push(e)}};return e.then(function(){r.status=`fulfilled`,r.value=t;for(var e=0;e<n.length;e++)(0,n[e])(t)},function(e){for(r.status=`rejected`,r.reason=e,e=0;e<n.length;e++)(0,n[e])(void 0)}),r}var Da=O.S;O.S=function(e,t){_u=Fe(),typeof t==`object`&&t&&typeof t.then==`function`&&wa(e,t),Da!==null&&Da(e,t)};var Oa=fe(null);function A(){var e=Oa.current;return e===null?Ql.pooledCache:e}function ka(e,t){t===null?me(Oa,Oa.current):me(Oa,t.pool)}function Aa(){var e=A();return e===null?null:{parent:_a._currentValue,pool:e}}var j=Error(i(460)),ja=Error(i(474)),Ma=Error(i(542)),Na={then:function(){}};function Pa(e){return e=e.status,e===`fulfilled`||e===`rejected`}function Fa(e,t,n){switch(n=e[n],n===void 0?e.push(t):n!==t&&(t.then(un,un),t=n),t.status){case`fulfilled`:return t.value;case`rejected`:throw e=t.reason,za(e),e;default:if(typeof t.status==`string`)t.then(un,un);else{if(e=Ql,e!==null&&100<e.shellSuspendCounter)throw Error(i(482));e=t,e.status=`pending`,e.then(function(e){if(t.status===`pending`){var n=t;n.status=`fulfilled`,n.value=e}},function(e){if(t.status===`pending`){var n=t;n.status=`rejected`,n.reason=e}})}switch(t.status){case`fulfilled`:return t.value;case`rejected`:throw e=t.reason,za(e),e}throw La=t,j}}function Ia(e){try{var t=e._init;return t(e._payload)}catch(e){throw typeof e==`object`&&e&&typeof e.then==`function`?(La=e,j):e}}var La=null;function Ra(){if(La===null)throw Error(i(459));var e=La;return La=null,e}function za(e){if(e===j||e===Ma)throw Error(i(483))}var Ba=null,Va=0;function Ha(e){var t=Va;return Va+=1,Ba===null&&(Ba=[]),Fa(Ba,e,t)}function Ua(e,t){t=t.props.ref,e.ref=t===void 0?null:t}function Wa(e,t){throw t.$$typeof===g?Error(i(525)):(e=Object.prototype.toString.call(t),Error(i(31,e===`[object Object]`?`object with keys {`+Object.keys(t).join(`, `)+`}`:e)))}function Ga(e){function t(t,n){if(e){var r=t.deletions;r===null?(t.deletions=[n],t.flags|=16):r.push(n)}}function n(n,r){if(!e)return null;for(;r!==null;)t(n,r),r=r.sibling;return null}function r(e){for(var t=new Map;e!==null;)e.key===null?t.set(e.index,e):t.set(e.key,e),e=e.sibling;return t}function a(e,t){return e=bi(e,t),e.index=0,e.sibling=null,e}function o(t,n,r){return t.index=r,e?(r=t.alternate,r===null?(t.flags|=67108866,n):(r=r.index,r<n?(t.flags|=67108866,n):r)):(t.flags|=1048576,n)}function s(t){return e&&t.alternate===null&&(t.flags|=67108866),t}function c(e,t,n,r){return t===null||t.tag!==6?(t=wi(n,e.mode,r),t.return=e,t):(t=a(t,n),t.return=e,t)}function l(e,t,n,r){var i=n.type;return i===y?d(e,t,n.props.children,r,n.key):t!==null&&(t.elementType===i||typeof i==`object`&&i&&i.$$typeof===ne&&Ia(i)===t.type)?(t=a(t,n.props),Ua(t,n),t.return=e,t):(t=Si(n.type,n.key,n.props,null,e.mode,r),Ua(t,n),t.return=e,t)}function u(e,t,n,r){return t===null||t.tag!==4||t.stateNode.containerInfo!==n.containerInfo||t.stateNode.implementation!==n.implementation?(t=Ei(n,e.mode,r),t.return=e,t):(t=a(t,n.children||[]),t.return=e,t)}function d(e,t,n,r,i){return t===null||t.tag!==7?(t=Ci(n,e.mode,r,i),t.return=e,t):(t=a(t,n),t.return=e,t)}function f(e,t,n){if(typeof t==`string`&&t!==``||typeof t==`number`||typeof t==`bigint`)return t=wi(``+t,e.mode,n),t.return=e,t;if(typeof t==`object`&&t){switch(t.$$typeof){case _:return n=Si(t.type,t.key,t.props,null,e.mode,n),Ua(n,t),n.return=e,n;case v:return t=Ei(t,e.mode,n),t.return=e,t;case ne:return t=Ia(t),f(e,t,n)}if(se(t)||D(t))return t=Ci(t,e.mode,n,null),t.return=e,t;if(typeof t.then==`function`)return f(e,Ha(t),n);if(t.$$typeof===C)return f(e,fa(e,t),n);Wa(e,t)}return null}function p(e,t,n,r){var i=t===null?null:t.key;if(typeof n==`string`&&n!==``||typeof n==`number`||typeof n==`bigint`)return i===null?c(e,t,``+n,r):null;if(typeof n==`object`&&n){switch(n.$$typeof){case _:return n.key===i?l(e,t,n,r):null;case v:return n.key===i?u(e,t,n,r):null;case ne:return n=Ia(n),p(e,t,n,r)}if(se(n)||D(n))return i===null?d(e,t,n,r,null):null;if(typeof n.then==`function`)return p(e,t,Ha(n),r);if(n.$$typeof===C)return p(e,t,fa(e,n),r);Wa(e,n)}return null}function m(e,t,n,r,i){if(typeof r==`string`&&r!==``||typeof r==`number`||typeof r==`bigint`)return e=e.get(n)||null,c(t,e,``+r,i);if(typeof r==`object`&&r){switch(r.$$typeof){case _:return e=e.get(r.key===null?n:r.key)||null,l(t,e,r,i);case v:return e=e.get(r.key===null?n:r.key)||null,u(t,e,r,i);case ne:return r=Ia(r),m(e,t,n,r,i)}if(se(r)||D(r))return e=e.get(n)||null,d(t,e,r,i,null);if(typeof r.then==`function`)return m(e,t,n,Ha(r),i);if(r.$$typeof===C)return m(e,t,n,fa(t,r),i);Wa(t,r)}return null}function h(i,a,s,c){for(var l=null,u=null,d=a,h=a=0,g=null;d!==null&&h<s.length;h++){d.index>h?(g=d,d=null):g=d.sibling;var _=p(i,d,s[h],c);if(_===null){d===null&&(d=g);break}e&&d&&_.alternate===null&&t(i,d),a=o(_,a,h),u===null?l=_:u.sibling=_,u=_,d=g}if(h===s.length)return n(i,d),Wi&&Ri(i,h),l;if(d===null){for(;h<s.length;h++)d=f(i,s[h],c),d!==null&&(a=o(d,a,h),u===null?l=d:u.sibling=d,u=d);return Wi&&Ri(i,h),l}for(d=r(d);h<s.length;h++)g=m(d,i,h,s[h],c),g!==null&&(e&&g.alternate!==null&&d.delete(g.key===null?h:g.key),a=o(g,a,h),u===null?l=g:u.sibling=g,u=g);return e&&d.forEach(function(e){return t(i,e)}),Wi&&Ri(i,h),l}function g(a,s,c,l){if(c==null)throw Error(i(151));for(var u=null,d=null,h=s,g=s=0,_=null,v=c.next();h!==null&&!v.done;g++,v=c.next()){h.index>g?(_=h,h=null):_=h.sibling;var y=p(a,h,v.value,l);if(y===null){h===null&&(h=_);break}e&&h&&y.alternate===null&&t(a,h),s=o(y,s,g),d===null?u=y:d.sibling=y,d=y,h=_}if(v.done)return n(a,h),Wi&&Ri(a,g),u;if(h===null){for(;!v.done;g++,v=c.next())v=f(a,v.value,l),v!==null&&(s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return Wi&&Ri(a,g),u}for(h=r(h);!v.done;g++,v=c.next())v=m(h,a,g,v.value,l),v!==null&&(e&&v.alternate!==null&&h.delete(v.key===null?g:v.key),s=o(v,s,g),d===null?u=v:d.sibling=v,d=v);return e&&h.forEach(function(e){return t(a,e)}),Wi&&Ri(a,g),u}function b(e,r,o,c){if(typeof o==`object`&&o&&o.type===y&&o.key===null&&(o=o.props.children),typeof o==`object`&&o){switch(o.$$typeof){case _:a:{for(var l=o.key;r!==null;){if(r.key===l){if(l=o.type,l===y){if(r.tag===7){n(e,r.sibling),c=a(r,o.props.children),c.return=e,e=c;break a}}else if(r.elementType===l||typeof l==`object`&&l&&l.$$typeof===ne&&Ia(l)===r.type){n(e,r.sibling),c=a(r,o.props),Ua(c,o),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}o.type===y?(c=Ci(o.props.children,e.mode,c,o.key),c.return=e,e=c):(c=Si(o.type,o.key,o.props,null,e.mode,c),Ua(c,o),c.return=e,e=c)}return s(e);case v:a:{for(l=o.key;r!==null;){if(r.key===l){if(r.tag===4&&r.stateNode.containerInfo===o.containerInfo&&r.stateNode.implementation===o.implementation){n(e,r.sibling),c=a(r,o.children||[]),c.return=e,e=c;break a}n(e,r);break}t(e,r),r=r.sibling}c=Ei(o,e.mode,c),c.return=e,e=c}return s(e);case ne:return o=Ia(o),b(e,r,o,c)}if(se(o))return h(e,r,o,c);if(D(o)){if(l=D(o),typeof l!=`function`)throw Error(i(150));return o=l.call(o),g(e,r,o,c)}if(typeof o.then==`function`)return b(e,r,Ha(o),c);if(o.$$typeof===C)return b(e,r,fa(e,o),c);Wa(e,o)}return typeof o==`string`&&o!==``||typeof o==`number`||typeof o==`bigint`?(o=``+o,r!==null&&r.tag===6?(n(e,r.sibling),c=a(r,o),c.return=e,e=c):(n(e,r),c=wi(o,e.mode,c),c.return=e,e=c),s(e)):n(e,r)}return function(e,t,n,r){try{Va=0;var i=b(e,t,n,r);return Ba=null,i}catch(t){if(t===j||t===Ma)throw t;var a=vi(29,t,null,e.mode);return a.lanes=r,a.return=e,a}}}var Ka=Ga(!0),qa=Ga(!1),Ja=!1;function Ya(e){e.updateQueue={baseState:e.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Xa(e,t){e=e.updateQueue,t.updateQueue===e&&(t.updateQueue={baseState:e.baseState,firstBaseUpdate:e.firstBaseUpdate,lastBaseUpdate:e.lastBaseUpdate,shared:e.shared,callbacks:null})}function Za(e){return{lane:e,tag:0,payload:null,callback:null,next:null}}function M(e,t,n){var r=e.updateQueue;if(r===null)return null;if(r=r.shared,Zl&2){var i=r.pending;return i===null?t.next=t:(t.next=i.next,i.next=t),r.pending=t,t=hi(e),mi(e,null,n),t}return di(e,r,t,n),hi(e)}function Qa(e,t,n){if(t=t.updateQueue,t!==null&&(t=t.shared,n&4194048)){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,lt(e,n)}}function $a(e,t){var n=e.updateQueue,r=e.alternate;if(r!==null&&(r=r.updateQueue,n===r)){var i=null,a=null;if(n=n.firstBaseUpdate,n!==null){do{var o={lane:n.lane,tag:n.tag,payload:n.payload,callback:null,next:null};a===null?i=a=o:a=a.next=o,n=n.next}while(n!==null);a===null?i=a=t:a=a.next=t}else i=a=t;n={baseState:r.baseState,firstBaseUpdate:i,lastBaseUpdate:a,shared:r.shared,callbacks:r.callbacks},e.updateQueue=n;return}e=n.lastBaseUpdate,e===null?n.firstBaseUpdate=t:e.next=t,n.lastBaseUpdate=t}var eo=!1;function to(){if(eo){var e=Ca;if(e!==null)throw e}}function no(e,t,n,r){eo=!1;var i=e.updateQueue;Ja=!1;var a=i.firstBaseUpdate,o=i.lastBaseUpdate,s=i.shared.pending;if(s!==null){i.shared.pending=null;var c=s,l=c.next;c.next=null,o===null?a=l:o.next=l,o=c;var u=e.alternate;u!==null&&(u=u.updateQueue,s=u.lastBaseUpdate,s!==o&&(s===null?u.firstBaseUpdate=l:s.next=l,u.lastBaseUpdate=c))}if(a!==null){var d=i.baseState;o=0,u=l=c=null,s=a;do{var f=s.lane&-536870913,p=f!==s.lane;if(p?(eu&f)===f:(r&f)===f){f!==0&&f===Sa&&(eo=!0),u!==null&&(u=u.next={lane:0,tag:s.tag,payload:s.payload,callback:null,next:null});a:{var m=e,g=s;f=t;var _=n;switch(g.tag){case 1:if(m=g.payload,typeof m==`function`){d=m.call(_,d,f);break a}d=m;break a;case 3:m.flags=m.flags&-65537|128;case 0:if(m=g.payload,f=typeof m==`function`?m.call(_,d,f):m,f==null)break a;d=h({},d,f);break a;case 2:Ja=!0}}f=s.callback,f!==null&&(e.flags|=64,p&&(e.flags|=8192),p=i.callbacks,p===null?i.callbacks=[f]:p.push(f))}else p={lane:f,tag:s.tag,payload:s.payload,callback:s.callback,next:null},u===null?(l=u=p,c=d):u=u.next=p,o|=f;if(s=s.next,s===null){if(s=i.shared.pending,s===null)break;p=s,s=p.next,p.next=null,i.lastBaseUpdate=p,i.shared.pending=null}}while(1);u===null&&(c=d),i.baseState=c,i.firstBaseUpdate=l,i.lastBaseUpdate=u,a===null&&(i.shared.lanes=0),cu|=o,e.lanes=o,e.memoizedState=d}}function ro(e,t){if(typeof e!=`function`)throw Error(i(191,e));e.call(t)}function io(e,t){var n=e.callbacks;if(n!==null)for(e.callbacks=null,e=0;e<n.length;e++)ro(n[e],t)}var ao=fe(null),oo=fe(0);function so(e,t){e=ou,me(oo,e),me(ao,t),ou=e|t.baseLanes}function co(){me(oo,ou),me(ao,ao.current)}function lo(){ou=oo.current,pe(ao),pe(oo)}var uo=fe(null),fo=null;function po(e){var t=e.alternate;me(vo,vo.current&1),me(uo,e),fo===null&&(t===null||ao.current!==null||t.memoizedState!==null)&&(fo=e)}function mo(e){me(vo,vo.current),me(uo,e),fo===null&&(fo=e)}function ho(e){e.tag===22?(me(vo,vo.current),me(uo,e),fo===null&&(fo=e)):go(e)}function go(){me(vo,vo.current),me(uo,uo.current)}function _o(e){pe(uo),fo===e&&(fo=null),pe(vo)}var vo=fe(0);function yo(e){for(var t=e;t!==null;){if(t.tag===13){var n=t.memoizedState;if(n!==null&&(n=n.dehydrated,n===null||Tf(n)||Ef(n)))return t}else if(t.tag===19&&(t.memoizedProps.revealOrder===`forwards`||t.memoizedProps.revealOrder===`backwards`||t.memoizedProps.revealOrder===`unstable_legacy-backwards`||t.memoizedProps.revealOrder===`together`)){if(t.flags&128)return t}else if(t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return null;t=t.return}t.sibling.return=t.return,t=t.sibling}return null}var bo=0,xo=null,So=null,Co=null,wo=!1,To=!1,Eo=!1,Do=0,Oo=0,ko=null,Ao=0;function jo(){throw Error(i(321))}function Mo(e,t){if(t===null)return!1;for(var n=0;n<t.length&&n<e.length;n++)if(!Mr(e[n],t[n]))return!1;return!0}function No(e,t,n,r,i,a){return bo=a,xo=t,t.memoizedState=null,t.updateQueue=null,t.lanes=0,O.H=e===null||e.memoizedState===null?Ys:Xs,Eo=!1,a=n(r,i),Eo=!1,To&&(a=Fo(t,n,r,i)),Po(e),a}function Po(e){O.H=Js;var t=So!==null&&So.next!==null;if(bo=0,Co=So=xo=null,wo=!1,Oo=0,ko=null,t)throw Error(i(300));e===null||pc||(e=e.dependencies,e!==null&&la(e)&&(pc=!0))}function Fo(e,t,n,r){xo=e;var a=0;do{if(To&&(ko=null),Oo=0,To=!1,25<=a)throw Error(i(301));if(a+=1,Co=So=null,e.updateQueue!=null){var o=e.updateQueue;o.lastEffect=null,o.events=null,o.stores=null,o.memoCache!=null&&(o.memoCache.index=0)}O.H=Zs,o=t(n,r)}while(To);return o}function N(){var e=O.H,t=e.useState()[0];return t=typeof t.then==`function`?Ho(t):t,e=e.useState()[0],(So===null?null:So.memoizedState)!==e&&(xo.flags|=1024),t}function Io(){var e=Do!==0;return Do=0,e}function Lo(e,t,n){t.updateQueue=e.updateQueue,t.flags&=-2053,e.lanes&=~n}function Ro(e){if(wo){for(e=e.memoizedState;e!==null;){var t=e.queue;t!==null&&(t.pending=null),e=e.next}wo=!1}bo=0,Co=So=xo=null,To=!1,Oo=Do=0,ko=null}function zo(){var e={memoizedState:null,baseState:null,baseQueue:null,queue:null,next:null};return Co===null?xo.memoizedState=Co=e:Co=Co.next=e,Co}function Bo(){if(So===null){var e=xo.alternate;e=e===null?null:e.memoizedState}else e=So.next;var t=Co===null?xo.memoizedState:Co.next;if(t!==null)Co=t,So=e;else{if(e===null)throw xo.alternate===null?Error(i(467)):Error(i(310));So=e,e={memoizedState:So.memoizedState,baseState:So.baseState,baseQueue:So.baseQueue,queue:So.queue,next:null},Co===null?xo.memoizedState=Co=e:Co=Co.next=e}return Co}function Vo(){return{lastEffect:null,events:null,stores:null,memoCache:null}}function Ho(e){var t=Oo;return Oo+=1,ko===null&&(ko=[]),e=Fa(ko,e,t),t=xo,(Co===null?t.memoizedState:Co.next)===null&&(t=t.alternate,O.H=t===null||t.memoizedState===null?Ys:Xs),e}function Uo(e){if(typeof e==`object`&&e){if(typeof e.then==`function`)return Ho(e);if(e.$$typeof===C)return da(e)}throw Error(i(438,String(e)))}function Wo(e){var t=null,n=xo.updateQueue;if(n!==null&&(t=n.memoCache),t==null){var r=xo.alternate;r!==null&&(r=r.updateQueue,r!==null&&(r=r.memoCache,r!=null&&(t={data:r.data.map(function(e){return e.slice()}),index:0})))}if(t??={data:[],index:0},n===null&&(n=Vo(),xo.updateQueue=n),n.memoCache=t,n=t.data[t.index],n===void 0)for(n=t.data[t.index]=Array(e),r=0;r<e;r++)n[r]=E;return t.index++,n}function Go(e,t){return typeof t==`function`?t(e):t}function Ko(e){return qo(Bo(),So,e)}function qo(e,t,n){var r=e.queue;if(r===null)throw Error(i(311));r.lastRenderedReducer=n;var a=e.baseQueue,o=r.pending;if(o!==null){if(a!==null){var s=a.next;a.next=o.next,o.next=s}t.baseQueue=a=o,r.pending=null}if(o=e.baseState,a===null)e.memoizedState=o;else{t=a.next;var c=s=null,l=null,u=t,d=!1;do{var f=u.lane&-536870913;if(f===u.lane?(bo&f)===f:(eu&f)===f){var p=u.revertLane;if(p===0)l!==null&&(l=l.next={lane:0,revertLane:0,gesture:null,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null}),f===Sa&&(d=!0);else if((bo&p)===p){u=u.next,p===Sa&&(d=!0);continue}else f={lane:0,revertLane:u.revertLane,gesture:null,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null},l===null?(c=l=f,s=o):l=l.next=f,xo.lanes|=p,cu|=p;f=u.action,Eo&&n(o,f),o=u.hasEagerState?u.eagerState:n(o,f)}else p={lane:f,revertLane:u.revertLane,gesture:u.gesture,action:u.action,hasEagerState:u.hasEagerState,eagerState:u.eagerState,next:null},l===null?(c=l=p,s=o):l=l.next=p,xo.lanes|=f,cu|=f;u=u.next}while(u!==null&&u!==t);if(l===null?s=o:l.next=c,!Mr(o,e.memoizedState)&&(pc=!0,d&&(n=Ca,n!==null)))throw n;e.memoizedState=o,e.baseState=s,e.baseQueue=l,r.lastRenderedState=o}return a===null&&(r.lanes=0),[e.memoizedState,r.dispatch]}function Jo(e){var t=Bo(),n=t.queue;if(n===null)throw Error(i(311));n.lastRenderedReducer=e;var r=n.dispatch,a=n.pending,o=t.memoizedState;if(a!==null){n.pending=null;var s=a=a.next;do o=e(o,s.action),s=s.next;while(s!==a);Mr(o,t.memoizedState)||(pc=!0),t.memoizedState=o,t.baseQueue===null&&(t.baseState=o),n.lastRenderedState=o}return[o,r]}function Yo(e,t,n){var r=xo,a=Bo(),o=Wi;if(o){if(n===void 0)throw Error(i(407));n=n()}else n=t();var s=!Mr((So||a).memoizedState,n);if(s&&(a.memoizedState=n,pc=!0),a=a.queue,bs(Qo.bind(null,r,a,e),[e]),a.getSnapshot!==t||s||Co!==null&&Co.memoizedState.tag&1){if(r.flags|=2048,hs(9,{destroy:void 0},Zo.bind(null,r,a,n,t),null),Ql===null)throw Error(i(349));o||bo&127||Xo(r,t,n)}return n}function Xo(e,t,n){e.flags|=16384,e={getSnapshot:t,value:n},t=xo.updateQueue,t===null?(t=Vo(),xo.updateQueue=t,t.stores=[e]):(n=t.stores,n===null?t.stores=[e]:n.push(e))}function Zo(e,t,n,r){t.value=n,t.getSnapshot=r,$o(t)&&es(e)}function Qo(e,t,n){return n(function(){$o(t)&&es(e)})}function $o(e){var t=e.getSnapshot;e=e.value;try{var n=t();return!Mr(e,n)}catch{return!0}}function es(e){var t=pi(e,2);t!==null&&Mu(t,e,2)}function ts(e){var t=zo();if(typeof e==`function`){var n=e;if(e=n(),Eo){Ke(!0);try{n()}finally{Ke(!1)}}}return t.memoizedState=t.baseState=e,t.queue={pending:null,lanes:0,dispatch:null,lastRenderedReducer:Go,lastRenderedState:e},t}function ns(e,t,n,r){return e.baseState=n,qo(e,So,typeof r==`function`?r:Go)}function rs(e,t,n,r,a){if(Gs(e))throw Error(i(485));if(e=t.action,e!==null){var o={payload:a,action:e,next:null,isTransition:!0,status:`pending`,value:null,reason:null,listeners:[],then:function(e){o.listeners.push(e)}};O.T===null?o.isTransition=!1:n(!0),r(o),n=t.pending,n===null?(o.next=t.pending=o,is(t,o)):(o.next=n.next,t.pending=n.next=o)}}function is(e,t){var n=t.action,r=t.payload,i=e.state;if(t.isTransition){var a=O.T,o={};O.T=o;try{var s=n(i,r),c=O.S;c!==null&&c(o,s),as(e,t,s)}catch(n){ss(e,t,n)}finally{a!==null&&o.types!==null&&(a.types=o.types),O.T=a}}else try{a=n(i,r),as(e,t,a)}catch(n){ss(e,t,n)}}function as(e,t,n){typeof n==`object`&&n&&typeof n.then==`function`?n.then(function(n){os(e,t,n)},function(n){return ss(e,t,n)}):os(e,t,n)}function os(e,t,n){t.status=`fulfilled`,t.value=n,cs(t),e.state=n,t=e.pending,t!==null&&(n=t.next,n===t?e.pending=null:(n=n.next,t.next=n,is(e,n)))}function ss(e,t,n){var r=e.pending;if(e.pending=null,r!==null){r=r.next;do t.status=`rejected`,t.reason=n,cs(t),t=t.next;while(t!==r)}e.action=null}function cs(e){e=e.listeners;for(var t=0;t<e.length;t++)(0,e[t])()}function ls(e,t){return t}function us(e,t){if(Wi){var n=Ql.formState;if(n!==null){a:{var r=xo;if(Wi){if(k){b:{for(var i=k,a=Ki;i.nodeType!==8;){if(!a){i=null;break b}if(i=Of(i.nextSibling),i===null){i=null;break b}}a=i.data,i=a===`F!`||a===`F`?i:null}if(i){k=Of(i.nextSibling),r=i.data===`F!`;break a}}Ji(r)}r=!1}r&&(t=n[0])}}return n=zo(),n.memoizedState=n.baseState=t,r={pending:null,lanes:0,dispatch:null,lastRenderedReducer:ls,lastRenderedState:t},n.queue=r,n=Hs.bind(null,xo,r),r.dispatch=n,r=ts(!1),a=Ws.bind(null,xo,!1,r.queue),r=zo(),i={state:t,dispatch:null,action:e,pending:null},r.queue=i,n=rs.bind(null,xo,i,a,n),i.dispatch=n,r.memoizedState=e,[t,n,!1]}function ds(e){return fs(Bo(),So,e)}function fs(e,t,n){if(t=qo(e,t,ls)[0],e=Ko(Go)[0],typeof t==`object`&&t&&typeof t.then==`function`)try{var r=Ho(t)}catch(e){throw e===j?Ma:e}else r=t;t=Bo();var i=t.queue,a=i.dispatch;return n!==t.memoizedState&&(xo.flags|=2048,hs(9,{destroy:void 0},ps.bind(null,i,n),null)),[r,a,e]}function ps(e,t){e.action=t}function ms(e){var t=Bo(),n=So;if(n!==null)return fs(t,n,e);Bo(),t=t.memoizedState,n=Bo();var r=n.queue.dispatch;return n.memoizedState=e,[t,r,!1]}function hs(e,t,n,r){return e={tag:e,create:n,deps:r,inst:t,next:null},t=xo.updateQueue,t===null&&(t=Vo(),xo.updateQueue=t),n=t.lastEffect,n===null?t.lastEffect=e.next=e:(r=n.next,n.next=e,e.next=r,t.lastEffect=e),e}function gs(){return Bo().memoizedState}function _s(e,t,n,r){var i=zo();xo.flags|=e,i.memoizedState=hs(1|t,{destroy:void 0},n,r===void 0?null:r)}function vs(e,t,n,r){var i=Bo();r=r===void 0?null:r;var a=i.memoizedState.inst;So!==null&&r!==null&&Mo(r,So.memoizedState.deps)?i.memoizedState=hs(t,a,n,r):(xo.flags|=e,i.memoizedState=hs(1|t,a,n,r))}function ys(e,t){_s(8390656,8,e,t)}function bs(e,t){vs(2048,8,e,t)}function xs(e){xo.flags|=4;var t=xo.updateQueue;if(t===null)t=Vo(),xo.updateQueue=t,t.events=[e];else{var n=t.events;n===null?t.events=[e]:n.push(e)}}function Ss(e){var t=Bo().memoizedState;return xs({ref:t,nextImpl:e}),function(){if(Zl&2)throw Error(i(440));return t.impl.apply(void 0,arguments)}}function Cs(e,t){return vs(4,2,e,t)}function ws(e,t){return vs(4,4,e,t)}function Ts(e,t){if(typeof t==`function`){e=e();var n=t(e);return function(){typeof n==`function`?n():t(null)}}if(t!=null)return e=e(),t.current=e,function(){t.current=null}}function Es(e,t,n){n=n==null?null:n.concat([e]),vs(4,4,Ts.bind(null,t,e),n)}function Ds(){}function Os(e,t){var n=Bo();t=t===void 0?null:t;var r=n.memoizedState;return t!==null&&Mo(t,r[1])?r[0]:(n.memoizedState=[e,t],e)}function ks(e,t){var n=Bo();t=t===void 0?null:t;var r=n.memoizedState;if(t!==null&&Mo(t,r[1]))return r[0];if(r=e(),Eo){Ke(!0);try{e()}finally{Ke(!1)}}return n.memoizedState=[r,t],r}function As(e,t,n){return n===void 0||bo&1073741824&&!(eu&261930)?e.memoizedState=t:(e.memoizedState=n,e=ju(),xo.lanes|=e,cu|=e,n)}function js(e,t,n,r){return Mr(n,t)?n:ao.current===null?!(bo&42)||bo&1073741824&&!(eu&261930)?(pc=!0,e.memoizedState=n):(e=ju(),xo.lanes|=e,cu|=e,t):(e=As(e,n,r),Mr(e,t)||(pc=!0),e)}function Ms(e,t,n,r,i){var a=ce.p;ce.p=a!==0&&8>a?a:8;var o=O.T,s={};O.T=s,Ws(e,!1,t,n);try{var c=i(),l=O.S;l!==null&&l(s,c),typeof c==`object`&&c&&typeof c.then==`function`?Us(e,t,Ea(c,r),Au(e)):Us(e,t,r,Au(e))}catch(n){Us(e,t,{then:function(){},status:`rejected`,reason:n},Au())}finally{ce.p=a,o!==null&&s.types!==null&&(o.types=s.types),O.T=o}}function Ns(){}function Ps(e,t,n,r){if(e.tag!==5)throw Error(i(476));var a=Fs(e).queue;Ms(e,a,t,le,n===null?Ns:function(){return Is(e),n(r)})}function Fs(e){var t=e.memoizedState;if(t!==null)return t;t={memoizedState:le,baseState:le,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Go,lastRenderedState:le},next:null};var n={};return t.next={memoizedState:n,baseState:n,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:Go,lastRenderedState:n},next:null},e.memoizedState=t,e=e.alternate,e!==null&&(e.memoizedState=t),t}function Is(e){var t=Fs(e);t.next===null&&(t=e.alternate.memoizedState),Us(e,t.next.queue,{},Au())}function Ls(){return da(mp)}function Rs(){return Bo().memoizedState}function zs(){return Bo().memoizedState}function Bs(e){for(var t=e.return;t!==null;){switch(t.tag){case 24:case 3:var n=Au();e=Za(n);var r=M(t,e,n);r!==null&&(Mu(r,t,n),Qa(r,t,n)),t={cache:va()},e.payload=t;return}t=t.return}}function Vs(e,t,n){var r=Au();n={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null},Gs(e)?Ks(t,n):(n=fi(e,t,n,r),n!==null&&(Mu(n,e,r),qs(n,t,r)))}function Hs(e,t,n){Us(e,t,n,Au())}function Us(e,t,n,r){var i={lane:r,revertLane:0,gesture:null,action:n,hasEagerState:!1,eagerState:null,next:null};if(Gs(e))Ks(t,i);else{var a=e.alternate;if(e.lanes===0&&(a===null||a.lanes===0)&&(a=t.lastRenderedReducer,a!==null))try{var o=t.lastRenderedState,s=a(o,n);if(i.hasEagerState=!0,i.eagerState=s,Mr(s,o))return di(e,t,i,0),Ql===null&&ui(),!1}catch{}if(n=fi(e,t,i,r),n!==null)return Mu(n,e,r),qs(n,t,r),!0}return!1}function Ws(e,t,n,r){if(r={lane:2,revertLane:kd(),gesture:null,action:r,hasEagerState:!1,eagerState:null,next:null},Gs(e)){if(t)throw Error(i(479))}else t=fi(e,n,r,2),t!==null&&Mu(t,e,2)}function Gs(e){var t=e.alternate;return e===xo||t!==null&&t===xo}function Ks(e,t){To=wo=!0;var n=e.pending;n===null?t.next=t:(t.next=n.next,n.next=t),e.pending=t}function qs(e,t,n){if(n&4194048){var r=t.lanes;r&=e.pendingLanes,n|=r,t.lanes=n,lt(e,n)}}var Js={readContext:da,use:Uo,useCallback:jo,useContext:jo,useEffect:jo,useImperativeHandle:jo,useLayoutEffect:jo,useInsertionEffect:jo,useMemo:jo,useReducer:jo,useRef:jo,useState:jo,useDebugValue:jo,useDeferredValue:jo,useTransition:jo,useSyncExternalStore:jo,useId:jo,useHostTransitionStatus:jo,useFormState:jo,useActionState:jo,useOptimistic:jo,useMemoCache:jo,useCacheRefresh:jo};Js.useEffectEvent=jo;var Ys={readContext:da,use:Uo,useCallback:function(e,t){return zo().memoizedState=[e,t===void 0?null:t],e},useContext:da,useEffect:ys,useImperativeHandle:function(e,t,n){n=n==null?null:n.concat([e]),_s(4194308,4,Ts.bind(null,t,e),n)},useLayoutEffect:function(e,t){return _s(4194308,4,e,t)},useInsertionEffect:function(e,t){_s(4,2,e,t)},useMemo:function(e,t){var n=zo();t=t===void 0?null:t;var r=e();if(Eo){Ke(!0);try{e()}finally{Ke(!1)}}return n.memoizedState=[r,t],r},useReducer:function(e,t,n){var r=zo();if(n!==void 0){var i=n(t);if(Eo){Ke(!0);try{n(t)}finally{Ke(!1)}}}else i=t;return r.memoizedState=r.baseState=i,e={pending:null,lanes:0,dispatch:null,lastRenderedReducer:e,lastRenderedState:i},r.queue=e,e=e.dispatch=Vs.bind(null,xo,e),[r.memoizedState,e]},useRef:function(e){var t=zo();return e={current:e},t.memoizedState=e},useState:function(e){e=ts(e);var t=e.queue,n=Hs.bind(null,xo,t);return t.dispatch=n,[e.memoizedState,n]},useDebugValue:Ds,useDeferredValue:function(e,t){return As(zo(),e,t)},useTransition:function(){var e=ts(!1);return e=Ms.bind(null,xo,e.queue,!0,!1),zo().memoizedState=e,[!1,e]},useSyncExternalStore:function(e,t,n){var r=xo,a=zo();if(Wi){if(n===void 0)throw Error(i(407));n=n()}else{if(n=t(),Ql===null)throw Error(i(349));eu&127||Xo(r,t,n)}a.memoizedState=n;var o={value:n,getSnapshot:t};return a.queue=o,ys(Qo.bind(null,r,o,e),[e]),r.flags|=2048,hs(9,{destroy:void 0},Zo.bind(null,r,o,n,t),null),n},useId:function(){var e=zo(),t=Ql.identifierPrefix;if(Wi){var n=Li,r=Ii;n=(r&~(1<<32-qe(r)-1)).toString(32)+n,t=`_`+t+`R_`+n,n=Do++,0<n&&(t+=`H`+n.toString(32)),t+=`_`}else n=Ao++,t=`_`+t+`r_`+n.toString(32)+`_`;return e.memoizedState=t},useHostTransitionStatus:Ls,useFormState:us,useActionState:us,useOptimistic:function(e){var t=zo();t.memoizedState=t.baseState=e;var n={pending:null,lanes:0,dispatch:null,lastRenderedReducer:null,lastRenderedState:null};return t.queue=n,t=Ws.bind(null,xo,!0,n),n.dispatch=t,[e,t]},useMemoCache:Wo,useCacheRefresh:function(){return zo().memoizedState=Bs.bind(null,xo)},useEffectEvent:function(e){var t=zo(),n={impl:e};return t.memoizedState=n,function(){if(Zl&2)throw Error(i(440));return n.impl.apply(void 0,arguments)}}},Xs={readContext:da,use:Uo,useCallback:Os,useContext:da,useEffect:bs,useImperativeHandle:Es,useInsertionEffect:Cs,useLayoutEffect:ws,useMemo:ks,useReducer:Ko,useRef:gs,useState:function(){return Ko(Go)},useDebugValue:Ds,useDeferredValue:function(e,t){return js(Bo(),So.memoizedState,e,t)},useTransition:function(){var e=Ko(Go)[0],t=Bo().memoizedState;return[typeof e==`boolean`?e:Ho(e),t]},useSyncExternalStore:Yo,useId:Rs,useHostTransitionStatus:Ls,useFormState:ds,useActionState:ds,useOptimistic:function(e,t){return ns(Bo(),So,e,t)},useMemoCache:Wo,useCacheRefresh:zs};Xs.useEffectEvent=Ss;var Zs={readContext:da,use:Uo,useCallback:Os,useContext:da,useEffect:bs,useImperativeHandle:Es,useInsertionEffect:Cs,useLayoutEffect:ws,useMemo:ks,useReducer:Jo,useRef:gs,useState:function(){return Jo(Go)},useDebugValue:Ds,useDeferredValue:function(e,t){var n=Bo();return So===null?As(n,e,t):js(n,So.memoizedState,e,t)},useTransition:function(){var e=Jo(Go)[0],t=Bo().memoizedState;return[typeof e==`boolean`?e:Ho(e),t]},useSyncExternalStore:Yo,useId:Rs,useHostTransitionStatus:Ls,useFormState:ms,useActionState:ms,useOptimistic:function(e,t){var n=Bo();return So===null?(n.baseState=e,[e,n.queue.dispatch]):ns(n,So,e,t)},useMemoCache:Wo,useCacheRefresh:zs};Zs.useEffectEvent=Ss;function Qs(e,t,n,r){t=e.memoizedState,n=n(r,t),n=n==null?t:h({},t,n),e.memoizedState=n,e.lanes===0&&(e.updateQueue.baseState=n)}var $s={enqueueSetState:function(e,t,n){e=e._reactInternals;var r=Au(),i=Za(r);i.payload=t,n!=null&&(i.callback=n),t=M(e,i,r),t!==null&&(Mu(t,e,r),Qa(t,e,r))},enqueueReplaceState:function(e,t,n){e=e._reactInternals;var r=Au(),i=Za(r);i.tag=1,i.payload=t,n!=null&&(i.callback=n),t=M(e,i,r),t!==null&&(Mu(t,e,r),Qa(t,e,r))},enqueueForceUpdate:function(e,t){e=e._reactInternals;var n=Au(),r=Za(n);r.tag=2,t!=null&&(r.callback=t),t=M(e,r,n),t!==null&&(Mu(t,e,n),Qa(t,e,n))}};function ec(e,t,n,r,i,a,o){return e=e.stateNode,typeof e.shouldComponentUpdate==`function`?e.shouldComponentUpdate(r,a,o):t.prototype&&t.prototype.isPureReactComponent?!Nr(n,r)||!Nr(i,a):!0}function tc(e,t,n,r){e=t.state,typeof t.componentWillReceiveProps==`function`&&t.componentWillReceiveProps(n,r),typeof t.UNSAFE_componentWillReceiveProps==`function`&&t.UNSAFE_componentWillReceiveProps(n,r),t.state!==e&&$s.enqueueReplaceState(t,t.state,null)}function nc(e,t){var n=t;if(`ref`in t)for(var r in n={},t)r!==`ref`&&(n[r]=t[r]);if(e=e.defaultProps)for(var i in n===t&&(n=h({},n)),e)n[i]===void 0&&(n[i]=e[i]);return n}function rc(e){oi(e)}function ic(e){console.error(e)}function ac(e){oi(e)}function oc(e,t){try{var n=e.onUncaughtError;n(t.value,{componentStack:t.stack})}catch(e){setTimeout(function(){throw e})}}function sc(e,t,n){try{var r=e.onCaughtError;r(n.value,{componentStack:n.stack,errorBoundary:t.tag===1?t.stateNode:null})}catch(e){setTimeout(function(){throw e})}}function cc(e,t,n){return n=Za(n),n.tag=3,n.payload={element:null},n.callback=function(){oc(e,t)},n}function lc(e){return e=Za(e),e.tag=3,e}function uc(e,t,n,r){var i=n.type.getDerivedStateFromError;if(typeof i==`function`){var a=r.value;e.payload=function(){return i(a)},e.callback=function(){sc(t,n,r)}}var o=n.stateNode;o!==null&&typeof o.componentDidCatch==`function`&&(e.callback=function(){sc(t,n,r),typeof i!=`function`&&(bu===null?bu=new Set([this]):bu.add(this));var e=r.stack;this.componentDidCatch(r.value,{componentStack:e===null?``:e})})}function dc(e,t,n,r,a){if(n.flags|=32768,typeof r==`object`&&r&&typeof r.then==`function`){if(t=n.alternate,t!==null&&ca(t,n,a,!0),n=uo.current,n!==null){switch(n.tag){case 31:case 13:return fo===null?Wu():n.alternate===null&&su===0&&(su=3),n.flags&=-257,n.flags|=65536,n.lanes=a,r===Na?n.flags|=16384:(t=n.updateQueue,t===null?n.updateQueue=new Set([r]):t.add(r),ld(e,r,a)),!1;case 22:return n.flags|=65536,r===Na?n.flags|=16384:(t=n.updateQueue,t===null?(t={transitions:null,markerInstances:null,retryQueue:new Set([r])},n.updateQueue=t):(n=t.retryQueue,n===null?t.retryQueue=new Set([r]):n.add(r)),ld(e,r,a)),!1}throw Error(i(435,n.tag))}return ld(e,r,a),Wu(),!1}if(Wi)return t=uo.current,t===null?(r!==qi&&(t=Error(i(423),{cause:r}),ea(Oi(t,n))),e=e.current.alternate,e.flags|=65536,a&=-a,e.lanes|=a,r=Oi(r,n),a=cc(e.stateNode,r,a),$a(e,a),su!==4&&(su=2)):(!(t.flags&65536)&&(t.flags|=256),t.flags|=65536,t.lanes=a,r!==qi&&(e=Error(i(422),{cause:r}),ea(Oi(e,n)))),!1;var o=Error(i(520),{cause:r});if(o=Oi(o,n),pu===null?pu=[o]:pu.push(o),su!==4&&(su=2),t===null)return!0;r=Oi(r,n),n=t;do{switch(n.tag){case 3:return n.flags|=65536,e=a&-a,n.lanes|=e,e=cc(n.stateNode,r,e),$a(n,e),!1;case 1:if(t=n.type,o=n.stateNode,!(n.flags&128)&&(typeof t.getDerivedStateFromError==`function`||o!==null&&typeof o.componentDidCatch==`function`&&(bu===null||!bu.has(o))))return n.flags|=65536,a&=-a,n.lanes|=a,a=lc(a),uc(a,e,n,r),$a(n,a),!1}n=n.return}while(n!==null);return!1}var fc=Error(i(461)),pc=!1;function mc(e,t,n,r){t.child=e===null?qa(t,null,n,r):Ka(t,e.child,n,r)}function hc(e,t,n,r,i){n=n.render;var a=t.ref;if(`ref`in r){var o={};for(var s in r)s!==`ref`&&(o[s]=r[s])}else o=r;return ua(t),r=No(e,t,n,o,a,i),s=Io(),e!==null&&!pc?(Lo(e,t,i),zc(e,t,i)):(Wi&&s&&Bi(t),t.flags|=1,mc(e,t,r,i),t.child)}function gc(e,t,n,r,i){if(e===null){var a=n.type;return typeof a==`function`&&!yi(a)&&a.defaultProps===void 0&&n.compare===null?(t.tag=15,t.type=a,_c(e,t,a,r,i)):(e=Si(n.type,null,r,t,t.mode,i),e.ref=t.ref,e.return=t,t.child=e)}if(a=e.child,!Bc(e,i)){var o=a.memoizedProps;if(n=n.compare,n=n===null?Nr:n,n(o,r)&&e.ref===t.ref)return zc(e,t,i)}return t.flags|=1,e=bi(a,r),e.ref=t.ref,e.return=t,t.child=e}function _c(e,t,n,r,i){if(e!==null){var a=e.memoizedProps;if(Nr(a,r)&&e.ref===t.ref){if(pc=!1,t.pendingProps=r=a,Bc(e,i))e.flags&131072&&(pc=!0);else return t.lanes=e.lanes,zc(e,t,i)}}return Tc(e,t,n,r,i)}function vc(e,t,n,r){var i=r.children,a=e===null?null:e.memoizedState;if(e===null&&t.stateNode===null&&(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),r.mode===`hidden`){if(t.flags&128){if(a=a===null?n:a.baseLanes|n,e!==null){for(r=t.child=e.child,i=0;r!==null;)i=i|r.lanes|r.childLanes,r=r.sibling;r=i&~a}else r=0,t.child=null;return bc(e,t,a,n,r)}if(n&536870912)t.memoizedState={baseLanes:0,cachePool:null},e!==null&&ka(t,a===null?null:a.cachePool),a===null?co():so(t,a),ho(t);else return r=t.lanes=536870912,bc(e,t,a===null?n:a.baseLanes|n,n,r)}else a===null?(e!==null&&ka(t,null),co(),go(t)):(ka(t,a.cachePool),so(t,a),go(t),t.memoizedState=null);return mc(e,t,i,n),t.child}function yc(e,t){return e!==null&&e.tag===22||t.stateNode!==null||(t.stateNode={_visibility:1,_pendingMarkers:null,_retryCache:null,_transitions:null}),t.sibling}function bc(e,t,n,r,i){var a=A();return a=a===null?null:{parent:_a._currentValue,pool:a},t.memoizedState={baseLanes:n,cachePool:a},e!==null&&ka(t,null),co(),ho(t),e!==null&&ca(e,t,r,!0),t.childLanes=i,null}function xc(e,t){return t=Pc({mode:t.mode,children:t.children},e.mode),t.ref=e.ref,e.child=t,t.return=e,t}function Sc(e,t,n){return Ka(t,e.child,null,n),e=xc(t,t.pendingProps),e.flags|=2,_o(t),t.memoizedState=null,e}function Cc(e,t,n){var r=t.pendingProps,a=!!(t.flags&128);if(t.flags&=-129,e===null){if(Wi){if(r.mode===`hidden`)return e=xc(t,r),t.lanes=536870912,yc(null,e);if(mo(t),(e=k)?(e=wf(e,Ki),e=e!==null&&e.data===`&`?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:Fi===null?null:{id:Ii,overflow:Li},retryLane:536870912,hydrationErrors:null},n=Ti(e),n.return=t,t.child=n,Ui=t,k=null)):e=null,e===null)throw Ji(t);return t.lanes=536870912,null}return xc(t,r)}var o=e.memoizedState;if(o!==null){var s=o.dehydrated;if(mo(t),a){if(t.flags&256)t.flags&=-257,t=Sc(e,t,n);else if(t.memoizedState!==null)t.child=e.child,t.flags|=128,t=null;else throw Error(i(558))}else if(pc||ca(e,t,n,!1),a=(n&e.childLanes)!==0,pc||a){if(r=Ql,r!==null&&(s=ut(r,n),s!==0&&s!==o.retryLane))throw o.retryLane=s,pi(e,s),Mu(r,e,s),fc;Wu(),t=Sc(e,t,n)}else e=o.treeContext,k=Of(s.nextSibling),Ui=t,Wi=!0,Gi=null,Ki=!1,e!==null&&Hi(t,e),t=xc(t,r),t.flags|=4096;return t}return e=bi(e.child,{mode:r.mode,children:r.children}),e.ref=t.ref,t.child=e,e.return=t,e}function wc(e,t){var n=t.ref;if(n===null)e!==null&&e.ref!==null&&(t.flags|=4194816);else{if(typeof n!=`function`&&typeof n!=`object`)throw Error(i(284));(e===null||e.ref!==n)&&(t.flags|=4194816)}}function Tc(e,t,n,r,i){return ua(t),n=No(e,t,n,r,void 0,i),r=Io(),e!==null&&!pc?(Lo(e,t,i),zc(e,t,i)):(Wi&&r&&Bi(t),t.flags|=1,mc(e,t,n,i),t.child)}function Ec(e,t,n,r,i,a){return ua(t),t.updateQueue=null,n=Fo(t,r,n,i),Po(e),r=Io(),e!==null&&!pc?(Lo(e,t,a),zc(e,t,a)):(Wi&&r&&Bi(t),t.flags|=1,mc(e,t,n,a),t.child)}function Dc(e,t,n,r,i){if(ua(t),t.stateNode===null){var a=gi,o=n.contextType;typeof o==`object`&&o&&(a=da(o)),a=new n(r,a),t.memoizedState=a.state!==null&&a.state!==void 0?a.state:null,a.updater=$s,t.stateNode=a,a._reactInternals=t,a=t.stateNode,a.props=r,a.state=t.memoizedState,a.refs={},Ya(t),o=n.contextType,a.context=typeof o==`object`&&o?da(o):gi,a.state=t.memoizedState,o=n.getDerivedStateFromProps,typeof o==`function`&&(Qs(t,n,o,r),a.state=t.memoizedState),typeof n.getDerivedStateFromProps==`function`||typeof a.getSnapshotBeforeUpdate==`function`||typeof a.UNSAFE_componentWillMount!=`function`&&typeof a.componentWillMount!=`function`||(o=a.state,typeof a.componentWillMount==`function`&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount==`function`&&a.UNSAFE_componentWillMount(),o!==a.state&&$s.enqueueReplaceState(a,a.state,null),no(t,r,a,i),to(),a.state=t.memoizedState),typeof a.componentDidMount==`function`&&(t.flags|=4194308),r=!0}else if(e===null){a=t.stateNode;var s=t.memoizedProps,c=nc(n,s);a.props=c;var l=a.context,u=n.contextType;o=gi,typeof u==`object`&&u&&(o=da(u));var d=n.getDerivedStateFromProps;u=typeof d==`function`||typeof a.getSnapshotBeforeUpdate==`function`,s=t.pendingProps!==s,u||typeof a.UNSAFE_componentWillReceiveProps!=`function`&&typeof a.componentWillReceiveProps!=`function`||(s||l!==o)&&tc(t,a,r,o),Ja=!1;var f=t.memoizedState;a.state=f,no(t,r,a,i),to(),l=t.memoizedState,s||f!==l||Ja?(typeof d==`function`&&(Qs(t,n,d,r),l=t.memoizedState),(c=Ja||ec(t,n,c,r,f,l,o))?(u||typeof a.UNSAFE_componentWillMount!=`function`&&typeof a.componentWillMount!=`function`||(typeof a.componentWillMount==`function`&&a.componentWillMount(),typeof a.UNSAFE_componentWillMount==`function`&&a.UNSAFE_componentWillMount()),typeof a.componentDidMount==`function`&&(t.flags|=4194308)):(typeof a.componentDidMount==`function`&&(t.flags|=4194308),t.memoizedProps=r,t.memoizedState=l),a.props=r,a.state=l,a.context=o,r=c):(typeof a.componentDidMount==`function`&&(t.flags|=4194308),r=!1)}else{a=t.stateNode,Xa(e,t),o=t.memoizedProps,u=nc(n,o),a.props=u,d=t.pendingProps,f=a.context,l=n.contextType,c=gi,typeof l==`object`&&l&&(c=da(l)),s=n.getDerivedStateFromProps,(l=typeof s==`function`||typeof a.getSnapshotBeforeUpdate==`function`)||typeof a.UNSAFE_componentWillReceiveProps!=`function`&&typeof a.componentWillReceiveProps!=`function`||(o!==d||f!==c)&&tc(t,a,r,c),Ja=!1,f=t.memoizedState,a.state=f,no(t,r,a,i),to();var p=t.memoizedState;o!==d||f!==p||Ja||e!==null&&e.dependencies!==null&&la(e.dependencies)?(typeof s==`function`&&(Qs(t,n,s,r),p=t.memoizedState),(u=Ja||ec(t,n,u,r,f,p,c)||e!==null&&e.dependencies!==null&&la(e.dependencies))?(l||typeof a.UNSAFE_componentWillUpdate!=`function`&&typeof a.componentWillUpdate!=`function`||(typeof a.componentWillUpdate==`function`&&a.componentWillUpdate(r,p,c),typeof a.UNSAFE_componentWillUpdate==`function`&&a.UNSAFE_componentWillUpdate(r,p,c)),typeof a.componentDidUpdate==`function`&&(t.flags|=4),typeof a.getSnapshotBeforeUpdate==`function`&&(t.flags|=1024)):(typeof a.componentDidUpdate!=`function`||o===e.memoizedProps&&f===e.memoizedState||(t.flags|=4),typeof a.getSnapshotBeforeUpdate!=`function`||o===e.memoizedProps&&f===e.memoizedState||(t.flags|=1024),t.memoizedProps=r,t.memoizedState=p),a.props=r,a.state=p,a.context=c,r=u):(typeof a.componentDidUpdate!=`function`||o===e.memoizedProps&&f===e.memoizedState||(t.flags|=4),typeof a.getSnapshotBeforeUpdate!=`function`||o===e.memoizedProps&&f===e.memoizedState||(t.flags|=1024),r=!1)}return a=r,wc(e,t),r=!!(t.flags&128),a||r?(a=t.stateNode,n=r&&typeof n.getDerivedStateFromError!=`function`?null:a.render(),t.flags|=1,e!==null&&r?(t.child=Ka(t,e.child,null,i),t.child=Ka(t,null,n,i)):mc(e,t,n,i),t.memoizedState=a.state,e=t.child):e=zc(e,t,i),e}function Oc(e,t,n,r){return Qi(),t.flags|=256,mc(e,t,n,r),t.child}var kc={dehydrated:null,treeContext:null,retryLane:0,hydrationErrors:null};function Ac(e){return{baseLanes:e,cachePool:Aa()}}function jc(e,t,n){return e=e===null?0:e.childLanes&~n,t&&(e|=du),e}function Mc(e,t,n){var r=t.pendingProps,a=!1,o=!!(t.flags&128),s;if((s=o)||(s=e!==null&&e.memoizedState===null?!1:!!(vo.current&2)),s&&(a=!0,t.flags&=-129),s=!!(t.flags&32),t.flags&=-33,e===null){if(Wi){if(a?po(t):go(t),(e=k)?(e=wf(e,Ki),e=e!==null&&e.data!==`&`?e:null,e!==null&&(t.memoizedState={dehydrated:e,treeContext:Fi===null?null:{id:Ii,overflow:Li},retryLane:536870912,hydrationErrors:null},n=Ti(e),n.return=t,t.child=n,Ui=t,k=null)):e=null,e===null)throw Ji(t);return Ef(e)?t.lanes=32:t.lanes=536870912,null}var c=r.children;return r=r.fallback,a?(go(t),a=t.mode,c=Pc({mode:`hidden`,children:c},a),r=Ci(r,a,n,null),c.return=t,r.return=t,c.sibling=r,t.child=c,r=t.child,r.memoizedState=Ac(n),r.childLanes=jc(e,s,n),t.memoizedState=kc,yc(null,r)):(po(t),Nc(t,c))}var l=e.memoizedState;if(l!==null&&(c=l.dehydrated,c!==null)){if(o)t.flags&256?(po(t),t.flags&=-257,t=Fc(e,t,n)):t.memoizedState===null?(go(t),c=r.fallback,a=t.mode,r=Pc({mode:`visible`,children:r.children},a),c=Ci(c,a,n,null),c.flags|=2,r.return=t,c.return=t,r.sibling=c,t.child=r,Ka(t,e.child,null,n),r=t.child,r.memoizedState=Ac(n),r.childLanes=jc(e,s,n),t.memoizedState=kc,t=yc(null,r)):(go(t),t.child=e.child,t.flags|=128,t=null);else if(po(t),Ef(c)){if(s=c.nextSibling&&c.nextSibling.dataset,s)var u=s.dgst;s=u,r=Error(i(419)),r.stack=``,r.digest=s,ea({value:r,source:null,stack:null}),t=Fc(e,t,n)}else if(pc||ca(e,t,n,!1),s=(n&e.childLanes)!==0,pc||s){if(s=Ql,s!==null&&(r=ut(s,n),r!==0&&r!==l.retryLane))throw l.retryLane=r,pi(e,r),Mu(s,e,r),fc;Tf(c)||Wu(),t=Fc(e,t,n)}else Tf(c)?(t.flags|=192,t.child=e.child,t=null):(e=l.treeContext,k=Of(c.nextSibling),Ui=t,Wi=!0,Gi=null,Ki=!1,e!==null&&Hi(t,e),t=Nc(t,r.children),t.flags|=4096);return t}return a?(go(t),c=r.fallback,a=t.mode,l=e.child,u=l.sibling,r=bi(l,{mode:`hidden`,children:r.children}),r.subtreeFlags=l.subtreeFlags&65011712,u===null?(c=Ci(c,a,n,null),c.flags|=2):c=bi(u,c),c.return=t,r.return=t,r.sibling=c,t.child=r,yc(null,r),r=t.child,c=e.child.memoizedState,c===null?c=Ac(n):(a=c.cachePool,a===null?a=Aa():(l=_a._currentValue,a=a.parent===l?a:{parent:l,pool:l}),c={baseLanes:c.baseLanes|n,cachePool:a}),r.memoizedState=c,r.childLanes=jc(e,s,n),t.memoizedState=kc,yc(e.child,r)):(po(t),n=e.child,e=n.sibling,n=bi(n,{mode:`visible`,children:r.children}),n.return=t,n.sibling=null,e!==null&&(s=t.deletions,s===null?(t.deletions=[e],t.flags|=16):s.push(e)),t.child=n,t.memoizedState=null,n)}function Nc(e,t){return t=Pc({mode:`visible`,children:t},e.mode),t.return=e,e.child=t}function Pc(e,t){return e=vi(22,e,null,t),e.lanes=0,e}function Fc(e,t,n){return Ka(t,e.child,null,n),e=Nc(t,t.pendingProps.children),e.flags|=2,t.memoizedState=null,e}function Ic(e,t,n){e.lanes|=t;var r=e.alternate;r!==null&&(r.lanes|=t),oa(e.return,t,n)}function Lc(e,t,n,r,i,a){var o=e.memoizedState;o===null?e.memoizedState={isBackwards:t,rendering:null,renderingStartTime:0,last:r,tail:n,tailMode:i,treeForkCount:a}:(o.isBackwards=t,o.rendering=null,o.renderingStartTime=0,o.last=r,o.tail=n,o.tailMode=i,o.treeForkCount=a)}function Rc(e,t,n){var r=t.pendingProps,i=r.revealOrder,a=r.tail;r=r.children;var o=vo.current,s=!!(o&2);if(s?(o=o&1|2,t.flags|=128):o&=1,me(vo,o),mc(e,t,r,n),r=Wi?Mi:0,!s&&e!==null&&e.flags&128)a:for(e=t.child;e!==null;){if(e.tag===13)e.memoizedState!==null&&Ic(e,n,t);else if(e.tag===19)Ic(e,n,t);else if(e.child!==null){e.child.return=e,e=e.child;continue}if(e===t)break a;for(;e.sibling===null;){if(e.return===null||e.return===t)break a;e=e.return}e.sibling.return=e.return,e=e.sibling}switch(i){case`forwards`:for(n=t.child,i=null;n!==null;)e=n.alternate,e!==null&&yo(e)===null&&(i=n),n=n.sibling;n=i,n===null?(i=t.child,t.child=null):(i=n.sibling,n.sibling=null),Lc(t,!1,i,n,a,r);break;case`backwards`:case`unstable_legacy-backwards`:for(n=null,i=t.child,t.child=null;i!==null;){if(e=i.alternate,e!==null&&yo(e)===null){t.child=i;break}e=i.sibling,i.sibling=n,n=i,i=e}Lc(t,!0,n,null,a,r);break;case`together`:Lc(t,!1,null,null,void 0,r);break;default:t.memoizedState=null}return t.child}function zc(e,t,n){if(e!==null&&(t.dependencies=e.dependencies),cu|=t.lanes,(n&t.childLanes)===0){if(e!==null){if(ca(e,t,n,!1),(n&t.childLanes)===0)return null}else return null}if(e!==null&&t.child!==e.child)throw Error(i(153));if(t.child!==null){for(e=t.child,n=bi(e,e.pendingProps),t.child=n,n.return=t;e.sibling!==null;)e=e.sibling,n=n.sibling=bi(e,e.pendingProps),n.return=t;n.sibling=null}return t.child}function Bc(e,t){return(e.lanes&t)!==0||(e=e.dependencies,!!(e!==null&&la(e)))}function Vc(e,t,n){switch(t.tag){case 3:ye(t,t.stateNode.containerInfo),ia(t,_a,e.memoizedState.cache),Qi();break;case 27:case 5:xe(t);break;case 4:ye(t,t.stateNode.containerInfo);break;case 10:ia(t,t.type,t.memoizedProps.value);break;case 31:if(t.memoizedState!==null)return t.flags|=128,mo(t),null;break;case 13:var r=t.memoizedState;if(r!==null)return r.dehydrated===null?(n&t.child.childLanes)===0?(po(t),e=zc(e,t,n),e===null?null:e.sibling):Mc(e,t,n):(po(t),t.flags|=128,null);po(t);break;case 19:var i=!!(e.flags&128);if(r=(n&t.childLanes)!==0,r||=(ca(e,t,n,!1),(n&t.childLanes)!==0),i){if(r)return Rc(e,t,n);t.flags|=128}if(i=t.memoizedState,i!==null&&(i.rendering=null,i.tail=null,i.lastEffect=null),me(vo,vo.current),r)break;return null;case 22:return t.lanes=0,vc(e,t,n,t.pendingProps);case 24:ia(t,_a,e.memoizedState.cache)}return zc(e,t,n)}function Hc(e,t,n){if(e!==null){if(e.memoizedProps!==t.pendingProps)pc=!0;else{if(!Bc(e,n)&&!(t.flags&128))return pc=!1,Vc(e,t,n);pc=!!(e.flags&131072)}}else pc=!1,Wi&&t.flags&1048576&&zi(t,Mi,t.index);switch(t.lanes=0,t.tag){case 16:a:{var r=t.pendingProps;if(e=Ia(t.elementType),t.type=e,typeof e==`function`)yi(e)?(r=nc(e,r),t.tag=1,t=Dc(null,t,e,r,n)):(t.tag=0,t=Tc(null,t,e,r,n));else{if(e!=null){var a=e.$$typeof;if(a===w){t.tag=11,t=hc(null,t,e,r,n);break a}if(a===te){t.tag=14,t=gc(null,t,e,r,n);break a}}throw t=oe(e)||e,Error(i(306,t,``))}}return t;case 0:return Tc(e,t,t.type,t.pendingProps,n);case 1:return r=t.type,a=nc(r,t.pendingProps),Dc(e,t,r,a,n);case 3:a:{if(ye(t,t.stateNode.containerInfo),e===null)throw Error(i(387));r=t.pendingProps;var o=t.memoizedState;a=o.element,Xa(e,t),no(t,r,null,n);var s=t.memoizedState;if(r=s.cache,ia(t,_a,r),r!==o.cache&&sa(t,[_a],n,!0),to(),r=s.element,o.isDehydrated){if(o={element:r,isDehydrated:!1,cache:s.cache},t.updateQueue.baseState=o,t.memoizedState=o,t.flags&256){t=Oc(e,t,r,n);break a}if(r!==a){a=Oi(Error(i(424)),t),ea(a),t=Oc(e,t,r,n);break a}switch(e=t.stateNode.containerInfo,e.nodeType){case 9:e=e.body;break;default:e=e.nodeName===`HTML`?e.ownerDocument.body:e}for(k=Of(e.firstChild),Ui=t,Wi=!0,Gi=null,Ki=!0,n=qa(t,null,r,n),t.child=n;n;)n.flags=n.flags&-3|4096,n=n.sibling}else{if(Qi(),r===a){t=zc(e,t,n);break a}mc(e,t,r,n)}t=t.child}return t;case 26:return wc(e,t),e===null?(n=Jf(t.type,null,t.pendingProps,null))?t.memoizedState=n:Wi||(n=t.type,e=t.pendingProps,r=sf(_e.current).createElement(n),r[gt]=t,r[_t]=e,ef(r,n,e),kt(r),t.stateNode=r):t.memoizedState=Jf(t.type,e.memoizedProps,t.pendingProps,e.memoizedState),null;case 27:return xe(t),e===null&&Wi&&(r=t.stateNode=Mf(t.type,t.pendingProps,_e.current),Ui=t,Ki=!0,a=k,vf(t.type)?(kf=a,k=Of(r.firstChild)):k=a),mc(e,t,t.pendingProps.children,n),wc(e,t),e===null&&(t.flags|=4194304),t.child;case 5:return e===null&&Wi&&((a=r=k)&&(r=Sf(r,t.type,t.pendingProps,Ki),r===null?a=!1:(t.stateNode=r,Ui=t,k=Of(r.firstChild),Ki=!1,a=!0)),a||Ji(t)),xe(t),a=t.type,o=t.pendingProps,s=e===null?null:e.memoizedProps,r=o.children,uf(a,o)?r=null:s!==null&&uf(a,s)&&(t.flags|=32),t.memoizedState!==null&&(a=No(e,t,N,null,null,n),mp._currentValue=a),wc(e,t),mc(e,t,r,n),t.child;case 6:return e===null&&Wi&&((e=n=k)&&(n=Cf(n,t.pendingProps,Ki),n===null?e=!1:(t.stateNode=n,Ui=t,k=null,e=!0)),e||Ji(t)),null;case 13:return Mc(e,t,n);case 4:return ye(t,t.stateNode.containerInfo),r=t.pendingProps,e===null?t.child=Ka(t,null,r,n):mc(e,t,r,n),t.child;case 11:return hc(e,t,t.type,t.pendingProps,n);case 7:return mc(e,t,t.pendingProps,n),t.child;case 8:return mc(e,t,t.pendingProps.children,n),t.child;case 12:return mc(e,t,t.pendingProps.children,n),t.child;case 10:return r=t.pendingProps,ia(t,t.type,r.value),mc(e,t,r.children,n),t.child;case 9:return a=t.type._context,r=t.pendingProps.children,ua(t),a=da(a),r=r(a),t.flags|=1,mc(e,t,r,n),t.child;case 14:return gc(e,t,t.type,t.pendingProps,n);case 15:return _c(e,t,t.type,t.pendingProps,n);case 19:return Rc(e,t,n);case 31:return Cc(e,t,n);case 22:return vc(e,t,n,t.pendingProps);case 24:return ua(t),r=da(_a),e===null?(a=A(),a===null&&(a=Ql,o=va(),a.pooledCache=o,o.refCount++,o!==null&&(a.pooledCacheLanes|=n),a=o),t.memoizedState={parent:r,cache:a},Ya(t),ia(t,_a,a)):((e.lanes&n)!==0&&(Xa(e,t),no(t,null,null,n),to()),a=e.memoizedState,o=t.memoizedState,a.parent===r?(r=o.cache,ia(t,_a,r),r!==a.cache&&sa(t,[_a],n,!0)):(a={parent:r,cache:r},t.memoizedState=a,t.lanes===0&&(t.memoizedState=t.updateQueue.baseState=a),ia(t,_a,r))),mc(e,t,t.pendingProps.children,n),t.child;case 29:throw t.pendingProps}throw Error(i(156,t.tag))}function Uc(e){e.flags|=4}function Wc(e,t,n,r,i){if((t=!!(e.mode&32))&&(t=!1),t){if(e.flags|=16777216,(i&335544128)===i){if(e.stateNode.complete)e.flags|=8192;else if(Vu())e.flags|=8192;else throw La=Na,ja}}else e.flags&=-16777217}function Gc(e,t){if(t.type!==`stylesheet`||t.state.loading&4)e.flags&=-16777217;else if(e.flags|=16777216,!lp(t)){if(Vu())e.flags|=8192;else throw La=Na,ja}}function Kc(e,t){t!==null&&(e.flags|=4),e.flags&16384&&(t=e.tag===22?536870912:it(),e.lanes|=t,fu|=t)}function qc(e,t){if(!Wi)switch(e.tailMode){case`hidden`:t=e.tail;for(var n=null;t!==null;)t.alternate!==null&&(n=t),t=t.sibling;n===null?e.tail=null:n.sibling=null;break;case`collapsed`:n=e.tail;for(var r=null;n!==null;)n.alternate!==null&&(r=n),n=n.sibling;r===null?t||e.tail===null?e.tail=null:e.tail.sibling=null:r.sibling=null}}function Jc(e){var t=e.alternate!==null&&e.alternate.child===e.child,n=0,r=0;if(t)for(var i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags&65011712,r|=i.flags&65011712,i.return=e,i=i.sibling;else for(i=e.child;i!==null;)n|=i.lanes|i.childLanes,r|=i.subtreeFlags,r|=i.flags,i.return=e,i=i.sibling;return e.subtreeFlags|=r,e.childLanes=n,t}function Yc(e,t,n){var r=t.pendingProps;switch(Vi(t),t.tag){case 16:case 15:case 0:case 11:case 7:case 8:case 12:case 9:case 14:return Jc(t),null;case 1:return Jc(t),null;case 3:return n=t.stateNode,r=null,e!==null&&(r=e.memoizedState.cache),t.memoizedState.cache!==r&&(t.flags|=2048),aa(_a),be(),n.pendingContext&&(n.context=n.pendingContext,n.pendingContext=null),(e===null||e.child===null)&&(Zi(t)?Uc(t):e===null||e.memoizedState.isDehydrated&&!(t.flags&256)||(t.flags|=1024,$i())),Jc(t),null;case 26:var a=t.type,o=t.memoizedState;return e===null?(Uc(t),o===null?(Jc(t),Wc(t,a,null,r,n)):(Jc(t),Gc(t,o))):o?o===e.memoizedState?(Jc(t),t.flags&=-16777217):(Uc(t),Jc(t),Gc(t,o)):(e=e.memoizedProps,e!==r&&Uc(t),Jc(t),Wc(t,a,e,r,n)),null;case 27:if(Se(t),n=_e.current,a=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==r&&Uc(t);else{if(!r){if(t.stateNode===null)throw Error(i(166));return Jc(t),null}e=he.current,Zi(t)?Yi(t,e):(e=Mf(a,r,n),t.stateNode=e,Uc(t))}return Jc(t),null;case 5:if(Se(t),a=t.type,e!==null&&t.stateNode!=null)e.memoizedProps!==r&&Uc(t);else{if(!r){if(t.stateNode===null)throw Error(i(166));return Jc(t),null}if(o=he.current,Zi(t))Yi(t,o);else{var s=sf(_e.current);switch(o){case 1:o=s.createElementNS(`http://www.w3.org/2000/svg`,a);break;case 2:o=s.createElementNS(`http://www.w3.org/1998/Math/MathML`,a);break;default:switch(a){case`svg`:o=s.createElementNS(`http://www.w3.org/2000/svg`,a);break;case`math`:o=s.createElementNS(`http://www.w3.org/1998/Math/MathML`,a);break;case`script`:o=s.createElement(`div`),o.innerHTML=`<script><\/script>`,o=o.removeChild(o.firstChild);break;case`select`:o=typeof r.is==`string`?s.createElement(`select`,{is:r.is}):s.createElement(`select`),r.multiple?o.multiple=!0:r.size&&(o.size=r.size);break;default:o=typeof r.is==`string`?s.createElement(a,{is:r.is}):s.createElement(a)}}o[gt]=t,o[_t]=r;a:for(s=t.child;s!==null;){if(s.tag===5||s.tag===6)o.appendChild(s.stateNode);else if(s.tag!==4&&s.tag!==27&&s.child!==null){s.child.return=s,s=s.child;continue}if(s===t)break a;for(;s.sibling===null;){if(s.return===null||s.return===t)break a;s=s.return}s.sibling.return=s.return,s=s.sibling}t.stateNode=o;a:switch(ef(o,a,r),a){case`button`:case`input`:case`select`:case`textarea`:r=!!r.autoFocus;break a;case`img`:r=!0;break a;default:r=!1}r&&Uc(t)}}return Jc(t),Wc(t,t.type,e===null?null:e.memoizedProps,t.pendingProps,n),null;case 6:if(e&&t.stateNode!=null)e.memoizedProps!==r&&Uc(t);else{if(typeof r!=`string`&&t.stateNode===null)throw Error(i(166));if(e=_e.current,Zi(t)){if(e=t.stateNode,n=t.memoizedProps,r=null,a=Ui,a!==null)switch(a.tag){case 27:case 5:r=a.memoizedProps}e[gt]=t,e=!!(e.nodeValue===n||r!==null&&!0===r.suppressHydrationWarning||Zd(e.nodeValue,n)),e||Ji(t,!0)}else e=sf(e).createTextNode(r),e[gt]=t,t.stateNode=e}return Jc(t),null;case 31:if(n=t.memoizedState,e===null||e.memoizedState!==null){if(r=Zi(t),n!==null){if(e===null){if(!r)throw Error(i(318));if(e=t.memoizedState,e=e===null?null:e.dehydrated,!e)throw Error(i(557));e[gt]=t}else Qi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Jc(t),e=!1}else n=$i(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=n),e=!0;if(!e)return t.flags&256?(_o(t),t):(_o(t),null);if(t.flags&128)throw Error(i(558))}return Jc(t),null;case 13:if(r=t.memoizedState,e===null||e.memoizedState!==null&&e.memoizedState.dehydrated!==null){if(a=Zi(t),r!==null&&r.dehydrated!==null){if(e===null){if(!a)throw Error(i(318));if(a=t.memoizedState,a=a===null?null:a.dehydrated,!a)throw Error(i(317));a[gt]=t}else Qi(),!(t.flags&128)&&(t.memoizedState=null),t.flags|=4;Jc(t),a=!1}else a=$i(),e!==null&&e.memoizedState!==null&&(e.memoizedState.hydrationErrors=a),a=!0;if(!a)return t.flags&256?(_o(t),t):(_o(t),null)}return _o(t),t.flags&128?(t.lanes=n,t):(n=r!==null,e=e!==null&&e.memoizedState!==null,n&&(r=t.child,a=null,r.alternate!==null&&r.alternate.memoizedState!==null&&r.alternate.memoizedState.cachePool!==null&&(a=r.alternate.memoizedState.cachePool.pool),o=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(o=r.memoizedState.cachePool.pool),o!==a&&(r.flags|=2048)),n!==e&&n&&(t.child.flags|=8192),Kc(t,t.updateQueue),Jc(t),null);case 4:return be(),e===null&&Vd(t.stateNode.containerInfo),Jc(t),null;case 10:return aa(t.type),Jc(t),null;case 19:if(pe(vo),r=t.memoizedState,r===null)return Jc(t),null;if(a=!!(t.flags&128),o=r.rendering,o===null){if(a)qc(r,!1);else{if(su!==0||e!==null&&e.flags&128)for(e=t.child;e!==null;){if(o=yo(e),o!==null){for(t.flags|=128,qc(r,!1),e=o.updateQueue,t.updateQueue=e,Kc(t,e),t.subtreeFlags=0,e=n,n=t.child;n!==null;)xi(n,e),n=n.sibling;return me(vo,vo.current&1|2),Wi&&Ri(t,r.treeForkCount),t.child}e=e.sibling}r.tail!==null&&Fe()>vu&&(t.flags|=128,a=!0,qc(r,!1),t.lanes=4194304)}}else{if(!a){if(e=yo(o),e!==null){if(t.flags|=128,a=!0,e=e.updateQueue,t.updateQueue=e,Kc(t,e),qc(r,!0),r.tail===null&&r.tailMode===`hidden`&&!o.alternate&&!Wi)return Jc(t),null}else 2*Fe()-r.renderingStartTime>vu&&n!==536870912&&(t.flags|=128,a=!0,qc(r,!1),t.lanes=4194304)}r.isBackwards?(o.sibling=t.child,t.child=o):(e=r.last,e===null?t.child=o:e.sibling=o,r.last=o)}return r.tail===null?(Jc(t),null):(e=r.tail,r.rendering=e,r.tail=e.sibling,r.renderingStartTime=Fe(),e.sibling=null,n=vo.current,me(vo,a?n&1|2:n&1),Wi&&Ri(t,r.treeForkCount),e);case 22:case 23:return _o(t),lo(),r=t.memoizedState!==null,e===null?r&&(t.flags|=8192):e.memoizedState!==null!==r&&(t.flags|=8192),r?n&536870912&&!(t.flags&128)&&(Jc(t),t.subtreeFlags&6&&(t.flags|=8192)):Jc(t),n=t.updateQueue,n!==null&&Kc(t,n.retryQueue),n=null,e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),r=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(r=t.memoizedState.cachePool.pool),r!==n&&(t.flags|=2048),e!==null&&pe(Oa),null;case 24:return n=null,e!==null&&(n=e.memoizedState.cache),t.memoizedState.cache!==n&&(t.flags|=2048),aa(_a),Jc(t),null;case 25:return null;case 30:return null}throw Error(i(156,t.tag))}function Xc(e,t){switch(Vi(t),t.tag){case 1:return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 3:return aa(_a),be(),e=t.flags,e&65536&&!(e&128)?(t.flags=e&-65537|128,t):null;case 26:case 27:case 5:return Se(t),null;case 31:if(t.memoizedState!==null){if(_o(t),t.alternate===null)throw Error(i(340));Qi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 13:if(_o(t),e=t.memoizedState,e!==null&&e.dehydrated!==null){if(t.alternate===null)throw Error(i(340));Qi()}return e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 19:return pe(vo),null;case 4:return be(),null;case 10:return aa(t.type),null;case 22:case 23:return _o(t),lo(),e!==null&&pe(Oa),e=t.flags,e&65536?(t.flags=e&-65537|128,t):null;case 24:return aa(_a),null;case 25:return null;default:return null}}function Zc(e,t){switch(Vi(t),t.tag){case 3:aa(_a),be();break;case 26:case 27:case 5:Se(t);break;case 4:be();break;case 31:t.memoizedState!==null&&_o(t);break;case 13:_o(t);break;case 19:pe(vo);break;case 10:aa(t.type);break;case 22:case 23:_o(t),lo(),e!==null&&pe(Oa);break;case 24:aa(_a)}}function Qc(e,t){try{var n=t.updateQueue,r=n===null?null:n.lastEffect;if(r!==null){var i=r.next;n=i;do{if((n.tag&e)===e){r=void 0;var a=n.create,o=n.inst;r=a(),o.destroy=r}n=n.next}while(n!==i)}}catch(e){cd(t,t.return,e)}}function $c(e,t,n){try{var r=t.updateQueue,i=r===null?null:r.lastEffect;if(i!==null){var a=i.next;r=a;do{if((r.tag&e)===e){var o=r.inst,s=o.destroy;if(s!==void 0){o.destroy=void 0,i=t;var c=n,l=s;try{l()}catch(e){cd(i,c,e)}}}r=r.next}while(r!==a)}}catch(e){cd(t,t.return,e)}}function el(e){var t=e.updateQueue;if(t!==null){var n=e.stateNode;try{io(t,n)}catch(t){cd(e,e.return,t)}}}function tl(e,t,n){n.props=nc(e.type,e.memoizedProps),n.state=e.memoizedState;try{n.componentWillUnmount()}catch(n){cd(e,t,n)}}function nl(e,t){try{var n=e.ref;if(n!==null){switch(e.tag){case 26:case 27:case 5:var r=e.stateNode;break;case 30:r=e.stateNode;break;default:r=e.stateNode}typeof n==`function`?e.refCleanup=n(r):n.current=r}}catch(n){cd(e,t,n)}}function rl(e,t){var n=e.ref,r=e.refCleanup;if(n!==null){if(typeof r==`function`)try{r()}catch(n){cd(e,t,n)}finally{e.refCleanup=null,e=e.alternate,e!=null&&(e.refCleanup=null)}else if(typeof n==`function`)try{n(null)}catch(n){cd(e,t,n)}else n.current=null}}function il(e){var t=e.type,n=e.memoizedProps,r=e.stateNode;try{a:switch(t){case`button`:case`input`:case`select`:case`textarea`:n.autoFocus&&r.focus();break a;case`img`:n.src?r.src=n.src:n.srcSet&&(r.srcset=n.srcSet)}}catch(t){cd(e,e.return,t)}}function al(e,t,n){try{var r=e.stateNode;tf(r,e.type,n,t),r[_t]=t}catch(t){cd(e,e.return,t)}}function ol(e){return e.tag===5||e.tag===3||e.tag===26||e.tag===27&&vf(e.type)||e.tag===4}function sl(e){a:for(;;){for(;e.sibling===null;){if(e.return===null||ol(e.return))return null;e=e.return}for(e.sibling.return=e.return,e=e.sibling;e.tag!==5&&e.tag!==6&&e.tag!==18;){if(e.tag===27&&vf(e.type)||e.flags&2||e.child===null||e.tag===4)continue a;e.child.return=e,e=e.child}if(!(e.flags&2))return e.stateNode}}function cl(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?(n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n).insertBefore(e,t):(t=n.nodeType===9?n.body:n.nodeName===`HTML`?n.ownerDocument.body:n,t.appendChild(e),n=n._reactRootContainer,n!=null||t.onclick!==null||(t.onclick=un));else if(r!==4&&(r===27&&vf(e.type)&&(n=e.stateNode,t=null),e=e.child,e!==null))for(cl(e,t,n),e=e.sibling;e!==null;)cl(e,t,n),e=e.sibling}function ll(e,t,n){var r=e.tag;if(r===5||r===6)e=e.stateNode,t?n.insertBefore(e,t):n.appendChild(e);else if(r!==4&&(r===27&&vf(e.type)&&(n=e.stateNode),e=e.child,e!==null))for(ll(e,t,n),e=e.sibling;e!==null;)ll(e,t,n),e=e.sibling}function ul(e){var t=e.stateNode,n=e.memoizedProps;try{for(var r=e.type,i=t.attributes;i.length;)t.removeAttributeNode(i[0]);ef(t,r,n),t[gt]=e,t[_t]=n}catch(t){cd(e,e.return,t)}}var dl=!1,fl=!1,pl=!1,ml=typeof WeakSet==`function`?WeakSet:Set,hl=null;function gl(e,t){if(e=e.containerInfo,af=bp,e=Lr(e),Rr(e)){if(`selectionStart`in e)var n={start:e.selectionStart,end:e.selectionEnd};else a:{n=(n=e.ownerDocument)&&n.defaultView||window;var r=n.getSelection&&n.getSelection();if(r&&r.rangeCount!==0){n=r.anchorNode;var a=r.anchorOffset,o=r.focusNode;r=r.focusOffset;try{n.nodeType,o.nodeType}catch{n=null;break a}var s=0,c=-1,l=-1,u=0,d=0,f=e,p=null;b:for(;;){for(var m;f!==n||a!==0&&f.nodeType!==3||(c=s+a),f!==o||r!==0&&f.nodeType!==3||(l=s+r),f.nodeType===3&&(s+=f.nodeValue.length),(m=f.firstChild)!==null;)p=f,f=m;for(;;){if(f===e)break b;if(p===n&&++u===a&&(c=s),p===o&&++d===r&&(l=s),(m=f.nextSibling)!==null)break;f=p,p=f.parentNode}f=m}n=c===-1||l===-1?null:{start:c,end:l}}else n=null}n||={start:0,end:0}}else n=null;for(of={focusedElem:e,selectionRange:n},bp=!1,hl=t;hl!==null;)if(t=hl,e=t.child,t.subtreeFlags&1028&&e!==null)e.return=t,hl=e;else for(;hl!==null;){switch(t=hl,o=t.alternate,e=t.flags,t.tag){case 0:if(e&4&&(e=t.updateQueue,e=e===null?null:e.events,e!==null))for(n=0;n<e.length;n++)a=e[n],a.ref.impl=a.nextImpl;break;case 11:case 15:break;case 1:if(e&1024&&o!==null){e=void 0,n=t,a=o.memoizedProps,o=o.memoizedState,r=n.stateNode;try{var h=nc(n.type,a);e=r.getSnapshotBeforeUpdate(h,o),r.__reactInternalSnapshotBeforeUpdate=e}catch(e){cd(n,n.return,e)}}break;case 3:if(e&1024){if(e=t.stateNode.containerInfo,n=e.nodeType,n===9)xf(e);else if(n===1)switch(e.nodeName){case`HEAD`:case`HTML`:case`BODY`:xf(e);break;default:e.textContent=``}}break;case 5:case 26:case 27:case 6:case 4:case 17:break;default:if(e&1024)throw Error(i(163))}if(e=t.sibling,e!==null){e.return=t.return,hl=e;break}hl=t.return}}function _l(e,t,n){var r=n.flags;switch(n.tag){case 0:case 11:case 15:Ml(e,n),r&4&&Qc(5,n);break;case 1:if(Ml(e,n),r&4){if(e=n.stateNode,t===null)try{e.componentDidMount()}catch(e){cd(n,n.return,e)}else{var i=nc(n.type,t.memoizedProps);t=t.memoizedState;try{e.componentDidUpdate(i,t,e.__reactInternalSnapshotBeforeUpdate)}catch(e){cd(n,n.return,e)}}}r&64&&el(n),r&512&&nl(n,n.return);break;case 3:if(Ml(e,n),r&64&&(e=n.updateQueue,e!==null)){if(t=null,n.child!==null)switch(n.child.tag){case 27:case 5:t=n.child.stateNode;break;case 1:t=n.child.stateNode}try{io(e,t)}catch(e){cd(n,n.return,e)}}break;case 27:t===null&&r&4&&ul(n);case 26:case 5:Ml(e,n),t===null&&r&4&&il(n),r&512&&nl(n,n.return);break;case 12:Ml(e,n);break;case 31:Ml(e,n),r&4&&Cl(e,n);break;case 13:Ml(e,n),r&4&&wl(e,n),r&64&&(e=n.memoizedState,e!==null&&(e=e.dehydrated,e!==null&&(n=fd.bind(null,n),Df(e,n))));break;case 22:if(r=n.memoizedState!==null||dl,!r){t=t!==null&&t.memoizedState!==null||fl,i=dl;var a=fl;dl=r,(fl=t)&&!a?Pl(e,n,!!(n.subtreeFlags&8772)):Ml(e,n),dl=i,fl=a}break;case 30:break;default:Ml(e,n)}}function vl(e){var t=e.alternate;t!==null&&(e.alternate=null,vl(t)),e.child=null,e.deletions=null,e.sibling=null,e.tag===5&&(t=e.stateNode,t!==null&&wt(t)),e.stateNode=null,e.return=null,e.dependencies=null,e.memoizedProps=null,e.memoizedState=null,e.pendingProps=null,e.stateNode=null,e.updateQueue=null}var yl=null,bl=!1;function xl(e,t,n){for(n=n.child;n!==null;)Sl(e,t,n),n=n.sibling}function Sl(e,t,n){if(Ge&&typeof Ge.onCommitFiberUnmount==`function`)try{Ge.onCommitFiberUnmount(We,n)}catch{}switch(n.tag){case 26:fl||rl(n,t),xl(e,t,n),n.memoizedState?n.memoizedState.count--:n.stateNode&&(n=n.stateNode,n.parentNode.removeChild(n));break;case 27:fl||rl(n,t);var r=yl,i=bl;vf(n.type)&&(yl=n.stateNode,bl=!1),xl(e,t,n),Nf(n.stateNode),yl=r,bl=i;break;case 5:fl||rl(n,t);case 6:if(r=yl,i=bl,yl=null,xl(e,t,n),yl=r,bl=i,yl!==null){if(bl)try{(yl.nodeType===9?yl.body:yl.nodeName===`HTML`?yl.ownerDocument.body:yl).removeChild(n.stateNode)}catch(e){cd(n,t,e)}else try{yl.removeChild(n.stateNode)}catch(e){cd(n,t,e)}}break;case 18:yl!==null&&(bl?(e=yl,yf(e.nodeType===9?e.body:e.nodeName===`HTML`?e.ownerDocument.body:e,n.stateNode),Gp(e)):yf(yl,n.stateNode));break;case 4:r=yl,i=bl,yl=n.stateNode.containerInfo,bl=!0,xl(e,t,n),yl=r,bl=i;break;case 0:case 11:case 14:case 15:$c(2,n,t),fl||$c(4,n,t),xl(e,t,n);break;case 1:fl||(rl(n,t),r=n.stateNode,typeof r.componentWillUnmount==`function`&&tl(n,t,r)),xl(e,t,n);break;case 21:xl(e,t,n);break;case 22:fl=(r=fl)||n.memoizedState!==null,xl(e,t,n),fl=r;break;default:xl(e,t,n)}}function Cl(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null))){e=e.dehydrated;try{Gp(e)}catch(e){cd(t,t.return,e)}}}function wl(e,t){if(t.memoizedState===null&&(e=t.alternate,e!==null&&(e=e.memoizedState,e!==null&&(e=e.dehydrated,e!==null))))try{Gp(e)}catch(e){cd(t,t.return,e)}}function Tl(e){switch(e.tag){case 31:case 13:case 19:var t=e.stateNode;return t===null&&(t=e.stateNode=new ml),t;case 22:return e=e.stateNode,t=e._retryCache,t===null&&(t=e._retryCache=new ml),t;default:throw Error(i(435,e.tag))}}function El(e,t){var n=Tl(e);t.forEach(function(t){if(!n.has(t)){n.add(t);var r=pd.bind(null,e,t);t.then(r,r)}})}function Dl(e,t){var n=t.deletions;if(n!==null)for(var r=0;r<n.length;r++){var a=n[r],o=e,s=t,c=s;a:for(;c!==null;){switch(c.tag){case 27:if(vf(c.type)){yl=c.stateNode,bl=!1;break a}break;case 5:yl=c.stateNode,bl=!1;break a;case 3:case 4:yl=c.stateNode.containerInfo,bl=!0;break a}c=c.return}if(yl===null)throw Error(i(160));Sl(o,s,a),yl=null,bl=!1,o=a.alternate,o!==null&&(o.return=null),a.return=null}if(t.subtreeFlags&13886)for(t=t.child;t!==null;)kl(t,e),t=t.sibling}var Ol=null;function kl(e,t){var n=e.alternate,r=e.flags;switch(e.tag){case 0:case 11:case 14:case 15:Dl(t,e),Al(e),r&4&&($c(3,e,e.return),Qc(3,e),$c(5,e,e.return));break;case 1:Dl(t,e),Al(e),r&512&&(fl||n===null||rl(n,n.return)),r&64&&dl&&(e=e.updateQueue,e!==null&&(r=e.callbacks,r!==null&&(n=e.shared.hiddenCallbacks,e.shared.hiddenCallbacks=n===null?r:n.concat(r))));break;case 26:var a=Ol;if(Dl(t,e),Al(e),r&512&&(fl||n===null||rl(n,n.return)),r&4){var o=n===null?null:n.memoizedState;if(r=e.memoizedState,n===null){if(r===null){if(e.stateNode===null){a:{r=e.type,n=e.memoizedProps,a=a.ownerDocument||a;b:switch(r){case`title`:o=a.getElementsByTagName(`title`)[0],(!o||o[Ct]||o[gt]||o.namespaceURI===`http://www.w3.org/2000/svg`||o.hasAttribute(`itemprop`))&&(o=a.createElement(r),a.head.insertBefore(o,a.querySelector(`head > title`))),ef(o,r,n),o[gt]=e,kt(o),r=o;break a;case`link`:var s=op(`link`,`href`,a).get(r+(n.href||``));if(s){for(var c=0;c<s.length;c++)if(o=s[c],o.getAttribute(`href`)===(n.href==null||n.href===``?null:n.href)&&o.getAttribute(`rel`)===(n.rel==null?null:n.rel)&&o.getAttribute(`title`)===(n.title==null?null:n.title)&&o.getAttribute(`crossorigin`)===(n.crossOrigin==null?null:n.crossOrigin)){s.splice(c,1);break b}}o=a.createElement(r),ef(o,r,n),a.head.appendChild(o);break;case`meta`:if(s=op(`meta`,`content`,a).get(r+(n.content||``))){for(c=0;c<s.length;c++)if(o=s[c],o.getAttribute(`content`)===(n.content==null?null:``+n.content)&&o.getAttribute(`name`)===(n.name==null?null:n.name)&&o.getAttribute(`property`)===(n.property==null?null:n.property)&&o.getAttribute(`http-equiv`)===(n.httpEquiv==null?null:n.httpEquiv)&&o.getAttribute(`charset`)===(n.charSet==null?null:n.charSet)){s.splice(c,1);break b}}o=a.createElement(r),ef(o,r,n),a.head.appendChild(o);break;default:throw Error(i(468,r))}o[gt]=e,kt(o),r=o}e.stateNode=r}else sp(a,e.type,e.stateNode)}else e.stateNode=tp(a,r,e.memoizedProps)}else o===r?r===null&&e.stateNode!==null&&al(e,e.memoizedProps,n.memoizedProps):(o===null?n.stateNode!==null&&(n=n.stateNode,n.parentNode.removeChild(n)):o.count--,r===null?sp(a,e.type,e.stateNode):tp(a,r,e.memoizedProps))}break;case 27:Dl(t,e),Al(e),r&512&&(fl||n===null||rl(n,n.return)),n!==null&&r&4&&al(e,e.memoizedProps,n.memoizedProps);break;case 5:if(Dl(t,e),Al(e),r&512&&(fl||n===null||rl(n,n.return)),e.flags&32){a=e.stateNode;try{tn(a,``)}catch(t){cd(e,e.return,t)}}r&4&&e.stateNode!=null&&(a=e.memoizedProps,al(e,a,n===null?a:n.memoizedProps)),r&1024&&(pl=!0);break;case 6:if(Dl(t,e),Al(e),r&4){if(e.stateNode===null)throw Error(i(162));r=e.memoizedProps,n=e.stateNode;try{n.nodeValue=r}catch(t){cd(e,e.return,t)}}break;case 3:if(ap=null,a=Ol,Ol=If(t.containerInfo),Dl(t,e),Ol=a,Al(e),r&4&&n!==null&&n.memoizedState.isDehydrated)try{Gp(t.containerInfo)}catch(t){cd(e,e.return,t)}pl&&(pl=!1,jl(e));break;case 4:r=Ol,Ol=If(e.stateNode.containerInfo),Dl(t,e),Al(e),Ol=r;break;case 12:Dl(t,e),Al(e);break;case 31:Dl(t,e),Al(e),r&4&&(r=e.updateQueue,r!==null&&(e.updateQueue=null,El(e,r)));break;case 13:Dl(t,e),Al(e),e.child.flags&8192&&e.memoizedState!==null!=(n!==null&&n.memoizedState!==null)&&(gu=Fe()),r&4&&(r=e.updateQueue,r!==null&&(e.updateQueue=null,El(e,r)));break;case 22:a=e.memoizedState!==null;var l=n!==null&&n.memoizedState!==null,u=dl,d=fl;if(dl=u||a,fl=d||l,Dl(t,e),fl=d,dl=u,Al(e),r&8192)a:for(t=e.stateNode,t._visibility=a?t._visibility&-2:t._visibility|1,a&&(n===null||l||dl||fl||Nl(e)),n=null,t=e;;){if(t.tag===5||t.tag===26){if(n===null){l=n=t;try{if(o=l.stateNode,a)s=o.style,typeof s.setProperty==`function`?s.setProperty(`display`,`none`,`important`):s.display=`none`;else{c=l.stateNode;var f=l.memoizedProps.style,p=f!=null&&f.hasOwnProperty(`display`)?f.display:null;c.style.display=p==null||typeof p==`boolean`?``:(``+p).trim()}}catch(e){cd(l,l.return,e)}}}else if(t.tag===6){if(n===null){l=t;try{l.stateNode.nodeValue=a?``:l.memoizedProps}catch(e){cd(l,l.return,e)}}}else if(t.tag===18){if(n===null){l=t;try{var m=l.stateNode;a?bf(m,!0):bf(l.stateNode,!1)}catch(e){cd(l,l.return,e)}}}else if((t.tag!==22&&t.tag!==23||t.memoizedState===null||t===e)&&t.child!==null){t.child.return=t,t=t.child;continue}if(t===e)break a;for(;t.sibling===null;){if(t.return===null||t.return===e)break a;n===t&&(n=null),t=t.return}n===t&&(n=null),t.sibling.return=t.return,t=t.sibling}r&4&&(r=e.updateQueue,r!==null&&(n=r.retryQueue,n!==null&&(r.retryQueue=null,El(e,n))));break;case 19:Dl(t,e),Al(e),r&4&&(r=e.updateQueue,r!==null&&(e.updateQueue=null,El(e,r)));break;case 30:break;case 21:break;default:Dl(t,e),Al(e)}}function Al(e){var t=e.flags;if(t&2){try{for(var n,r=e.return;r!==null;){if(ol(r)){n=r;break}r=r.return}if(n==null)throw Error(i(160));switch(n.tag){case 27:var a=n.stateNode;ll(e,sl(e),a);break;case 5:var o=n.stateNode;n.flags&32&&(tn(o,``),n.flags&=-33),ll(e,sl(e),o);break;case 3:case 4:var s=n.stateNode.containerInfo;cl(e,sl(e),s);break;default:throw Error(i(161))}}catch(t){cd(e,e.return,t)}e.flags&=-3}t&4096&&(e.flags&=-4097)}function jl(e){if(e.subtreeFlags&1024)for(e=e.child;e!==null;){var t=e;jl(t),t.tag===5&&t.flags&1024&&t.stateNode.reset(),e=e.sibling}}function Ml(e,t){if(t.subtreeFlags&8772)for(t=t.child;t!==null;)_l(e,t.alternate,t),t=t.sibling}function Nl(e){for(e=e.child;e!==null;){var t=e;switch(t.tag){case 0:case 11:case 14:case 15:$c(4,t,t.return),Nl(t);break;case 1:rl(t,t.return);var n=t.stateNode;typeof n.componentWillUnmount==`function`&&tl(t,t.return,n),Nl(t);break;case 27:Nf(t.stateNode);case 26:case 5:rl(t,t.return),Nl(t);break;case 22:t.memoizedState===null&&Nl(t);break;case 30:Nl(t);break;default:Nl(t)}e=e.sibling}}function Pl(e,t,n){for(n&&=!!(t.subtreeFlags&8772),t=t.child;t!==null;){var r=t.alternate,i=e,a=t,o=a.flags;switch(a.tag){case 0:case 11:case 15:Pl(i,a,n),Qc(4,a);break;case 1:if(Pl(i,a,n),r=a,i=r.stateNode,typeof i.componentDidMount==`function`)try{i.componentDidMount()}catch(e){cd(r,r.return,e)}if(r=a,i=r.updateQueue,i!==null){var s=r.stateNode;try{var c=i.shared.hiddenCallbacks;if(c!==null)for(i.shared.hiddenCallbacks=null,i=0;i<c.length;i++)ro(c[i],s)}catch(e){cd(r,r.return,e)}}n&&o&64&&el(a),nl(a,a.return);break;case 27:ul(a);case 26:case 5:Pl(i,a,n),n&&r===null&&o&4&&il(a),nl(a,a.return);break;case 12:Pl(i,a,n);break;case 31:Pl(i,a,n),n&&o&4&&Cl(i,a);break;case 13:Pl(i,a,n),n&&o&4&&wl(i,a);break;case 22:a.memoizedState===null&&Pl(i,a,n),nl(a,a.return);break;case 30:break;default:Pl(i,a,n)}t=t.sibling}}function Fl(e,t){var n=null;e!==null&&e.memoizedState!==null&&e.memoizedState.cachePool!==null&&(n=e.memoizedState.cachePool.pool),e=null,t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(e=t.memoizedState.cachePool.pool),e!==n&&(e!=null&&e.refCount++,n!=null&&ya(n))}function Il(e,t){e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&ya(e))}function Ll(e,t,n,r){if(t.subtreeFlags&10256)for(t=t.child;t!==null;)Rl(e,t,n,r),t=t.sibling}function Rl(e,t,n,r){var i=t.flags;switch(t.tag){case 0:case 11:case 15:Ll(e,t,n,r),i&2048&&Qc(9,t);break;case 1:Ll(e,t,n,r);break;case 3:Ll(e,t,n,r),i&2048&&(e=null,t.alternate!==null&&(e=t.alternate.memoizedState.cache),t=t.memoizedState.cache,t!==e&&(t.refCount++,e!=null&&ya(e)));break;case 12:if(i&2048){Ll(e,t,n,r),e=t.stateNode;try{var a=t.memoizedProps,o=a.id,s=a.onPostCommit;typeof s==`function`&&s(o,t.alternate===null?`mount`:`update`,e.passiveEffectDuration,-0)}catch(e){cd(t,t.return,e)}}else Ll(e,t,n,r);break;case 31:Ll(e,t,n,r);break;case 13:Ll(e,t,n,r);break;case 23:break;case 22:a=t.stateNode,o=t.alternate,t.memoizedState===null?a._visibility&2?Ll(e,t,n,r):(a._visibility|=2,zl(e,t,n,r,!!(t.subtreeFlags&10256)||!1)):a._visibility&2?Ll(e,t,n,r):Bl(e,t),i&2048&&Fl(o,t);break;case 24:Ll(e,t,n,r),i&2048&&Il(t.alternate,t);break;default:Ll(e,t,n,r)}}function zl(e,t,n,r,i){for(i&&=!!(t.subtreeFlags&10256)||!1,t=t.child;t!==null;){var a=e,o=t,s=n,c=r,l=o.flags;switch(o.tag){case 0:case 11:case 15:zl(a,o,s,c,i),Qc(8,o);break;case 23:break;case 22:var u=o.stateNode;o.memoizedState===null?(u._visibility|=2,zl(a,o,s,c,i)):u._visibility&2?zl(a,o,s,c,i):Bl(a,o),i&&l&2048&&Fl(o.alternate,o);break;case 24:zl(a,o,s,c,i),i&&l&2048&&Il(o.alternate,o);break;default:zl(a,o,s,c,i)}t=t.sibling}}function Bl(e,t){if(t.subtreeFlags&10256)for(t=t.child;t!==null;){var n=e,r=t,i=r.flags;switch(r.tag){case 22:Bl(n,r),i&2048&&Fl(r.alternate,r);break;case 24:Bl(n,r),i&2048&&Il(r.alternate,r);break;default:Bl(n,r)}t=t.sibling}}var Vl=8192;function Hl(e,t,n){if(e.subtreeFlags&Vl)for(e=e.child;e!==null;)Ul(e,t,n),e=e.sibling}function Ul(e,t,n){switch(e.tag){case 26:Hl(e,t,n),e.flags&Vl&&e.memoizedState!==null&&up(n,Ol,e.memoizedState,e.memoizedProps);break;case 5:Hl(e,t,n);break;case 3:case 4:var r=Ol;Ol=If(e.stateNode.containerInfo),Hl(e,t,n),Ol=r;break;case 22:e.memoizedState===null&&(r=e.alternate,r!==null&&r.memoizedState!==null?(r=Vl,Vl=16777216,Hl(e,t,n),Vl=r):Hl(e,t,n));break;default:Hl(e,t,n)}}function Wl(e){var t=e.alternate;if(t!==null&&(e=t.child,e!==null)){t.child=null;do t=e.sibling,e.sibling=null,e=t;while(e!==null)}}function Gl(e){var t=e.deletions;if(e.flags&16){if(t!==null)for(var n=0;n<t.length;n++){var r=t[n];hl=r,Jl(r,e)}Wl(e)}if(e.subtreeFlags&10256)for(e=e.child;e!==null;)Kl(e),e=e.sibling}function Kl(e){switch(e.tag){case 0:case 11:case 15:Gl(e),e.flags&2048&&$c(9,e,e.return);break;case 3:Gl(e);break;case 12:Gl(e);break;case 22:var t=e.stateNode;e.memoizedState!==null&&t._visibility&2&&(e.return===null||e.return.tag!==13)?(t._visibility&=-3,ql(e)):Gl(e);break;default:Gl(e)}}function ql(e){var t=e.deletions;if(e.flags&16){if(t!==null)for(var n=0;n<t.length;n++){var r=t[n];hl=r,Jl(r,e)}Wl(e)}for(e=e.child;e!==null;){switch(t=e,t.tag){case 0:case 11:case 15:$c(8,t,t.return),ql(t);break;case 22:n=t.stateNode,n._visibility&2&&(n._visibility&=-3,ql(t));break;default:ql(t)}e=e.sibling}}function Jl(e,t){for(;hl!==null;){var n=hl;switch(n.tag){case 0:case 11:case 15:$c(8,n,t);break;case 23:case 22:if(n.memoizedState!==null&&n.memoizedState.cachePool!==null){var r=n.memoizedState.cachePool.pool;r!=null&&r.refCount++}break;case 24:ya(n.memoizedState.cache)}if(r=n.child,r!==null)r.return=n,hl=r;else a:for(n=e;hl!==null;){r=hl;var i=r.sibling,a=r.return;if(vl(r),r===n){hl=null;break a}if(i!==null){i.return=a,hl=i;break a}hl=a}}}var Yl={getCacheForType:function(e){var t=da(_a),n=t.data.get(e);return n===void 0&&(n=e(),t.data.set(e,n)),n},cacheSignal:function(){return da(_a).controller.signal}},Xl=typeof WeakMap==`function`?WeakMap:Map,Zl=0,Ql=null,$l=null,eu=0,tu=0,nu=null,ru=!1,iu=!1,au=!1,ou=0,su=0,cu=0,lu=0,uu=0,du=0,fu=0,pu=null,mu=null,hu=!1,gu=0,_u=0,vu=1/0,yu=null,bu=null,xu=0,Su=null,Cu=null,wu=0,Tu=0,Eu=null,Du=null,Ou=0,ku=null;function Au(){return Zl&2&&eu!==0?eu&-eu:O.T===null?pt():kd()}function ju(){if(du===0){if(!(eu&536870912)||Wi){var e=Qe;Qe<<=1,!(Qe&3932160)&&(Qe=262144),du=e}else du=536870912}return e=uo.current,e!==null&&(e.flags|=32),du}function Mu(e,t,n){(e===Ql&&(tu===2||tu===9)||e.cancelPendingCommit!==null)&&(zu(e,0),Iu(e,eu,du,!1)),ot(e,n),(!(Zl&2)||e!==Ql)&&(e===Ql&&(!(Zl&2)&&(lu|=n),su===4&&Iu(e,eu,du,!1)),xd(e))}function Nu(e,t,n){if(Zl&6)throw Error(i(327));var r=!n&&!(t&127)&&(t&e.expiredLanes)===0||nt(e,t),a=r?qu(e,t):Gu(e,t,!0),o=r;do{if(a===0){iu&&!r&&Iu(e,t,0,!1);break}if(n=e.current.alternate,o&&!Fu(n)){a=Gu(e,t,!1),o=!1;continue}if(a===2){if(o=t,e.errorRecoveryDisabledLanes&o)var s=0;else s=e.pendingLanes&-536870913,s=s===0?s&536870912?536870912:0:s;if(s!==0){t=s;a:{var c=e;a=pu;var l=c.current.memoizedState.isDehydrated;if(l&&(zu(c,s).flags|=256),s=Gu(c,s,!1),s!==2){if(au&&!l){c.errorRecoveryDisabledLanes|=o,lu|=o,a=4;break a}o=mu,mu=a,o!==null&&(mu===null?mu=o:mu.push.apply(mu,o))}a=s}if(o=!1,a!==2)continue}}if(a===1){zu(e,0),Iu(e,t,0,!0);break}a:{switch(r=e,o=a,o){case 0:case 1:throw Error(i(345));case 4:if((t&4194048)!==t)break;case 6:Iu(r,t,du,!ru);break a;case 2:mu=null;break;case 3:case 5:break;default:throw Error(i(329))}if((t&62914560)===t&&(a=gu+300-Fe(),10<a)){if(Iu(r,t,du,!ru),tt(r,0,!0)!==0)break a;wu=t,r.timeoutHandle=pf(Pu.bind(null,r,n,mu,yu,hu,t,du,lu,fu,ru,o,`Throttled`,-0,0),a);break a}Pu(r,n,mu,yu,hu,t,du,lu,fu,ru,o,null,-0,0)}break}while(1);xd(e)}function Pu(e,t,n,r,i,a,o,s,c,l,u,d,f,p){if(e.timeoutHandle=-1,d=t.subtreeFlags,d&8192||(d&16785408)==16785408){d={stylesheets:null,count:0,imgCount:0,imgBytes:0,suspenseyImages:[],waitingForImages:!0,waitingForViewTransition:!1,unsuspend:un},Ul(t,a,d);var m=(a&62914560)===a?gu-Fe():(a&4194048)===a?_u-Fe():0;if(m=dp(d,m),m!==null){wu=a,e.cancelPendingCommit=m(ed.bind(null,e,t,a,n,r,i,o,s,c,u,d,null,f,p)),Iu(e,a,o,!l);return}}ed(e,t,a,n,r,i,o,s,c)}function Fu(e){for(var t=e;;){var n=t.tag;if((n===0||n===11||n===15)&&t.flags&16384&&(n=t.updateQueue,n!==null&&(n=n.stores,n!==null)))for(var r=0;r<n.length;r++){var i=n[r],a=i.getSnapshot;i=i.value;try{if(!Mr(a(),i))return!1}catch{return!1}}if(n=t.child,t.subtreeFlags&16384&&n!==null)n.return=t,t=n;else{if(t===e)break;for(;t.sibling===null;){if(t.return===null||t.return===e)return!0;t=t.return}t.sibling.return=t.return,t=t.sibling}}return!0}function Iu(e,t,n,r){t&=~uu,t&=~lu,e.suspendedLanes|=t,e.pingedLanes&=~t,r&&(e.warmLanes|=t),r=e.expirationTimes;for(var i=t;0<i;){var a=31-qe(i),o=1<<a;r[a]=-1,i&=~o}n!==0&&ct(e,n,t)}function Lu(){return Zl&6?!0:(Sd(0,!1),!1)}function Ru(){if($l!==null){if(tu===0)var e=$l.return;else e=$l,ra=na=null,Ro(e),Ba=null,Va=0,e=$l;for(;e!==null;)Zc(e.alternate,e),e=e.return;$l=null}}function zu(e,t){var n=e.timeoutHandle;n!==-1&&(e.timeoutHandle=-1,mf(n)),n=e.cancelPendingCommit,n!==null&&(e.cancelPendingCommit=null,n()),wu=0,Ru(),Ql=e,$l=n=bi(e.current,null),eu=t,tu=0,nu=null,ru=!1,iu=nt(e,t),au=!1,fu=du=uu=lu=cu=su=0,mu=pu=null,hu=!1,t&8&&(t|=t&32);var r=e.entangledLanes;if(r!==0)for(e=e.entanglements,r&=t;0<r;){var i=31-qe(r),a=1<<i;t|=e[i],r&=~a}return ou=t,ui(),n}function Bu(e,t){xo=null,O.H=Js,t===j||t===Ma?(t=Ra(),tu=3):t===ja?(t=Ra(),tu=4):tu=t===fc?8:typeof t==`object`&&t&&typeof t.then==`function`?6:1,nu=t,$l===null&&(su=1,oc(e,Oi(t,e.current)))}function Vu(){var e=uo.current;return e===null?!0:(eu&4194048)===eu?fo===null:(eu&62914560)===eu||eu&536870912?e===fo:!1}function Hu(){var e=O.H;return O.H=Js,e===null?Js:e}function Uu(){var e=O.A;return O.A=Yl,e}function Wu(){su=4,ru||(eu&4194048)!==eu&&uo.current!==null||(iu=!0),!(cu&134217727)&&!(lu&134217727)||Ql===null||Iu(Ql,eu,du,!1)}function Gu(e,t,n){var r=Zl;Zl|=2;var i=Hu(),a=Uu();(Ql!==e||eu!==t)&&(yu=null,zu(e,t)),t=!1;var o=su;a:do try{if(tu!==0&&$l!==null){var s=$l,c=nu;switch(tu){case 8:Ru(),o=6;break a;case 3:case 2:case 9:case 6:uo.current===null&&(t=!0);var l=tu;if(tu=0,nu=null,Zu(e,s,c,l),n&&iu){o=0;break a}break;default:l=tu,tu=0,nu=null,Zu(e,s,c,l)}}Ku(),o=su;break}catch(t){Bu(e,t)}while(1);return t&&e.shellSuspendCounter++,ra=na=null,Zl=r,O.H=i,O.A=a,$l===null&&(Ql=null,eu=0,ui()),o}function Ku(){for(;$l!==null;)Yu($l)}function qu(e,t){var n=Zl;Zl|=2;var r=Hu(),a=Uu();Ql!==e||eu!==t?(yu=null,vu=Fe()+500,zu(e,t)):iu=nt(e,t);a:do try{if(tu!==0&&$l!==null){t=$l;var o=nu;b:switch(tu){case 1:tu=0,nu=null,Zu(e,t,o,1);break;case 2:case 9:if(Pa(o)){tu=0,nu=null,Xu(t);break}t=function(){tu!==2&&tu!==9||Ql!==e||(tu=7),xd(e)},o.then(t,t);break a;case 3:tu=7;break a;case 4:tu=5;break a;case 7:Pa(o)?(tu=0,nu=null,Xu(t)):(tu=0,nu=null,Zu(e,t,o,7));break;case 5:var s=null;switch($l.tag){case 26:s=$l.memoizedState;case 5:case 27:var c=$l;if(s?lp(s):c.stateNode.complete){tu=0,nu=null;var l=c.sibling;if(l!==null)$l=l;else{var u=c.return;u===null?$l=null:($l=u,Qu(u))}break b}}tu=0,nu=null,Zu(e,t,o,5);break;case 6:tu=0,nu=null,Zu(e,t,o,6);break;case 8:Ru(),su=6;break a;default:throw Error(i(462))}}Ju();break}catch(t){Bu(e,t)}while(1);return ra=na=null,O.H=r,O.A=a,Zl=n,$l===null?(Ql=null,eu=0,ui(),su):0}function Ju(){for(;$l!==null&&!Ne();)Yu($l)}function Yu(e){var t=Hc(e.alternate,e,ou);e.memoizedProps=e.pendingProps,t===null?Qu(e):$l=t}function Xu(e){var t=e,n=t.alternate;switch(t.tag){case 15:case 0:t=Ec(n,t,t.pendingProps,t.type,void 0,eu);break;case 11:t=Ec(n,t,t.pendingProps,t.type.render,t.ref,eu);break;case 5:Ro(t);default:Zc(n,t),t=$l=xi(t,ou),t=Hc(n,t,ou)}e.memoizedProps=e.pendingProps,t===null?Qu(e):$l=t}function Zu(e,t,n,r){ra=na=null,Ro(t),Ba=null,Va=0;var i=t.return;try{if(dc(e,i,t,n,eu)){su=1,oc(e,Oi(n,e.current)),$l=null;return}}catch(t){if(i!==null)throw $l=i,t;su=1,oc(e,Oi(n,e.current)),$l=null;return}t.flags&32768?(Wi||r===1?e=!0:iu||eu&536870912?e=!1:(ru=e=!0,(r===2||r===9||r===3||r===6)&&(r=uo.current,r!==null&&r.tag===13&&(r.flags|=16384))),$u(t,e)):Qu(t)}function Qu(e){var t=e;do{if(t.flags&32768){$u(t,ru);return}e=t.return;var n=Yc(t.alternate,t,ou);if(n!==null){$l=n;return}if(t=t.sibling,t!==null){$l=t;return}$l=t=e}while(t!==null);su===0&&(su=5)}function $u(e,t){do{var n=Xc(e.alternate,e);if(n!==null){n.flags&=32767,$l=n;return}if(n=e.return,n!==null&&(n.flags|=32768,n.subtreeFlags=0,n.deletions=null),!t&&(e=e.sibling,e!==null)){$l=e;return}$l=e=n}while(e!==null);su=6,$l=null}function ed(e,t,n,r,a,o,s,c,l){e.cancelPendingCommit=null;do ad();while(xu!==0);if(Zl&6)throw Error(i(327));if(t!==null){if(t===e.current)throw Error(i(177));if(o=t.lanes|t.childLanes,o|=li,st(e,n,o,s,c,l),e===Ql&&($l=Ql=null,eu=0),Cu=t,Su=e,wu=n,Tu=o,Eu=a,Du=r,t.subtreeFlags&10256||t.flags&10256?(e.callbackNode=null,e.callbackPriority=0,md(ze,function(){return od(),null})):(e.callbackNode=null,e.callbackPriority=0),r=!!(t.flags&13878),t.subtreeFlags&13878||r){r=O.T,O.T=null,a=ce.p,ce.p=2,s=Zl,Zl|=4;try{gl(e,t,n)}finally{Zl=s,ce.p=a,O.T=r}}xu=1,td(),nd(),rd()}}function td(){if(xu===1){xu=0;var e=Su,t=Cu,n=!!(t.flags&13878);if(t.subtreeFlags&13878||n){n=O.T,O.T=null;var r=ce.p;ce.p=2;var i=Zl;Zl|=4;try{kl(t,e);var a=of,o=Lr(e.containerInfo),s=a.focusedElem,c=a.selectionRange;if(o!==s&&s&&s.ownerDocument&&Ir(s.ownerDocument.documentElement,s)){if(c!==null&&Rr(s)){var l=c.start,u=c.end;if(u===void 0&&(u=l),`selectionStart`in s)s.selectionStart=l,s.selectionEnd=Math.min(u,s.value.length);else{var d=s.ownerDocument||document,f=d&&d.defaultView||window;if(f.getSelection){var p=f.getSelection(),m=s.textContent.length,h=Math.min(c.start,m),g=c.end===void 0?h:Math.min(c.end,m);!p.extend&&h>g&&(o=g,g=h,h=o);var _=Fr(s,h),v=Fr(s,g);if(_&&v&&(p.rangeCount!==1||p.anchorNode!==_.node||p.anchorOffset!==_.offset||p.focusNode!==v.node||p.focusOffset!==v.offset)){var y=d.createRange();y.setStart(_.node,_.offset),p.removeAllRanges(),h>g?(p.addRange(y),p.extend(v.node,v.offset)):(y.setEnd(v.node,v.offset),p.addRange(y))}}}}for(d=[],p=s;p=p.parentNode;)p.nodeType===1&&d.push({element:p,left:p.scrollLeft,top:p.scrollTop});for(typeof s.focus==`function`&&s.focus(),s=0;s<d.length;s++){var b=d[s];b.element.scrollLeft=b.left,b.element.scrollTop=b.top}}bp=!!af,of=af=null}finally{Zl=i,ce.p=r,O.T=n}}e.current=t,xu=2}}function nd(){if(xu===2){xu=0;var e=Su,t=Cu,n=!!(t.flags&8772);if(t.subtreeFlags&8772||n){n=O.T,O.T=null;var r=ce.p;ce.p=2;var i=Zl;Zl|=4;try{_l(e,t.alternate,t)}finally{Zl=i,ce.p=r,O.T=n}}xu=3}}function rd(){if(xu===4||xu===3){xu=0,Pe();var e=Su,t=Cu,n=wu,r=Du;t.subtreeFlags&10256||t.flags&10256?xu=5:(xu=0,Cu=Su=null,id(e,e.pendingLanes));var i=e.pendingLanes;if(i===0&&(bu=null),ft(n),t=t.stateNode,Ge&&typeof Ge.onCommitFiberRoot==`function`)try{Ge.onCommitFiberRoot(We,t,void 0,(t.current.flags&128)==128)}catch{}if(r!==null){t=O.T,i=ce.p,ce.p=2,O.T=null;try{for(var a=e.onRecoverableError,o=0;o<r.length;o++){var s=r[o];a(s.value,{componentStack:s.stack})}}finally{O.T=t,ce.p=i}}wu&3&&ad(),xd(e),i=e.pendingLanes,n&261930&&i&42?e===ku?Ou++:(Ou=0,ku=e):Ou=0,Sd(0,!1)}}function id(e,t){(e.pooledCacheLanes&=t)===0&&(t=e.pooledCache,t!=null&&(e.pooledCache=null,ya(t)))}function ad(){return td(),nd(),rd(),od()}function od(){if(xu!==5)return!1;var e=Su,t=Tu;Tu=0;var n=ft(wu),r=O.T,a=ce.p;try{ce.p=32>n?32:n,O.T=null,n=Eu,Eu=null;var o=Su,s=wu;if(xu=0,Cu=Su=null,wu=0,Zl&6)throw Error(i(331));var c=Zl;if(Zl|=4,Kl(o.current),Rl(o,o.current,s,n),Zl=c,Sd(0,!1),Ge&&typeof Ge.onPostCommitFiberRoot==`function`)try{Ge.onPostCommitFiberRoot(We,o)}catch{}return!0}finally{ce.p=a,O.T=r,id(e,t)}}function sd(e,t,n){t=Oi(n,t),t=cc(e.stateNode,t,2),e=M(e,t,2),e!==null&&(ot(e,2),xd(e))}function cd(e,t,n){if(e.tag===3)sd(e,e,n);else for(;t!==null;){if(t.tag===3){sd(t,e,n);break}if(t.tag===1){var r=t.stateNode;if(typeof t.type.getDerivedStateFromError==`function`||typeof r.componentDidCatch==`function`&&(bu===null||!bu.has(r))){e=Oi(n,e),n=lc(2),r=M(t,n,2),r!==null&&(uc(n,r,t,e),ot(r,2),xd(r));break}}t=t.return}}function ld(e,t,n){var r=e.pingCache;if(r===null){r=e.pingCache=new Xl;var i=new Set;r.set(t,i)}else i=r.get(t),i===void 0&&(i=new Set,r.set(t,i));i.has(n)||(au=!0,i.add(n),e=ud.bind(null,e,t,n),t.then(e,e))}function ud(e,t,n){var r=e.pingCache;r!==null&&r.delete(t),e.pingedLanes|=e.suspendedLanes&n,e.warmLanes&=~n,Ql===e&&(eu&n)===n&&(su===4||su===3&&(eu&62914560)===eu&&300>Fe()-gu?!(Zl&2)&&zu(e,0):uu|=n,fu===eu&&(fu=0)),xd(e)}function dd(e,t){t===0&&(t=it()),e=pi(e,t),e!==null&&(ot(e,t),xd(e))}function fd(e){var t=e.memoizedState,n=0;t!==null&&(n=t.retryLane),dd(e,n)}function pd(e,t){var n=0;switch(e.tag){case 31:case 13:var r=e.stateNode,a=e.memoizedState;a!==null&&(n=a.retryLane);break;case 19:r=e.stateNode;break;case 22:r=e.stateNode._retryCache;break;default:throw Error(i(314))}r!==null&&r.delete(t),dd(e,n)}function md(e,t){return je(e,t)}var hd=null,gd=null,_d=!1,vd=!1,yd=!1,bd=0;function xd(e){e!==gd&&e.next===null&&(gd===null?hd=gd=e:gd=gd.next=e),vd=!0,_d||(_d=!0,Od())}function Sd(e,t){if(!yd&&vd){yd=!0;do for(var n=!1,r=hd;r!==null;){if(!t){if(e!==0){var i=r.pendingLanes;if(i===0)var a=0;else{var o=r.suspendedLanes,s=r.pingedLanes;a=(1<<31-qe(42|e)+1)-1,a&=i&~(o&~s),a=a&201326741?a&201326741|1:a?a|2:0}a!==0&&(n=!0,Dd(r,a))}else a=eu,a=tt(r,r===Ql?a:0,r.cancelPendingCommit!==null||r.timeoutHandle!==-1),!(a&3)||nt(r,a)||(n=!0,Dd(r,a))}r=r.next}while(n);yd=!1}}function Cd(){wd()}function wd(){vd=_d=!1;var e=0;bd!==0&&ff()&&(e=bd);for(var t=Fe(),n=null,r=hd;r!==null;){var i=r.next,a=Td(r,t);a===0?(r.next=null,n===null?hd=i:n.next=i,i===null&&(gd=n)):(n=r,(e!==0||a&3)&&(vd=!0)),r=i}xu!==0&&xu!==5||Sd(e,!1),bd!==0&&(bd=0)}function Td(e,t){for(var n=e.suspendedLanes,r=e.pingedLanes,i=e.expirationTimes,a=e.pendingLanes&-62914561;0<a;){var o=31-qe(a),s=1<<o,c=i[o];c===-1?((s&n)===0||(s&r)!==0)&&(i[o]=rt(s,t)):c<=t&&(e.expiredLanes|=s),a&=~s}if(t=Ql,n=eu,n=tt(e,e===t?n:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),r=e.callbackNode,n===0||e===t&&(tu===2||tu===9)||e.cancelPendingCommit!==null)return r!==null&&r!==null&&Me(r),e.callbackNode=null,e.callbackPriority=0;if(!(n&3)||nt(e,n)){if(t=n&-n,t===e.callbackPriority)return t;switch(r!==null&&Me(r),ft(n)){case 2:case 8:n=Re;break;case 32:n=ze;break;case 268435456:n=Ve;break;default:n=ze}return r=Ed.bind(null,e),n=je(n,r),e.callbackPriority=t,e.callbackNode=n,t}return r!==null&&r!==null&&Me(r),e.callbackPriority=2,e.callbackNode=null,2}function Ed(e,t){if(xu!==0&&xu!==5)return e.callbackNode=null,e.callbackPriority=0,null;var n=e.callbackNode;if(ad()&&e.callbackNode!==n)return null;var r=eu;return r=tt(e,e===Ql?r:0,e.cancelPendingCommit!==null||e.timeoutHandle!==-1),r===0?null:(Nu(e,r,t),Td(e,Fe()),e.callbackNode!=null&&e.callbackNode===n?Ed.bind(null,e):null)}function Dd(e,t){if(ad())return null;Nu(e,t,!0)}function Od(){gf(function(){Zl&6?je(Le,Cd):wd()})}function kd(){if(bd===0){var e=Sa;e===0&&(e=Ze,Ze<<=1,!(Ze&261888)&&(Ze=256)),bd=e}return bd}function Ad(e){return e==null||typeof e==`symbol`||typeof e==`boolean`?null:typeof e==`function`?e:ln(``+e)}function jd(e,t){var n=t.ownerDocument.createElement(`input`);return n.name=t.name,n.value=t.value,e.id&&n.setAttribute(`form`,e.id),t.parentNode.insertBefore(n,t),e=new FormData(e),n.parentNode.removeChild(n),e}function Md(e,t,n,r,i){if(t===`submit`&&n&&n.stateNode===i){var a=Ad((i[_t]||null).action),o=r.submitter;o&&(t=(t=o[_t]||null)?Ad(t.formAction):o.getAttribute(`formAction`),t!==null&&(a=t,o=null));var s=new jn(`action`,`action`,null,r,i);e.push({event:s,listeners:[{instance:null,listener:function(){if(r.defaultPrevented){if(bd!==0){var e=o?jd(i,o):new FormData(i);Ps(n,{pending:!0,data:e,method:i.method,action:a},null,e)}}else typeof a==`function`&&(s.preventDefault(),e=o?jd(i,o):new FormData(i),Ps(n,{pending:!0,data:e,method:i.method,action:a},a,e))},currentTarget:i}]})}}for(var Nd=0;Nd<ii.length;Nd++){var Pd=ii[Nd];ai(Pd.toLowerCase(),`on`+(Pd[0].toUpperCase()+Pd.slice(1)))}ai(Xr,`onAnimationEnd`),ai(Zr,`onAnimationIteration`),ai(Qr,`onAnimationStart`),ai(`dblclick`,`onDoubleClick`),ai(`focusin`,`onFocus`),ai(`focusout`,`onBlur`),ai($r,`onTransitionRun`),ai(ei,`onTransitionStart`),ai(ti,`onTransitionCancel`),ai(ni,`onTransitionEnd`),Nt(`onMouseEnter`,[`mouseout`,`mouseover`]),Nt(`onMouseLeave`,[`mouseout`,`mouseover`]),Nt(`onPointerEnter`,[`pointerout`,`pointerover`]),Nt(`onPointerLeave`,[`pointerout`,`pointerover`]),Mt(`onChange`,`change click focusin focusout input keydown keyup selectionchange`.split(` `)),Mt(`onSelect`,`focusout contextmenu dragend focusin keydown keyup mousedown mouseup selectionchange`.split(` `)),Mt(`onBeforeInput`,[`compositionend`,`keypress`,`textInput`,`paste`]),Mt(`onCompositionEnd`,`compositionend focusout keydown keypress keyup mousedown`.split(` `)),Mt(`onCompositionStart`,`compositionstart focusout keydown keypress keyup mousedown`.split(` `)),Mt(`onCompositionUpdate`,`compositionupdate focusout keydown keypress keyup mousedown`.split(` `));var Fd=`abort canplay canplaythrough durationchange emptied encrypted ended error loadeddata loadedmetadata loadstart pause play playing progress ratechange resize seeked seeking stalled suspend timeupdate volumechange waiting`.split(` `),Id=new Set(`beforetoggle cancel close invalid load scroll scrollend toggle`.split(` `).concat(Fd));function Ld(e,t){t=!!(t&4);for(var n=0;n<e.length;n++){var r=e[n],i=r.event;r=r.listeners;a:{var a=void 0;if(t)for(var o=r.length-1;0<=o;o--){var s=r[o],c=s.instance,l=s.currentTarget;if(s=s.listener,c!==a&&i.isPropagationStopped())break a;a=s,i.currentTarget=l;try{a(i)}catch(e){oi(e)}i.currentTarget=null,a=c}else for(o=0;o<r.length;o++){if(s=r[o],c=s.instance,l=s.currentTarget,s=s.listener,c!==a&&i.isPropagationStopped())break a;a=s,i.currentTarget=l;try{a(i)}catch(e){oi(e)}i.currentTarget=null,a=c}}}}function Rd(e,t){var n=t[yt];n===void 0&&(n=t[yt]=new Set);var r=e+`__bubble`;n.has(r)||(Hd(t,e,2,!1),n.add(r))}function zd(e,t,n){var r=0;t&&(r|=4),Hd(n,e,r,t)}var Bd=`_reactListening`+Math.random().toString(36).slice(2);function Vd(e){if(!e[Bd]){e[Bd]=!0,At.forEach(function(t){t!==`selectionchange`&&(Id.has(t)||zd(t,!1,e),zd(t,!0,e))});var t=e.nodeType===9?e:e.ownerDocument;t===null||t[Bd]||(t[Bd]=!0,zd(`selectionchange`,!1,t))}}function Hd(e,t,n,r){switch(Dp(t)){case 2:var i=xp;break;case 8:i=Sp;break;default:i=Cp}n=i.bind(null,t,n,e),i=void 0,!bn||t!==`touchstart`&&t!==`touchmove`&&t!==`wheel`||(i=!0),r?i===void 0?e.addEventListener(t,n,!0):e.addEventListener(t,n,{capture:!0,passive:i}):i===void 0?e.addEventListener(t,n,!1):e.addEventListener(t,n,{passive:i})}function Ud(e,t,n,r,i){var a=r;if(!(t&1)&&!(t&2)&&r!==null)a:for(;;){if(r===null)return;var s=r.tag;if(s===3||s===4){var c=r.stateNode.containerInfo;if(c===i)break;if(s===4)for(s=r.return;s!==null;){var l=s.tag;if((l===3||l===4)&&s.stateNode.containerInfo===i)return;s=s.return}for(;c!==null;){if(s=Tt(c),s===null)return;if(l=s.tag,l===5||l===6||l===26||l===27){r=a=s;continue a}c=c.parentNode}}r=r.return}_n(function(){var r=a,i=fn(n),s=[];a:{var c=ri.get(e);if(c!==void 0){var l=jn,u=e;switch(e){case`keypress`:if(En(n)===0)break a;case`keydown`:case`keyup`:l=Yn;break;case`focusin`:u=`focus`,l=Bn;break;case`focusout`:u=`blur`,l=Bn;break;case`beforeblur`:case`afterblur`:l=Bn;break;case`click`:if(n.button===2)break a;case`auxclick`:case`dblclick`:case`mousedown`:case`mousemove`:case`mouseup`:case`mouseout`:case`mouseover`:case`contextmenu`:l=Rn;break;case`drag`:case`dragend`:case`dragenter`:case`dragexit`:case`dragleave`:case`dragover`:case`dragstart`:case`drop`:l=zn;break;case`touchcancel`:case`touchend`:case`touchmove`:case`touchstart`:l=Zn;break;case Xr:case Zr:case Qr:l=Vn;break;case ni:l=Qn;break;case`scroll`:case`scrollend`:l=Nn;break;case`wheel`:l=$n;break;case`copy`:case`cut`:case`paste`:l=Hn;break;case`gotpointercapture`:case`lostpointercapture`:case`pointercancel`:case`pointerdown`:case`pointermove`:case`pointerout`:case`pointerover`:case`pointerup`:l=Xn;break;case`toggle`:case`beforetoggle`:l=er}var d=!!(t&4),f=!d&&(e===`scroll`||e===`scrollend`),p=d?c===null?null:c+`Capture`:c;d=[];for(var m=r,h;m!==null;){var g=m;if(h=g.stateNode,g=g.tag,g!==5&&g!==26&&g!==27||h===null||p===null||(g=vn(m,p),g!=null&&d.push(Wd(m,g,h))),f)break;m=m.return}0<d.length&&(c=new l(c,u,null,n,i),s.push({event:c,listeners:d}))}}if(!(t&7)){a:{if(c=e===`mouseover`||e===`pointerover`,l=e===`mouseout`||e===`pointerout`,c&&n!==dn&&(u=n.relatedTarget||n.fromElement)&&(Tt(u)||u[vt]))break a;if((l||c)&&(c=i.window===i?i:(c=i.ownerDocument)?c.defaultView||c.parentWindow:window,l?(u=n.relatedTarget||n.toElement,l=r,u=u?Tt(u):null,u!==null&&(f=o(u),d=u.tag,u!==f||d!==5&&d!==27&&d!==6)&&(u=null)):(l=null,u=r),l!==u)){if(d=Rn,g=`onMouseLeave`,p=`onMouseEnter`,m=`mouse`,(e===`pointerout`||e===`pointerover`)&&(d=Xn,g=`onPointerLeave`,p=`onPointerEnter`,m=`pointer`),f=l==null?c:Dt(l),h=u==null?c:Dt(u),c=new d(g,m+`leave`,l,n,i),c.target=f,c.relatedTarget=h,g=null,Tt(i)===r&&(d=new d(p,m+`enter`,u,n,i),d.target=h,d.relatedTarget=f,g=d),f=g,l&&u)b:{for(d=Kd,p=l,m=u,h=0,g=p;g;g=d(g))h++;g=0;for(var _=m;_;_=d(_))g++;for(;0<h-g;)p=d(p),h--;for(;0<g-h;)m=d(m),g--;for(;h--;){if(p===m||m!==null&&p===m.alternate){d=p;break b}p=d(p),m=d(m)}d=null}else d=null;l!==null&&qd(s,c,l,d,!1),u!==null&&f!==null&&qd(s,f,u,d,!0)}}a:{if(c=r?Dt(r):window,l=c.nodeName&&c.nodeName.toLowerCase(),l===`select`||l===`input`&&c.type===`file`)var v=br;else if(mr(c)){if(xr)v=Ar;else{v=Or;var y=Dr}}else l=c.nodeName,!l||l.toLowerCase()!==`input`||c.type!==`checkbox`&&c.type!==`radio`?r&&on(r.elementType)&&(v=br):v=kr;if(v&&=v(e,r)){hr(s,v,n,i);break a}y&&y(e,c,r),e===`focusout`&&r&&c.type===`number`&&r.memoizedProps.value!=null&&Zt(c,`number`,c.value)}switch(y=r?Dt(r):window,e){case`focusin`:(mr(y)||y.contentEditable===`true`)&&(Br=y,Vr=r,Hr=null);break;case`focusout`:Hr=Vr=Br=null;break;case`mousedown`:Ur=!0;break;case`contextmenu`:case`mouseup`:case`dragend`:Ur=!1,Wr(s,n,i);break;case`selectionchange`:if(zr)break;case`keydown`:case`keyup`:Wr(s,n,i)}var b;if(nr)b:{switch(e){case`compositionstart`:var x=`onCompositionStart`;break b;case`compositionend`:x=`onCompositionEnd`;break b;case`compositionupdate`:x=`onCompositionUpdate`;break b}x=void 0}else ur?cr(e,n)&&(x=`onCompositionEnd`):e===`keydown`&&n.keyCode===229&&(x=`onCompositionStart`);x&&(ar&&n.locale!==`ko`&&(ur||x!==`onCompositionStart`?x===`onCompositionEnd`&&ur&&(b=Tn()):(Sn=i,Cn=`value`in Sn?Sn.value:Sn.textContent,ur=!0)),y=Gd(r,x),0<y.length&&(x=new Un(x,e,null,n,i),s.push({event:x,listeners:y}),b?x.data=b:(b=lr(n),b!==null&&(x.data=b)))),(b=ir?dr(e,n):fr(e,n))&&(x=Gd(r,`onBeforeInput`),0<x.length&&(y=new Un(`onBeforeInput`,`beforeinput`,null,n,i),s.push({event:y,listeners:x}),y.data=b)),Md(s,e,r,n,i)}Ld(s,t)})}function Wd(e,t,n){return{instance:e,listener:t,currentTarget:n}}function Gd(e,t){for(var n=t+`Capture`,r=[];e!==null;){var i=e,a=i.stateNode;if(i=i.tag,i!==5&&i!==26&&i!==27||a===null||(i=vn(e,n),i!=null&&r.unshift(Wd(e,i,a)),i=vn(e,t),i!=null&&r.push(Wd(e,i,a))),e.tag===3)return r;e=e.return}return[]}function Kd(e){if(e===null)return null;do e=e.return;while(e&&e.tag!==5&&e.tag!==27);return e||null}function qd(e,t,n,r,i){for(var a=t._reactName,o=[];n!==null&&n!==r;){var s=n,c=s.alternate,l=s.stateNode;if(s=s.tag,c!==null&&c===r)break;s!==5&&s!==26&&s!==27||l===null||(c=l,i?(l=vn(n,a),l!=null&&o.unshift(Wd(n,l,c))):i||(l=vn(n,a),l!=null&&o.push(Wd(n,l,c)))),n=n.return}o.length!==0&&e.push({event:t,listeners:o})}var Jd=/\r\n?/g,Yd=/\u0000|\uFFFD/g;function Xd(e){return(typeof e==`string`?e:``+e).replace(Jd,`
9
+ `).replace(Yd,``)}function Zd(e,t){return t=Xd(t),Xd(e)===t}function Qd(e,t,n,r,a,o){switch(n){case`children`:typeof r==`string`?t===`body`||t===`textarea`&&r===``||tn(e,r):(typeof r==`number`||typeof r==`bigint`)&&t!==`body`&&tn(e,``+r);break;case`className`:zt(e,`class`,r);break;case`tabIndex`:zt(e,`tabindex`,r);break;case`dir`:case`role`:case`viewBox`:case`width`:case`height`:zt(e,n,r);break;case`style`:an(e,r,o);break;case`data`:if(t!==`object`){zt(e,`data`,r);break}case`src`:case`href`:if(r===``&&(t!==`a`||n!==`href`)){e.removeAttribute(n);break}if(r==null||typeof r==`function`||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=ln(``+r),e.setAttribute(n,r);break;case`action`:case`formAction`:if(typeof r==`function`){e.setAttribute(n,`javascript:throw new Error('A React form was unexpectedly submitted. If you called form.submit() manually, consider using form.requestSubmit() instead. If you\\'re trying to use event.stopPropagation() in a submit event handler, consider also calling event.preventDefault().')`);break}if(typeof o==`function`&&(n===`formAction`?(t!==`input`&&Qd(e,t,`name`,a.name,a,null),Qd(e,t,`formEncType`,a.formEncType,a,null),Qd(e,t,`formMethod`,a.formMethod,a,null),Qd(e,t,`formTarget`,a.formTarget,a,null)):(Qd(e,t,`encType`,a.encType,a,null),Qd(e,t,`method`,a.method,a,null),Qd(e,t,`target`,a.target,a,null))),r==null||typeof r==`symbol`||typeof r==`boolean`){e.removeAttribute(n);break}r=ln(``+r),e.setAttribute(n,r);break;case`onClick`:r!=null&&(e.onclick=un);break;case`onScroll`:r!=null&&Rd(`scroll`,e);break;case`onScrollEnd`:r!=null&&Rd(`scrollend`,e);break;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(i(61));if(n=r.__html,n!=null){if(a.children!=null)throw Error(i(60));e.innerHTML=n}}break;case`multiple`:e.multiple=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`muted`:e.muted=r&&typeof r!=`function`&&typeof r!=`symbol`;break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`defaultValue`:case`defaultChecked`:case`innerHTML`:case`ref`:break;case`autoFocus`:break;case`xlinkHref`:if(r==null||typeof r==`function`||typeof r==`boolean`||typeof r==`symbol`){e.removeAttribute(`xlink:href`);break}n=ln(``+r),e.setAttributeNS(`http://www.w3.org/1999/xlink`,`xlink:href`,n);break;case`contentEditable`:case`spellCheck`:case`draggable`:case`value`:case`autoReverse`:case`externalResourcesRequired`:case`focusable`:case`preserveAlpha`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``+r):e.removeAttribute(n);break;case`inert`:case`allowFullScreen`:case`async`:case`autoPlay`:case`controls`:case`default`:case`defer`:case`disabled`:case`disablePictureInPicture`:case`disableRemotePlayback`:case`formNoValidate`:case`hidden`:case`loop`:case`noModule`:case`noValidate`:case`open`:case`playsInline`:case`readOnly`:case`required`:case`reversed`:case`scoped`:case`seamless`:case`itemScope`:r&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,``):e.removeAttribute(n);break;case`capture`:case`download`:!0===r?e.setAttribute(n,``):!1!==r&&r!=null&&typeof r!=`function`&&typeof r!=`symbol`?e.setAttribute(n,r):e.removeAttribute(n);break;case`cols`:case`rows`:case`size`:case`span`:r!=null&&typeof r!=`function`&&typeof r!=`symbol`&&!isNaN(r)&&1<=r?e.setAttribute(n,r):e.removeAttribute(n);break;case`rowSpan`:case`start`:r==null||typeof r==`function`||typeof r==`symbol`||isNaN(r)?e.removeAttribute(n):e.setAttribute(n,r);break;case`popover`:Rd(`beforetoggle`,e),Rd(`toggle`,e),Rt(e,`popover`,r);break;case`xlinkActuate`:Bt(e,`http://www.w3.org/1999/xlink`,`xlink:actuate`,r);break;case`xlinkArcrole`:Bt(e,`http://www.w3.org/1999/xlink`,`xlink:arcrole`,r);break;case`xlinkRole`:Bt(e,`http://www.w3.org/1999/xlink`,`xlink:role`,r);break;case`xlinkShow`:Bt(e,`http://www.w3.org/1999/xlink`,`xlink:show`,r);break;case`xlinkTitle`:Bt(e,`http://www.w3.org/1999/xlink`,`xlink:title`,r);break;case`xlinkType`:Bt(e,`http://www.w3.org/1999/xlink`,`xlink:type`,r);break;case`xmlBase`:Bt(e,`http://www.w3.org/XML/1998/namespace`,`xml:base`,r);break;case`xmlLang`:Bt(e,`http://www.w3.org/XML/1998/namespace`,`xml:lang`,r);break;case`xmlSpace`:Bt(e,`http://www.w3.org/XML/1998/namespace`,`xml:space`,r);break;case`is`:Rt(e,`is`,r);break;case`innerText`:case`textContent`:break;default:(!(2<n.length)||n[0]!==`o`&&n[0]!==`O`||n[1]!==`n`&&n[1]!==`N`)&&(n=sn.get(n)||n,Rt(e,n,r))}}function $d(e,t,n,r,a,o){switch(n){case`style`:an(e,r,o);break;case`dangerouslySetInnerHTML`:if(r!=null){if(typeof r!=`object`||!(`__html`in r))throw Error(i(61));if(n=r.__html,n!=null){if(a.children!=null)throw Error(i(60));e.innerHTML=n}}break;case`children`:typeof r==`string`?tn(e,r):(typeof r==`number`||typeof r==`bigint`)&&tn(e,``+r);break;case`onScroll`:r!=null&&Rd(`scroll`,e);break;case`onScrollEnd`:r!=null&&Rd(`scrollend`,e);break;case`onClick`:r!=null&&(e.onclick=un);break;case`suppressContentEditableWarning`:case`suppressHydrationWarning`:case`innerHTML`:case`ref`:break;case`innerText`:case`textContent`:break;default:if(!jt.hasOwnProperty(n))a:{if(n[0]===`o`&&n[1]===`n`&&(a=n.endsWith(`Capture`),t=n.slice(2,a?n.length-7:void 0),o=e[_t]||null,o=o==null?null:o[n],typeof o==`function`&&e.removeEventListener(t,o,a),typeof r==`function`)){typeof o!=`function`&&o!==null&&(n in e?e[n]=null:e.hasAttribute(n)&&e.removeAttribute(n)),e.addEventListener(t,r,a);break a}n in e?e[n]=r:!0===r?e.setAttribute(n,``):Rt(e,n,r)}}}function ef(e,t,n){switch(t){case`div`:case`span`:case`svg`:case`path`:case`a`:case`g`:case`p`:case`li`:break;case`img`:Rd(`error`,e),Rd(`load`,e);var r=!1,a=!1,o;for(o in n)if(n.hasOwnProperty(o)){var s=n[o];if(s!=null)switch(o){case`src`:r=!0;break;case`srcSet`:a=!0;break;case`children`:case`dangerouslySetInnerHTML`:throw Error(i(137,t));default:Qd(e,t,o,s,n,null)}}a&&Qd(e,t,`srcSet`,n.srcSet,n,null),r&&Qd(e,t,`src`,n.src,n,null);return;case`input`:Rd(`invalid`,e);var c=o=s=a=null,l=null,u=null;for(r in n)if(n.hasOwnProperty(r)){var d=n[r];if(d!=null)switch(r){case`name`:a=d;break;case`type`:s=d;break;case`checked`:l=d;break;case`defaultChecked`:u=d;break;case`value`:o=d;break;case`defaultValue`:c=d;break;case`children`:case`dangerouslySetInnerHTML`:if(d!=null)throw Error(i(137,t));break;default:Qd(e,t,r,d,n,null)}}Xt(e,o,c,l,u,s,a,!1);return;case`select`:for(a in Rd(`invalid`,e),r=s=o=null,n)if(n.hasOwnProperty(a)&&(c=n[a],c!=null))switch(a){case`value`:o=c;break;case`defaultValue`:s=c;break;case`multiple`:r=c;default:Qd(e,t,a,c,n,null)}t=o,n=s,e.multiple=!!r,t==null?n!=null&&Qt(e,!!r,n,!0):Qt(e,!!r,t,!1);return;case`textarea`:for(s in Rd(`invalid`,e),o=a=r=null,n)if(n.hasOwnProperty(s)&&(c=n[s],c!=null))switch(s){case`value`:r=c;break;case`defaultValue`:a=c;break;case`children`:o=c;break;case`dangerouslySetInnerHTML`:if(c!=null)throw Error(i(91));break;default:Qd(e,t,s,c,n,null)}en(e,r,a,o);return;case`option`:for(l in n)if(n.hasOwnProperty(l)&&(r=n[l],r!=null))switch(l){case`selected`:e.selected=r&&typeof r!=`function`&&typeof r!=`symbol`;break;default:Qd(e,t,l,r,n,null)}return;case`dialog`:Rd(`beforetoggle`,e),Rd(`toggle`,e),Rd(`cancel`,e),Rd(`close`,e);break;case`iframe`:case`object`:Rd(`load`,e);break;case`video`:case`audio`:for(r=0;r<Fd.length;r++)Rd(Fd[r],e);break;case`image`:Rd(`error`,e),Rd(`load`,e);break;case`details`:Rd(`toggle`,e);break;case`embed`:case`source`:case`link`:Rd(`error`,e),Rd(`load`,e);case`area`:case`base`:case`br`:case`col`:case`hr`:case`keygen`:case`meta`:case`param`:case`track`:case`wbr`:case`menuitem`:for(u in n)if(n.hasOwnProperty(u)&&(r=n[u],r!=null))switch(u){case`children`:case`dangerouslySetInnerHTML`:throw Error(i(137,t));default:Qd(e,t,u,r,n,null)}return;default:if(on(t)){for(d in n)n.hasOwnProperty(d)&&(r=n[d],r!==void 0&&$d(e,t,d,r,n,void 0));return}}for(c in n)n.hasOwnProperty(c)&&(r=n[c],r!=null&&Qd(e,t,c,r,n,null))}function tf(e,t,n,r){switch(t){case`div`:case`span`:case`svg`:case`path`:case`a`:case`g`:case`p`:case`li`:break;case`input`:var a=null,o=null,s=null,c=null,l=null,u=null,d=null;for(m in n){var f=n[m];if(n.hasOwnProperty(m)&&f!=null)switch(m){case`checked`:break;case`value`:break;case`defaultValue`:l=f;default:r.hasOwnProperty(m)||Qd(e,t,m,null,r,f)}}for(var p in r){var m=r[p];if(f=n[p],r.hasOwnProperty(p)&&(m!=null||f!=null))switch(p){case`type`:o=m;break;case`name`:a=m;break;case`checked`:u=m;break;case`defaultChecked`:d=m;break;case`value`:s=m;break;case`defaultValue`:c=m;break;case`children`:case`dangerouslySetInnerHTML`:if(m!=null)throw Error(i(137,t));break;default:m!==f&&Qd(e,t,p,m,r,f)}}Yt(e,s,c,l,u,d,o,a);return;case`select`:for(o in m=s=c=p=null,n)if(l=n[o],n.hasOwnProperty(o)&&l!=null)switch(o){case`value`:break;case`multiple`:m=l;default:r.hasOwnProperty(o)||Qd(e,t,o,null,r,l)}for(a in r)if(o=r[a],l=n[a],r.hasOwnProperty(a)&&(o!=null||l!=null))switch(a){case`value`:p=o;break;case`defaultValue`:c=o;break;case`multiple`:s=o;default:o!==l&&Qd(e,t,a,o,r,l)}t=c,n=s,r=m,p==null?!!r!=!!n&&(t==null?Qt(e,!!n,n?[]:``,!1):Qt(e,!!n,t,!0)):Qt(e,!!n,p,!1);return;case`textarea`:for(c in m=p=null,n)if(a=n[c],n.hasOwnProperty(c)&&a!=null&&!r.hasOwnProperty(c))switch(c){case`value`:break;case`children`:break;default:Qd(e,t,c,null,r,a)}for(s in r)if(a=r[s],o=n[s],r.hasOwnProperty(s)&&(a!=null||o!=null))switch(s){case`value`:p=a;break;case`defaultValue`:m=a;break;case`children`:break;case`dangerouslySetInnerHTML`:if(a!=null)throw Error(i(91));break;default:a!==o&&Qd(e,t,s,a,r,o)}$t(e,p,m);return;case`option`:for(var h in n)if(p=n[h],n.hasOwnProperty(h)&&p!=null&&!r.hasOwnProperty(h))switch(h){case`selected`:e.selected=!1;break;default:Qd(e,t,h,null,r,p)}for(l in r)if(p=r[l],m=n[l],r.hasOwnProperty(l)&&p!==m&&(p!=null||m!=null))switch(l){case`selected`:e.selected=p&&typeof p!=`function`&&typeof p!=`symbol`;break;default:Qd(e,t,l,p,r,m)}return;case`img`:case`link`:case`area`:case`base`:case`br`:case`col`:case`embed`:case`hr`:case`keygen`:case`meta`:case`param`:case`source`:case`track`:case`wbr`:case`menuitem`:for(var g in n)p=n[g],n.hasOwnProperty(g)&&p!=null&&!r.hasOwnProperty(g)&&Qd(e,t,g,null,r,p);for(u in r)if(p=r[u],m=n[u],r.hasOwnProperty(u)&&p!==m&&(p!=null||m!=null))switch(u){case`children`:case`dangerouslySetInnerHTML`:if(p!=null)throw Error(i(137,t));break;default:Qd(e,t,u,p,r,m)}return;default:if(on(t)){for(var _ in n)p=n[_],n.hasOwnProperty(_)&&p!==void 0&&!r.hasOwnProperty(_)&&$d(e,t,_,void 0,r,p);for(d in r)p=r[d],m=n[d],!r.hasOwnProperty(d)||p===m||p===void 0&&m===void 0||$d(e,t,d,p,r,m);return}}for(var v in n)p=n[v],n.hasOwnProperty(v)&&p!=null&&!r.hasOwnProperty(v)&&Qd(e,t,v,null,r,p);for(f in r)p=r[f],m=n[f],!r.hasOwnProperty(f)||p===m||p==null&&m==null||Qd(e,t,f,p,r,m)}function nf(e){switch(e){case`css`:case`script`:case`font`:case`img`:case`image`:case`input`:case`link`:return!0;default:return!1}}function rf(){if(typeof performance.getEntriesByType==`function`){for(var e=0,t=0,n=performance.getEntriesByType(`resource`),r=0;r<n.length;r++){var i=n[r],a=i.transferSize,o=i.initiatorType,s=i.duration;if(a&&s&&nf(o)){for(o=0,s=i.responseEnd,r+=1;r<n.length;r++){var c=n[r],l=c.startTime;if(l>s)break;var u=c.transferSize,d=c.initiatorType;u&&nf(d)&&(c=c.responseEnd,o+=u*(c<s?1:(s-l)/(c-l)))}if(--r,t+=8*(a+o)/(i.duration/1e3),e++,10<e)break}}if(0<e)return t/e/1e6}return navigator.connection&&(e=navigator.connection.downlink,typeof e==`number`)?e:5}var af=null,of=null;function sf(e){return e.nodeType===9?e:e.ownerDocument}function cf(e){switch(e){case`http://www.w3.org/2000/svg`:return 1;case`http://www.w3.org/1998/Math/MathML`:return 2;default:return 0}}function lf(e,t){if(e===0)switch(t){case`svg`:return 1;case`math`:return 2;default:return 0}return e===1&&t===`foreignObject`?0:e}function uf(e,t){return e===`textarea`||e===`noscript`||typeof t.children==`string`||typeof t.children==`number`||typeof t.children==`bigint`||typeof t.dangerouslySetInnerHTML==`object`&&t.dangerouslySetInnerHTML!==null&&t.dangerouslySetInnerHTML.__html!=null}var df=null;function ff(){var e=window.event;return e&&e.type===`popstate`?e!==df&&(df=e,!0):(df=null,!1)}var pf=typeof setTimeout==`function`?setTimeout:void 0,mf=typeof clearTimeout==`function`?clearTimeout:void 0,hf=typeof Promise==`function`?Promise:void 0,gf=typeof queueMicrotask==`function`?queueMicrotask:hf===void 0?pf:function(e){return hf.resolve(null).then(e).catch(_f)};function _f(e){setTimeout(function(){throw e})}function vf(e){return e===`head`}function yf(e,t){var n=t,r=0;do{var i=n.nextSibling;if(e.removeChild(n),i&&i.nodeType===8){if(n=i.data,n===`/$`||n===`/&`){if(r===0){e.removeChild(i),Gp(t);return}r--}else if(n===`$`||n===`$?`||n===`$~`||n===`$!`||n===`&`)r++;else if(n===`html`)Nf(e.ownerDocument.documentElement);else if(n===`head`){n=e.ownerDocument.head,Nf(n);for(var a=n.firstChild;a;){var o=a.nextSibling,s=a.nodeName;a[Ct]||s===`SCRIPT`||s===`STYLE`||s===`LINK`&&a.rel.toLowerCase()===`stylesheet`||n.removeChild(a),a=o}}else n===`body`&&Nf(e.ownerDocument.body)}n=i}while(n);Gp(t)}function bf(e,t){var n=e;e=0;do{var r=n.nextSibling;if(n.nodeType===1?t?(n._stashedDisplay=n.style.display,n.style.display=`none`):(n.style.display=n._stashedDisplay||``,n.getAttribute(`style`)===``&&n.removeAttribute(`style`)):n.nodeType===3&&(t?(n._stashedText=n.nodeValue,n.nodeValue=``):n.nodeValue=n._stashedText||``),r&&r.nodeType===8){if(n=r.data,n===`/$`){if(e===0)break;e--}else n!==`$`&&n!==`$?`&&n!==`$~`&&n!==`$!`||e++}n=r}while(n)}function xf(e){var t=e.firstChild;for(t&&t.nodeType===10&&(t=t.nextSibling);t;){var n=t;switch(t=t.nextSibling,n.nodeName){case`HTML`:case`HEAD`:case`BODY`:xf(n),wt(n);continue;case`SCRIPT`:case`STYLE`:continue;case`LINK`:if(n.rel.toLowerCase()===`stylesheet`)continue}e.removeChild(n)}}function Sf(e,t,n,r){for(;e.nodeType===1;){var i=n;if(e.nodeName.toLowerCase()!==t.toLowerCase()){if(!r&&(e.nodeName!==`INPUT`||e.type!==`hidden`))break}else if(!r){if(t===`input`&&e.type===`hidden`){var a=i.name==null?null:``+i.name;if(i.type===`hidden`&&e.getAttribute(`name`)===a)return e}else return e}else if(!e[Ct])switch(t){case`meta`:if(!e.hasAttribute(`itemprop`))break;return e;case`link`:if(a=e.getAttribute(`rel`),a===`stylesheet`&&e.hasAttribute(`data-precedence`)||a!==i.rel||e.getAttribute(`href`)!==(i.href==null||i.href===``?null:i.href)||e.getAttribute(`crossorigin`)!==(i.crossOrigin==null?null:i.crossOrigin)||e.getAttribute(`title`)!==(i.title==null?null:i.title))break;return e;case`style`:if(e.hasAttribute(`data-precedence`))break;return e;case`script`:if(a=e.getAttribute(`src`),(a!==(i.src==null?null:i.src)||e.getAttribute(`type`)!==(i.type==null?null:i.type)||e.getAttribute(`crossorigin`)!==(i.crossOrigin==null?null:i.crossOrigin))&&a&&e.hasAttribute(`async`)&&!e.hasAttribute(`itemprop`))break;return e;default:return e}if(e=Of(e.nextSibling),e===null)break}return null}function Cf(e,t,n){if(t===``)return null;for(;e.nodeType!==3;)if((e.nodeType!==1||e.nodeName!==`INPUT`||e.type!==`hidden`)&&!n||(e=Of(e.nextSibling),e===null))return null;return e}function wf(e,t){for(;e.nodeType!==8;)if((e.nodeType!==1||e.nodeName!==`INPUT`||e.type!==`hidden`)&&!t||(e=Of(e.nextSibling),e===null))return null;return e}function Tf(e){return e.data===`$?`||e.data===`$~`}function Ef(e){return e.data===`$!`||e.data===`$?`&&e.ownerDocument.readyState!==`loading`}function Df(e,t){var n=e.ownerDocument;if(e.data===`$~`)e._reactRetry=t;else if(e.data!==`$?`||n.readyState!==`loading`)t();else{var r=function(){t(),n.removeEventListener(`DOMContentLoaded`,r)};n.addEventListener(`DOMContentLoaded`,r),e._reactRetry=r}}function Of(e){for(;e!=null;e=e.nextSibling){var t=e.nodeType;if(t===1||t===3)break;if(t===8){if(t=e.data,t===`$`||t===`$!`||t===`$?`||t===`$~`||t===`&`||t===`F!`||t===`F`)break;if(t===`/$`||t===`/&`)return null}}return e}var kf=null;function Af(e){e=e.nextSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n===`/$`||n===`/&`){if(t===0)return Of(e.nextSibling);t--}else n!==`$`&&n!==`$!`&&n!==`$?`&&n!==`$~`&&n!==`&`||t++}e=e.nextSibling}return null}function jf(e){e=e.previousSibling;for(var t=0;e;){if(e.nodeType===8){var n=e.data;if(n===`$`||n===`$!`||n===`$?`||n===`$~`||n===`&`){if(t===0)return e;t--}else n!==`/$`&&n!==`/&`||t++}e=e.previousSibling}return null}function Mf(e,t,n){switch(t=sf(n),e){case`html`:if(e=t.documentElement,!e)throw Error(i(452));return e;case`head`:if(e=t.head,!e)throw Error(i(453));return e;case`body`:if(e=t.body,!e)throw Error(i(454));return e;default:throw Error(i(451))}}function Nf(e){for(var t=e.attributes;t.length;)e.removeAttributeNode(t[0]);wt(e)}var Pf=new Map,Ff=new Set;function If(e){return typeof e.getRootNode==`function`?e.getRootNode():e.nodeType===9?e:e.ownerDocument}var Lf=ce.d;ce.d={f:Rf,r:zf,D:Vf,C:Hf,L:Uf,m:Wf,X:Kf,S:Gf,M:qf};function Rf(){var e=Lf.f(),t=Lu();return e||t}function zf(e){var t=Et(e);t!==null&&t.tag===5&&t.type===`form`?Is(t):Lf.r(e)}var P=typeof document>`u`?null:document;function Bf(e,t,n){var r=P;if(r&&typeof t==`string`&&t){var i=Jt(t);i=`link[rel="`+e+`"][href="`+i+`"]`,typeof n==`string`&&(i+=`[crossorigin="`+n+`"]`),Ff.has(i)||(Ff.add(i),e={rel:e,crossOrigin:n,href:t},r.querySelector(i)===null&&(t=r.createElement(`link`),ef(t,`link`,e),kt(t),r.head.appendChild(t)))}}function Vf(e){Lf.D(e),Bf(`dns-prefetch`,e,null)}function Hf(e,t){Lf.C(e,t),Bf(`preconnect`,e,t)}function Uf(e,t,n){Lf.L(e,t,n);var r=P;if(r&&e&&t){var i=`link[rel="preload"][as="`+Jt(t)+`"]`;t===`image`&&n&&n.imageSrcSet?(i+=`[imagesrcset="`+Jt(n.imageSrcSet)+`"]`,typeof n.imageSizes==`string`&&(i+=`[imagesizes="`+Jt(n.imageSizes)+`"]`)):i+=`[href="`+Jt(e)+`"]`;var a=i;switch(t){case`style`:a=Yf(e);break;case`script`:a=$f(e)}Pf.has(a)||(e=h({rel:`preload`,href:t===`image`&&n&&n.imageSrcSet?void 0:e,as:t},n),Pf.set(a,e),r.querySelector(i)!==null||t===`style`&&r.querySelector(Xf(a))||t===`script`&&r.querySelector(ep(a))||(t=r.createElement(`link`),ef(t,`link`,e),kt(t),r.head.appendChild(t)))}}function Wf(e,t){Lf.m(e,t);var n=P;if(n&&e){var r=t&&typeof t.as==`string`?t.as:`script`,i=`link[rel="modulepreload"][as="`+Jt(r)+`"][href="`+Jt(e)+`"]`,a=i;switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:a=$f(e)}if(!Pf.has(a)&&(e=h({rel:`modulepreload`,href:e},t),Pf.set(a,e),n.querySelector(i)===null)){switch(r){case`audioworklet`:case`paintworklet`:case`serviceworker`:case`sharedworker`:case`worker`:case`script`:if(n.querySelector(ep(a)))return}r=n.createElement(`link`),ef(r,`link`,e),kt(r),n.head.appendChild(r)}}}function Gf(e,t,n){Lf.S(e,t,n);var r=P;if(r&&e){var i=Ot(r).hoistableStyles,a=Yf(e);t||=`default`;var o=i.get(a);if(!o){var s={loading:0,preload:null};if(o=r.querySelector(Xf(a)))s.loading=5;else{e=h({rel:`stylesheet`,href:e,"data-precedence":t},n),(n=Pf.get(a))&&rp(e,n);var c=o=r.createElement(`link`);kt(c),ef(c,`link`,e),c._p=new Promise(function(e,t){c.onload=e,c.onerror=t}),c.addEventListener(`load`,function(){s.loading|=1}),c.addEventListener(`error`,function(){s.loading|=2}),s.loading|=4,np(o,t,r)}o={type:`stylesheet`,instance:o,count:1,state:s},i.set(a,o)}}}function Kf(e,t){Lf.X(e,t);var n=P;if(n&&e){var r=Ot(n).hoistableScripts,i=$f(e),a=r.get(i);a||(a=n.querySelector(ep(i)),a||(e=h({src:e,async:!0},t),(t=Pf.get(i))&&ip(e,t),a=n.createElement(`script`),kt(a),ef(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function qf(e,t){Lf.M(e,t);var n=P;if(n&&e){var r=Ot(n).hoistableScripts,i=$f(e),a=r.get(i);a||(a=n.querySelector(ep(i)),a||(e=h({src:e,async:!0,type:`module`},t),(t=Pf.get(i))&&ip(e,t),a=n.createElement(`script`),kt(a),ef(a,`link`,e),n.head.appendChild(a)),a={type:`script`,instance:a,count:1,state:null},r.set(i,a))}}function Jf(e,t,n,r){var a=(a=_e.current)?If(a):null;if(!a)throw Error(i(446));switch(e){case`meta`:case`title`:return null;case`style`:return typeof n.precedence==`string`&&typeof n.href==`string`?(t=Yf(n.href),n=Ot(a).hoistableStyles,r=n.get(t),r||(r={type:`style`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};case`link`:if(n.rel===`stylesheet`&&typeof n.href==`string`&&typeof n.precedence==`string`){e=Yf(n.href);var o=Ot(a).hoistableStyles,s=o.get(e);if(s||(a=a.ownerDocument||a,s={type:`stylesheet`,instance:null,count:0,state:{loading:0,preload:null}},o.set(e,s),(o=a.querySelector(Xf(e)))&&!o._p&&(s.instance=o,s.state.loading=5),Pf.has(e)||(n={rel:`preload`,as:`style`,href:n.href,crossOrigin:n.crossOrigin,integrity:n.integrity,media:n.media,hrefLang:n.hrefLang,referrerPolicy:n.referrerPolicy},Pf.set(e,n),o||Qf(a,e,n,s.state))),t&&r===null)throw Error(i(528,``));return s}if(t&&r!==null)throw Error(i(529,``));return null;case`script`:return t=n.async,n=n.src,typeof n==`string`&&t&&typeof t!=`function`&&typeof t!=`symbol`?(t=$f(n),n=Ot(a).hoistableScripts,r=n.get(t),r||(r={type:`script`,instance:null,count:0,state:null},n.set(t,r)),r):{type:`void`,instance:null,count:0,state:null};default:throw Error(i(444,e))}}function Yf(e){return`href="`+Jt(e)+`"`}function Xf(e){return`link[rel="stylesheet"][`+e+`]`}function Zf(e){return h({},e,{"data-precedence":e.precedence,precedence:null})}function Qf(e,t,n,r){e.querySelector(`link[rel="preload"][as="style"][`+t+`]`)?r.loading=1:(t=e.createElement(`link`),r.preload=t,t.addEventListener(`load`,function(){return r.loading|=1}),t.addEventListener(`error`,function(){return r.loading|=2}),ef(t,`link`,n),kt(t),e.head.appendChild(t))}function $f(e){return`[src="`+Jt(e)+`"]`}function ep(e){return`script[async]`+e}function tp(e,t,n){if(t.count++,t.instance===null)switch(t.type){case`style`:var r=e.querySelector(`style[data-href~="`+Jt(n.href)+`"]`);if(r)return t.instance=r,kt(r),r;var a=h({},n,{"data-href":n.href,"data-precedence":n.precedence,href:null,precedence:null});return r=(e.ownerDocument||e).createElement(`style`),kt(r),ef(r,`style`,a),np(r,n.precedence,e),t.instance=r;case`stylesheet`:a=Yf(n.href);var o=e.querySelector(Xf(a));if(o)return t.state.loading|=4,t.instance=o,kt(o),o;r=Zf(n),(a=Pf.get(a))&&rp(r,a),o=(e.ownerDocument||e).createElement(`link`),kt(o);var s=o;return s._p=new Promise(function(e,t){s.onload=e,s.onerror=t}),ef(o,`link`,r),t.state.loading|=4,np(o,n.precedence,e),t.instance=o;case`script`:return o=$f(n.src),(a=e.querySelector(ep(o)))?(t.instance=a,kt(a),a):(r=n,(a=Pf.get(o))&&(r=h({},n),ip(r,a)),e=e.ownerDocument||e,a=e.createElement(`script`),kt(a),ef(a,`link`,r),e.head.appendChild(a),t.instance=a);case`void`:return null;default:throw Error(i(443,t.type))}else t.type===`stylesheet`&&!(t.state.loading&4)&&(r=t.instance,t.state.loading|=4,np(r,n.precedence,e));return t.instance}function np(e,t,n){for(var r=n.querySelectorAll(`link[rel="stylesheet"][data-precedence],style[data-precedence]`),i=r.length?r[r.length-1]:null,a=i,o=0;o<r.length;o++){var s=r[o];if(s.dataset.precedence===t)a=s;else if(a!==i)break}a?a.parentNode.insertBefore(e,a.nextSibling):(t=n.nodeType===9?n.head:n,t.insertBefore(e,t.firstChild))}function rp(e,t){e.crossOrigin??=t.crossOrigin,e.referrerPolicy??=t.referrerPolicy,e.title??=t.title}function ip(e,t){e.crossOrigin??=t.crossOrigin,e.referrerPolicy??=t.referrerPolicy,e.integrity??=t.integrity}var ap=null;function op(e,t,n){if(ap===null){var r=new Map,i=ap=new Map;i.set(n,r)}else i=ap,r=i.get(n),r||(r=new Map,i.set(n,r));if(r.has(e))return r;for(r.set(e,null),n=n.getElementsByTagName(e),i=0;i<n.length;i++){var a=n[i];if(!(a[Ct]||a[gt]||e===`link`&&a.getAttribute(`rel`)===`stylesheet`)&&a.namespaceURI!==`http://www.w3.org/2000/svg`){var o=a.getAttribute(t)||``;o=e+o;var s=r.get(o);s?s.push(a):r.set(o,[a])}}return r}function sp(e,t,n){e=e.ownerDocument||e,e.head.insertBefore(n,t===`title`?e.querySelector(`head > title`):null)}function cp(e,t,n){if(n===1||t.itemProp!=null)return!1;switch(e){case`meta`:case`title`:return!0;case`style`:if(typeof t.precedence!=`string`||typeof t.href!=`string`||t.href===``)break;return!0;case`link`:if(typeof t.rel!=`string`||typeof t.href!=`string`||t.href===``||t.onLoad||t.onError)break;switch(t.rel){case`stylesheet`:return e=t.disabled,typeof t.precedence==`string`&&e==null;default:return!0}case`script`:if(t.async&&typeof t.async!=`function`&&typeof t.async!=`symbol`&&!t.onLoad&&!t.onError&&t.src&&typeof t.src==`string`)return!0}return!1}function lp(e){return!(e.type===`stylesheet`&&!(e.state.loading&3))}function up(e,t,n,r){if(n.type===`stylesheet`&&(typeof r.media!=`string`||!1!==matchMedia(r.media).matches)&&!(n.state.loading&4)){if(n.instance===null){var i=Yf(r.href),a=t.querySelector(Xf(i));if(a){t=a._p,typeof t==`object`&&t&&typeof t.then==`function`&&(e.count++,e=I.bind(e),t.then(e,e)),n.state.loading|=4,n.instance=a,kt(a);return}a=t.ownerDocument||t,r=Zf(r),(i=Pf.get(i))&&rp(r,i),a=a.createElement(`link`),kt(a);var o=a;o._p=new Promise(function(e,t){o.onload=e,o.onerror=t}),ef(a,`link`,r),n.instance=a}e.stylesheets===null&&(e.stylesheets=new Map),e.stylesheets.set(n,t),(t=n.state.preload)&&!(n.state.loading&3)&&(e.count++,n=I.bind(e),t.addEventListener(`load`,n),t.addEventListener(`error`,n))}}var F=0;function dp(e,t){return e.stylesheets&&e.count===0&&L(e,e.stylesheets),0<e.count||0<e.imgCount?function(n){var r=setTimeout(function(){if(e.stylesheets&&L(e,e.stylesheets),e.unsuspend){var t=e.unsuspend;e.unsuspend=null,t()}},6e4+t);0<e.imgBytes&&F===0&&(F=62500*rf());var i=setTimeout(function(){if(e.waitingForImages=!1,e.count===0&&(e.stylesheets&&L(e,e.stylesheets),e.unsuspend)){var t=e.unsuspend;e.unsuspend=null,t()}},(e.imgBytes>F?50:800)+t);return e.unsuspend=n,function(){e.unsuspend=null,clearTimeout(r),clearTimeout(i)}}:null}function I(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)L(this,this.stylesheets);else if(this.unsuspend){var e=this.unsuspend;this.unsuspend=null,e()}}}var fp=null;function L(e,t){e.stylesheets=null,e.unsuspend!==null&&(e.count++,fp=new Map,t.forEach(pp,e),fp=null,I.call(e))}function pp(e,t){if(!(t.state.loading&4)){var n=fp.get(e);if(n)var r=n.get(null);else{n=new Map,fp.set(e,n);for(var i=e.querySelectorAll(`link[data-precedence],style[data-precedence]`),a=0;a<i.length;a++){var o=i[a];(o.nodeName===`LINK`||o.getAttribute(`media`)!==`not all`)&&(n.set(o.dataset.precedence,o),r=o)}r&&n.set(null,r)}i=t.instance,o=i.getAttribute(`data-precedence`),a=n.get(o)||r,a===r&&n.set(null,i),n.set(o,i),this.count++,r=I.bind(this),i.addEventListener(`load`,r),i.addEventListener(`error`,r),a?a.parentNode.insertBefore(i,a.nextSibling):(e=e.nodeType===9?e.head:e,e.insertBefore(i,e.firstChild)),t.state.loading|=4}}var mp={$$typeof:C,Provider:null,Consumer:null,_currentValue:le,_currentValue2:le,_threadCount:0};function hp(e,t,n,r,i,a,o,s,c){this.tag=1,this.containerInfo=e,this.pingCache=this.current=this.pendingChildren=null,this.timeoutHandle=-1,this.callbackNode=this.next=this.pendingContext=this.context=this.cancelPendingCommit=null,this.callbackPriority=0,this.expirationTimes=at(-1),this.entangledLanes=this.shellSuspendCounter=this.errorRecoveryDisabledLanes=this.expiredLanes=this.warmLanes=this.pingedLanes=this.suspendedLanes=this.pendingLanes=0,this.entanglements=at(0),this.hiddenUpdates=at(null),this.identifierPrefix=r,this.onUncaughtError=i,this.onCaughtError=a,this.onRecoverableError=o,this.pooledCache=null,this.pooledCacheLanes=0,this.formState=c,this.incompleteTransitions=new Map}function gp(e,t,n,r,i,a,o,s,c,l,u,d){return e=new hp(e,t,n,o,c,l,u,d,s),t=1,!0===a&&(t|=24),a=vi(3,null,null,t),e.current=a,a.stateNode=e,t=va(),t.refCount++,e.pooledCache=t,t.refCount++,a.memoizedState={element:r,isDehydrated:n,cache:t},Ya(a),e}function _p(e){return e?(e=gi,e):gi}function R(e,t,n,r,i,a){i=_p(i),r.context===null?r.context=i:r.pendingContext=i,r=Za(t),r.payload={element:n},a=a===void 0?null:a,a!==null&&(r.callback=a),n=M(e,r,t),n!==null&&(Mu(n,e,t),Qa(n,e,t))}function vp(e,t){if(e=e.memoizedState,e!==null&&e.dehydrated!==null){var n=e.retryLane;e.retryLane=n!==0&&n<t?n:t}}function z(e,t){vp(e,t),(e=e.alternate)&&vp(e,t)}function B(e){if(e.tag===13||e.tag===31){var t=pi(e,67108864);t!==null&&Mu(t,e,67108864),z(e,67108864)}}function yp(e){if(e.tag===13||e.tag===31){var t=Au();t=dt(t);var n=pi(e,t);n!==null&&Mu(n,e,t),z(e,t)}}var bp=!0;function xp(e,t,n,r){var i=O.T;O.T=null;var a=ce.p;try{ce.p=2,Cp(e,t,n,r)}finally{ce.p=a,O.T=i}}function Sp(e,t,n,r){var i=O.T;O.T=null;var a=ce.p;try{ce.p=8,Cp(e,t,n,r)}finally{ce.p=a,O.T=i}}function Cp(e,t,n,r){if(bp){var i=wp(r);if(i===null)Ud(e,t,r,Tp,n),Fp(e,r);else if(Lp(i,e,t,n,r))r.stopPropagation();else if(Fp(e,r),t&4&&-1<Pp.indexOf(e)){for(;i!==null;){var a=Et(i);if(a!==null)switch(a.tag){case 3:if(a=a.stateNode,a.current.memoizedState.isDehydrated){var o=et(a.pendingLanes);if(o!==0){var s=a;for(s.pendingLanes|=2,s.entangledLanes|=2;o;){var c=1<<31-qe(o);s.entanglements[1]|=c,o&=~c}xd(a),!(Zl&6)&&(vu=Fe()+500,Sd(0,!1))}}break;case 31:case 13:s=pi(a,2),s!==null&&Mu(s,a,2),Lu(),z(a,2)}if(a=wp(r),a===null&&Ud(e,t,r,Tp,n),a===i)break;i=a}i!==null&&r.stopPropagation()}else Ud(e,t,r,null,n)}}function wp(e){return e=fn(e),Ep(e)}var Tp=null;function Ep(e){if(Tp=null,e=Tt(e),e!==null){var t=o(e);if(t===null)e=null;else{var n=t.tag;if(n===13){if(e=s(t),e!==null)return e;e=null}else if(n===31){if(e=c(t),e!==null)return e;e=null}else if(n===3){if(t.stateNode.current.memoizedState.isDehydrated)return t.tag===3?t.stateNode.containerInfo:null;e=null}else t!==e&&(e=null)}}return Tp=e,null}function Dp(e){switch(e){case`beforetoggle`:case`cancel`:case`click`:case`close`:case`contextmenu`:case`copy`:case`cut`:case`auxclick`:case`dblclick`:case`dragend`:case`dragstart`:case`drop`:case`focusin`:case`focusout`:case`input`:case`invalid`:case`keydown`:case`keypress`:case`keyup`:case`mousedown`:case`mouseup`:case`paste`:case`pause`:case`play`:case`pointercancel`:case`pointerdown`:case`pointerup`:case`ratechange`:case`reset`:case`resize`:case`seeked`:case`submit`:case`toggle`:case`touchcancel`:case`touchend`:case`touchstart`:case`volumechange`:case`change`:case`selectionchange`:case`textInput`:case`compositionstart`:case`compositionend`:case`compositionupdate`:case`beforeblur`:case`afterblur`:case`beforeinput`:case`blur`:case`fullscreenchange`:case`focus`:case`hashchange`:case`popstate`:case`select`:case`selectstart`:return 2;case`drag`:case`dragenter`:case`dragexit`:case`dragleave`:case`dragover`:case`mousemove`:case`mouseout`:case`mouseover`:case`pointermove`:case`pointerout`:case`pointerover`:case`scroll`:case`touchmove`:case`wheel`:case`mouseenter`:case`mouseleave`:case`pointerenter`:case`pointerleave`:return 8;case`message`:switch(Ie()){case Le:return 2;case Re:return 8;case ze:case Be:return 32;case Ve:return 268435456;default:return 32}default:return 32}}var Op=!1,kp=null,Ap=null,V=null,jp=new Map,Mp=new Map,Np=[],Pp=`mousedown mouseup touchcancel touchend touchstart auxclick dblclick pointercancel pointerdown pointerup dragend dragstart drop compositionend compositionstart keydown keypress keyup input textInput copy cut paste click change contextmenu reset`.split(` `);function Fp(e,t){switch(e){case`focusin`:case`focusout`:kp=null;break;case`dragenter`:case`dragleave`:Ap=null;break;case`mouseover`:case`mouseout`:V=null;break;case`pointerover`:case`pointerout`:jp.delete(t.pointerId);break;case`gotpointercapture`:case`lostpointercapture`:Mp.delete(t.pointerId)}}function Ip(e,t,n,r,i,a){return e===null||e.nativeEvent!==a?(e={blockedOn:t,domEventName:n,eventSystemFlags:r,nativeEvent:a,targetContainers:[i]},t!==null&&(t=Et(t),t!==null&&B(t)),e):(e.eventSystemFlags|=r,t=e.targetContainers,i!==null&&t.indexOf(i)===-1&&t.push(i),e)}function Lp(e,t,n,r,i){switch(t){case`focusin`:return kp=Ip(kp,e,t,n,r,i),!0;case`dragenter`:return Ap=Ip(Ap,e,t,n,r,i),!0;case`mouseover`:return V=Ip(V,e,t,n,r,i),!0;case`pointerover`:var a=i.pointerId;return jp.set(a,Ip(jp.get(a)||null,e,t,n,r,i)),!0;case`gotpointercapture`:return a=i.pointerId,Mp.set(a,Ip(Mp.get(a)||null,e,t,n,r,i)),!0}return!1}function Rp(e){var t=Tt(e.target);if(t!==null){var n=o(t);if(n!==null){if(t=n.tag,t===13){if(t=s(n),t!==null){e.blockedOn=t,mt(e.priority,function(){yp(n)});return}}else if(t===31){if(t=c(n),t!==null){e.blockedOn=t,mt(e.priority,function(){yp(n)});return}}else if(t===3&&n.stateNode.current.memoizedState.isDehydrated){e.blockedOn=n.tag===3?n.stateNode.containerInfo:null;return}}}e.blockedOn=null}function zp(e){if(e.blockedOn!==null)return!1;for(var t=e.targetContainers;0<t.length;){var n=wp(e.nativeEvent);if(n===null){n=e.nativeEvent;var r=new n.constructor(n.type,n);dn=r,n.target.dispatchEvent(r),dn=null}else return t=Et(n),t!==null&&B(t),e.blockedOn=n,!1;t.shift()}return!0}function Bp(e,t,n){zp(e)&&n.delete(t)}function Vp(){Op=!1,kp!==null&&zp(kp)&&(kp=null),Ap!==null&&zp(Ap)&&(Ap=null),V!==null&&zp(V)&&(V=null),jp.forEach(Bp),Mp.forEach(Bp)}function Hp(e,n){e.blockedOn===n&&(e.blockedOn=null,Op||(Op=!0,t.unstable_scheduleCallback(t.unstable_NormalPriority,Vp)))}var Up=null;function Wp(e){Up!==e&&(Up=e,t.unstable_scheduleCallback(t.unstable_NormalPriority,function(){Up===e&&(Up=null);for(var t=0;t<e.length;t+=3){var n=e[t],r=e[t+1],i=e[t+2];if(typeof r!=`function`){if(Ep(r||n)===null)continue;break}var a=Et(n);a!==null&&(e.splice(t,3),t-=3,Ps(a,{pending:!0,data:i,method:n.method,action:r},r,i))}}))}function Gp(e){function t(t){return Hp(t,e)}kp!==null&&Hp(kp,e),Ap!==null&&Hp(Ap,e),V!==null&&Hp(V,e),jp.forEach(t),Mp.forEach(t);for(var n=0;n<Np.length;n++){var r=Np[n];r.blockedOn===e&&(r.blockedOn=null)}for(;0<Np.length&&(n=Np[0],n.blockedOn===null);)Rp(n),n.blockedOn===null&&Np.shift();if(n=(e.ownerDocument||e).$$reactFormReplay,n!=null)for(r=0;r<n.length;r+=3){var i=n[r],a=n[r+1],o=i[_t]||null;if(typeof a==`function`)o||Wp(n);else if(o){var s=null;if(a&&a.hasAttribute(`formAction`)){if(i=a,o=a[_t]||null)s=o.formAction;else if(Ep(i)!==null)continue}else s=o.action;typeof s==`function`?n[r+1]=s:(n.splice(r,3),r-=3),Wp(n)}}}function Kp(){function e(e){e.canIntercept&&e.info===`react-transition`&&e.intercept({handler:function(){return new Promise(function(e){return i=e})},focusReset:`manual`,scroll:`manual`})}function t(){i!==null&&(i(),i=null),r||setTimeout(n,20)}function n(){if(!r&&!navigation.transition){var e=navigation.currentEntry;e&&e.url!=null&&navigation.navigate(e.url,{state:e.getState(),info:`react-transition`,history:`replace`})}}if(typeof navigation==`object`){var r=!1,i=null;return navigation.addEventListener(`navigate`,e),navigation.addEventListener(`navigatesuccess`,t),navigation.addEventListener(`navigateerror`,t),setTimeout(n,100),function(){r=!0,navigation.removeEventListener(`navigate`,e),navigation.removeEventListener(`navigatesuccess`,t),navigation.removeEventListener(`navigateerror`,t),i!==null&&(i(),i=null)}}}function qp(e){this._internalRoot=e}Jp.prototype.render=qp.prototype.render=function(e){var t=this._internalRoot;if(t===null)throw Error(i(409));var n=t.current;R(n,Au(),e,t,null,null)},Jp.prototype.unmount=qp.prototype.unmount=function(){var e=this._internalRoot;if(e!==null){this._internalRoot=null;var t=e.containerInfo;R(e.current,2,null,e,null,null),Lu(),t[vt]=null}};function Jp(e){this._internalRoot=e}Jp.prototype.unstable_scheduleHydration=function(e){if(e){var t=pt();e={blockedOn:null,target:e,priority:t};for(var n=0;n<Np.length&&t!==0&&t<Np[n].priority;n++);Np.splice(n,0,e),n===0&&Rp(e)}};var Yp=n.version;if(Yp!==`19.2.8`)throw Error(i(527,Yp,`19.2.8`));ce.findDOMNode=function(e){var t=e._reactInternals;if(t===void 0)throw typeof e.render==`function`?Error(i(188)):(e=Object.keys(e).join(`,`),Error(i(268,e)));return e=d(t),e=e===null?null:p(e),e=e===null?null:e.stateNode,e};var Xp={bundleType:0,version:`19.2.8`,rendererPackageName:`react-dom`,currentDispatcherRef:O,reconcilerVersion:`19.2.8`};if(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__<`u`){var Zp=__REACT_DEVTOOLS_GLOBAL_HOOK__;if(!Zp.isDisabled&&Zp.supportsFiber)try{We=Zp.inject(Xp),Ge=Zp}catch{}}e.createRoot=function(e,t){if(!a(e))throw Error(i(299));var n=!1,r=``,o=rc,s=ic,c=ac;return t!=null&&(!0===t.unstable_strictMode&&(n=!0),t.identifierPrefix!==void 0&&(r=t.identifierPrefix),t.onUncaughtError!==void 0&&(o=t.onUncaughtError),t.onCaughtError!==void 0&&(s=t.onCaughtError),t.onRecoverableError!==void 0&&(c=t.onRecoverableError)),t=gp(e,1,!1,null,null,n,r,null,o,s,c,Kp),e[vt]=t.current,Vd(e),new qp(t)}})),g=o(((e,t)=>{function n(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>`u`||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!=`function`))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(n)}catch(e){console.error(e)}}n(),t.exports=h()})),_=/^(?:[a-z][a-z0-9+.-]*:|[\\/]{2})/i,v=/^[\\/]{2}/;function y(e,t){return t+e.replace(/\\/g,`/`)}var b=`popstate`;function x(e){return typeof e==`object`&&!!e&&`pathname`in e&&`search`in e&&`hash`in e&&`state`in e&&`key`in e}function S(e={}){function t(e,t){let n=t.state?.masked,{pathname:r,search:i,hash:a}=n||e.location;return te(``,{pathname:r,search:i,hash:a},t.state&&t.state.usr||null,t.state&&t.state.key||`default`,n?{pathname:e.location.pathname,search:e.location.search,hash:e.location.hash}:void 0)}function n(e,t){return typeof t==`string`?t:ne(t)}return E(t,n,null,e)}function C(e,t){if(e===!1||e==null)throw Error(t)}function w(e,t){if(!e){typeof console<`u`&&console.warn(t);try{throw Error(t)}catch{}}}function T(){return Math.random().toString(36).substring(2,10)}function ee(e,t){return{usr:e.state,key:e.key,idx:t,masked:e.mask?{pathname:e.pathname,search:e.search,hash:e.hash}:void 0}}function te(e,t,n=null,r,i){return{pathname:typeof e==`string`?e:e.pathname,search:``,hash:``,...typeof t==`string`?re(t):t,state:n,key:t&&t.key||r||T(),mask:i}}function ne({pathname:e=`/`,search:t=``,hash:n=``}){return t&&t!==`?`&&(e+=t.charAt(0)===`?`?t:`?`+t),n&&n!==`#`&&(e+=n.charAt(0)===`#`?n:`#`+n),e}function re(e){let t={};if(e){let n=e.indexOf(`#`);n>=0&&(t.hash=e.substring(n),e=e.substring(0,n));let r=e.indexOf(`?`);r>=0&&(t.search=e.substring(r),e=e.substring(0,r)),e&&(t.pathname=e)}return t}function E(e,t,n,r={}){let{window:i=document.defaultView,v5Compat:a=!1}=r,o=i.history,s=`POP`,c=null,l=u();l??(l=0,o.replaceState({...o.state,idx:l},``));function u(){return(o.state||{idx:null}).idx}function d(){s=`POP`;let e=u(),t=e==null?null:e-l;l=e,c&&c({action:s,location:h.location,delta:t})}function f(e,t){s=`PUSH`;let r=x(e)?e:te(h.location,e,t);n&&n(r,e),l=u()+1;let d=ee(r,l),f=h.createHref(r.mask||r);try{o.pushState(d,``,f)}catch(e){if(e instanceof DOMException&&e.name===`DataCloneError`)throw e;i.location.assign(f)}a&&c&&c({action:s,location:h.location,delta:1})}function p(e,t){s=`REPLACE`;let r=x(e)?e:te(h.location,e,t);n&&n(r,e),l=u();let i=ee(r,l),d=h.createHref(r.mask||r);o.replaceState(i,``,d),a&&c&&c({action:s,location:h.location,delta:0})}function m(e){return ie(i,e)}let h={get action(){return s},get location(){return e(i,o)},listen(e){if(c)throw Error(`A history only accepts one active listener`);return i.addEventListener(b,d),c=e,()=>{i.removeEventListener(b,d),c=null}},createHref(e){return t(i,e)},createURL:m,encodeLocation(e){let t=m(e);return{pathname:t.pathname,search:t.search,hash:t.hash}},push:f,replace:p,go(e){return o.go(e)}};return h}function ie(e,t,n=!1){let r=`http://localhost`;e&&(r=e.location.origin===`null`?e.location.href:e.location.origin),C(r,`No window.location.(origin|href) available to create URL`);let i=typeof t==`string`?t:ne(t);return i=i.replace(/ $/,`%20`),!n&&v.test(i)&&(i=r+i),new URL(i,r)}var D=c(u(),1),ae=class{#e=new Map;constructor(e){if(e)for(let[t,n]of e)this.set(t,n)}get(e){if(this.#e.has(e))return this.#e.get(e);if(e.defaultValue!==void 0)return e.defaultValue;throw Error(`No value found for context`)}set(e,t){this.#e.set(e,t)}},oe=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`children`]);function se(e){return oe.has(e)}var O=new Set([`lazy`,`caseSensitive`,`path`,`id`,`index`,`middleware`,`children`]);function ce(e){return O.has(e)}function le(e){return e.index===!0}function ue(e){let t={};return e.Component&&Object.assign(t,{element:D.createElement(e.Component),Component:void 0}),e.HydrateFallback&&Object.assign(t,{hydrateFallbackElement:D.createElement(e.HydrateFallback),HydrateFallback:void 0}),e.ErrorBoundary&&Object.assign(t,{errorElement:D.createElement(e.ErrorBoundary),ErrorBoundary:void 0}),t}function de(e,t=ue,n=[],r={},i=!1){return e.map((e,a)=>{let o=[...n,String(a)],s=typeof e.id==`string`?e.id:o.join(`-`);if(C(e.index!==!0||!e.children,`Cannot specify children on an index route`),C(i||!r[s],`Found a route id collision on id "${s}". Route id's must be globally unique within Data Router usages`),le(e)){let n={...e,id:s};return r[s]=fe(n,t(n)),n}{let n={...e,id:s,children:void 0};return r[s]=fe(n,t(n)),e.children&&(n.children=de(e.children,t,o,r,i)),n}})}function fe(e,t){return Object.assign(e,{...t,...typeof t.lazy==`object`&&t.lazy!=null?{lazy:{...e.lazy,...t.lazy}}:{}})}function pe(e,t,n=`/`){return me(e,t,n,!1)}function me(e,t,n,r,i){let a=Ie((typeof t==`string`?re(t):t).pathname||`/`,n);if(a==null)return null;let o=i??ge(e),s=null,c=Fe(a);for(let e=0;s==null&&e<o.length;++e)s=je(o[e],c,r);return s}function he(e,t){let{route:n,pathname:r,params:i}=e;return{id:n.id,pathname:r,params:i,loaderData:t[n.id],handle:n.handle}}function ge(e){let t=_e(e);return ye(t),t}function _e(e,t=[],n=[],r=``,i=!1){let a=(e,a,o=i,s)=>{let c={relativePath:s===void 0?e.path||``:s,caseSensitive:e.caseSensitive===!0,childrenIndex:a,route:e};if(c.relativePath.startsWith(`/`)){if(!c.relativePath.startsWith(r)&&o)return;C(c.relativePath.startsWith(r),`Absolute route path "${c.relativePath}" nested under path "${r}" is not valid. An absolute child route path must start with the combined path of all its parent routes.`),c.relativePath=c.relativePath.slice(r.length)}let l=Ke([r,c.relativePath]),u=n.concat(c);e.children&&e.children.length>0&&(C(e.index!==!0,`Index routes must not have child routes. Please remove all child routes from route path "${l}".`),_e(e.children,t,u,l,o)),(e.path!=null||e.index)&&t.push({path:l,score:ke(l,e.index),routesMeta:u.map((e,t)=>{let[n,r]=Pe(e.relativePath,e.caseSensitive,t===u.length-1);return{...e,matcher:n,compiledParams:r}})})};return e.forEach((e,t)=>{if(e.path===``||!e.path?.includes(`?`))a(e,t);else for(let n of ve(e.path))a(e,t,!0,n)}),t}function ve(e){let t=e.split(`/`);if(t.length===0)return[];let[n,...r]=t,i=n.endsWith(`?`),a=n.replace(/\?$/,``);if(r.length===0)return i?[a,``]:[a];let o=ve(r.join(`/`)),s=[];return s.push(...o.map(e=>e===``?a:[a,e].join(`/`))),i&&s.push(...o),s.map(t=>e.startsWith(`/`)&&t===``?`/`:t)}function ye(e){e.sort((e,t)=>e.score===t.score?Ae(e.routesMeta.map(e=>e.childrenIndex),t.routesMeta.map(e=>e.childrenIndex)):t.score-e.score)}var be=/^:[\w-]+$/,xe=/^:[\w-]+/,Se=3.5,Ce=3,we=2,Te=1,Ee=10,De=-2,Oe=e=>e===`*`;function ke(e,t){let n=e.split(`/`),r=n.length;return n.some(Oe)&&(r+=De),t&&(r+=we),n.filter(e=>!Oe(e)).reduce((e,t)=>e+(be.test(t)?Ce:xe.test(t)?Se:t===``?Te:Ee),r)}function Ae(e,t){return e.length===t.length&&e.slice(0,-1).every((e,n)=>e===t[n])?e[e.length-1]-t[t.length-1]:0}function je(e,t,n=!1){let{routesMeta:r}=e,i={},a=`/`,o=[];for(let e=0;e<r.length;++e){let s=r[e],c=e===r.length-1,l=a===`/`?t:t.slice(a.length)||`/`,u={path:s.relativePath,caseSensitive:s.caseSensitive,end:c},d=s.matcher&&s.compiledParams?Ne(u,l,s.matcher,s.compiledParams):Me(u,l),f=s.route;if(!d&&c&&n&&!r[r.length-1].route.index&&(d=Me({path:s.relativePath,caseSensitive:s.caseSensitive,end:!1},l)),!d)return null;Object.assign(i,d.params),o.push({params:i,pathname:Ke([a,d.pathname]),pathnameBase:Je(Ke([a,d.pathnameBase])),route:f}),d.pathnameBase!==`/`&&(a=Ke([a,d.pathnameBase]))}return o}function Me(e,t){typeof e==`string`&&(e={path:e,caseSensitive:!1,end:!0});let[n,r]=Pe(e.path,e.caseSensitive,e.end);return Ne(e,t,n,r)}function Ne(e,t,n,r){let i=t.match(n);if(!i)return null;let a=i[0],o=qe(a,1),s=i.slice(1);return{params:r.reduce((e,{paramName:t,isOptional:n},r)=>{if(t===`*`){let e=s[r]||``;o=qe(a.slice(0,a.length-e.length),1)}let i=s[r];return e[t]=n&&!i?void 0:(i||``).replace(/%2F/g,`/`),e},{}),pathname:a,pathnameBase:o,pattern:e}}function Pe(e,t=!1,n=!0){w(e===`*`||!e.endsWith(`*`)||e.endsWith(`/*`),`Route path "${e}" will be treated as if it were "${e.replace(/\*$/,`/*`)}" because the \`*\` character must always follow a \`/\` in the pattern. To get rid of this warning, please change the route path to "${e.replace(/\*$/,`/*`)}".`);let r=[],i=`^`+e.replace(/\/*\*?$/,``).replace(/^\/*/,`/`).replace(/[\\.*+^${}|()[\]]/g,`\\$&`).replace(/\/:([\w-]+)(\?)?/g,(e,t,n,i,a)=>{if(r.push({paramName:t,isOptional:n!=null}),n){let t=a.charAt(i+e.length);return t&&t!==`/`?`/([^\\/]*)`:`(?:/([^\\/]*))?`}return`/([^\\/]+)`}).replace(/\/([\w-]+)\?(?=\/|$|\()/g,`(?:/$1)?`);return e.endsWith(`*`)?(r.push({paramName:`*`}),i+=e===`*`||e===`/*`?`(.*)$`:`(?:\\/(.+)|\\/*)$`):n?i+=`\\/*$`:e!==``&&e!==`/`&&(i+=`(?:(?=\\/|$))`),[new RegExp(i,t?void 0:`i`),r]}function Fe(e){try{return e.split(`/`).map(e=>decodeURIComponent(e).replace(/\//g,`%2F`)).join(`/`)}catch(t){return w(!1,`The URL path "${e}" could not be decoded because it is a malformed URL segment. This is probably due to a bad percent encoding (${t}).`),e}}function Ie(e,t){if(t===`/`)return e;if(!e.toLowerCase().startsWith(t.toLowerCase()))return null;let n=t.endsWith(`/`)?t.length-1:t.length,r=e.charAt(n);return r&&r!==`/`?null:e.slice(n)||`/`}function Le({basename:e,pathname:t}){return t===`/`?e:Ke([e,t])}var Re=e=>_.test(e);function ze(e,t=`/`){let{pathname:n,search:r=``,hash:i=``}=typeof e==`string`?re(e):e,a;return n?(n=Ge(n),a=n.startsWith(`/`)||n.startsWith(`\\`)?Be(n.substring(1),`/`):Be(n,t)):a=t,{pathname:a,search:Ye(r),hash:Xe(i)}}function Be(e,t){let n=qe(t).split(`/`);return e.split(`/`).forEach(e=>{e===`..`?n.length>1&&n.pop():e!==`.`&&n.push(e)}),n.length>1?n.join(`/`):`/`}function Ve(e,t,n,r){return`Cannot include a '${e}' character in a manually specified \`to.${t}\` field [${JSON.stringify(r)}]. Please separate it out to the \`to.${n}\` field. Alternatively you may provide the full path as a string in <Link to="..."> and the router will parse it for you.`}function He(e){return e.filter((e,t)=>t===0||e.route.path&&e.route.path.length>0)}function Ue(e){let t=He(e);return t.map((e,n)=>n===t.length-1?e.pathname:e.pathnameBase)}function We(e,t,n,r=!1){let i;typeof e==`string`?i=re(e):(i={...e},C(!i.pathname||!i.pathname.includes(`?`),Ve(`?`,`pathname`,`search`,i)),C(!i.pathname||!i.pathname.includes(`#`),Ve(`#`,`pathname`,`hash`,i)),C(!i.search||!i.search.includes(`#`),Ve(`#`,`search`,`hash`,i)));let a=e===``||i.pathname===``,o=a?`/`:i.pathname,s;if(o==null)s=n;else{let e=t.length-1;if(!r&&o.startsWith(`..`)){let t=o.split(`/`);for(;t[0]===`..`;)t.shift(),--e;i.pathname=t.join(`/`)}s=e>=0?t[e]:`/`}let c=ze(i,s),l=o&&o!==`/`&&o.endsWith(`/`),u=(a||o===`.`)&&n.endsWith(`/`);return!c.pathname.endsWith(`/`)&&(l||u)&&(c.pathname+=`/`),c}var Ge=e=>e.replace(/[\\/]{2,}/g,`/`),Ke=e=>Ge(e.join(`/`));function qe(e,t=0){let n=e.length;for(;n>t&&e.charCodeAt(n-1)===47;)n--;return n===e.length?e:e.slice(0,n)}var Je=e=>qe(e).replace(/^\/*/,`/`),Ye=e=>!e||e===`?`?``:e.startsWith(`?`)?e:`?`+e,Xe=e=>!e||e===`#`?``:e.startsWith(`#`)?e:`#`+e,Ze=[`EvalError`,`RangeError`,`ReferenceError`,`SyntaxError`,`TypeError`,`URIError`],Qe=class{status;statusText;data;error;internal;constructor(e,t,n,r=!1){this.status=e,this.statusText=t||``,this.internal=r,n instanceof Error?(this.data=n.toString(),this.error=n):this.data=n}};function $e(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.internal==`boolean`&&`data`in e}function et(e){return Ke(e.map(e=>e.route.path).filter(Boolean))||`/`}function tt(e,t){let n=new URL(typeof e==`string`||e instanceof URL?e:e.url),r=typeof t==`string`?re(t):t;if(n.pathname=r.pathname||`/`,r.search){let e=new URLSearchParams(r.search),t=e.getAll(`index`);e.delete(`index`);for(let n of t.filter(Boolean))e.append(`index`,n);let i=e.toString();n.search=i?`?${i}`:``}else n.search=``;return n.hash=r.hash||``,n}var nt=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;function rt(e,t){let n=e;if(typeof n!=`string`||!_.test(n))return{absoluteURL:void 0,isExternal:!1,to:n};let r=n,i=!1;if(nt)try{let e=new URL(window.location.href),r=v.test(n)?new URL(y(n,e.protocol)):new URL(n),a=Ie(r.pathname,t);r.origin===e.origin&&a!=null?n=a+r.search+r.hash:i=!0}catch{w(!1,`<Link to="${n}"> contains an invalid URL which will probably break when clicked - please update to a valid URL path.`)}return{absoluteURL:r,isExternal:i,to:n}}var it=Symbol(`Uninstrumented`),at=new WeakMap;function ot(e,t){let n={lazy:[],"lazy.loader":[],"lazy.action":[],"lazy.middleware":[],middleware:[],loader:[],action:[]};e.forEach(e=>e({id:t.id,index:t.index,path:t.path,instrument(e){e.lazy!=null&&n.lazy.push(e.lazy),e[`lazy.loader`]!=null&&n[`lazy.loader`].push(e[`lazy.loader`]),e[`lazy.action`]!=null&&n[`lazy.action`].push(e[`lazy.action`]),e[`lazy.middleware`]!=null&&n[`lazy.middleware`].push(e[`lazy.middleware`]),e.middleware!=null&&n.middleware.push(e.middleware),e.loader!=null&&n.loader.push(e.loader),e.action!=null&&n.action.push(e.action)}}));let r={};if(typeof t.lazy==`function`&&n.lazy.length>0){let e=t.lazy;r.lazy=async(...t)=>ft(await pt(n.lazy,void 0,()=>e(...t),mt))}if(typeof t.lazy==`object`){let e=t.lazy;if(typeof e.middleware==`function`&&n[`lazy.middleware`].length>0){let t=e.middleware;r.lazy=Object.assign(r.lazy||{},{middleware:async(...e)=>ft(await pt(n[`lazy.middleware`],void 0,()=>t(...e),mt))})}if(typeof e.loader==`function`&&n[`lazy.loader`].length>0){let t=e.loader;r.lazy=Object.assign(r.lazy||{},{loader:async(...e)=>ft(await pt(n[`lazy.loader`],void 0,()=>t(...e),mt))})}if(typeof e.action==`function`&&n[`lazy.action`].length>0){let t=e.action;r.lazy=Object.assign(r.lazy||{},{action:async(...e)=>ft(await pt(n[`lazy.action`],void 0,()=>t(...e),mt))})}}if(typeof t.loader==`function`&&n.loader.length>0){let e=ct(t.loader),i=async(...t)=>ft(await pt(n.loader,ht(t[0]),()=>e(...t),mt));e.hydrate===!0&&(i.hydrate=!0),lt(i,e),r.loader=i}if(typeof t.action==`function`&&n.action.length>0){let e=ct(t.action),i=async(...t)=>ft(await pt(n.action,ht(t[0]),()=>e(...t),mt));lt(i,e),r.action=i}return t.middleware&&t.middleware.length>0&&n.middleware.length>0&&(r.middleware=t.middleware.map(e=>{let t=ct(e),r=async(...e)=>ft(await pt(n.middleware,ht(e[0]),()=>t(...e),mt));return lt(r,t),r})),r}function st(e,t){let n={navigate:[],fetch:[]};if(t.forEach(e=>e({instrument(e){e.navigate!=null&&n.navigate.push(e.navigate),e.fetch!=null&&n.fetch.push(e.fetch)}})),n.navigate.length>0){let t=ct(e.navigate),r=async(...r)=>{let[i,a]=r,o,s={to:typeof i==`number`||typeof i==`string`?i:i?ne(i):`.`,...gt(e,a??{})};return ft(await pt(n.navigate,s,async()=>{if(typeof i==`number`)return await t(...r);let n=ut(e,e=>{o=e});try{return await t(...r)}finally{n()}},e=>({...mt(e),meta:o})))};lt(r,t),e.navigate=r}if(n.fetch.length>0){let t=ct(e.fetch),r=async(...r)=>{let[i,a,o,s]=r,c;return ft(await pt(n.fetch,{href:o??`.`,fetcherKey:i,...gt(e,s??{})},async()=>{let n=ut(e,e=>{c=e});try{return await t(...r)}finally{n()}},e=>({...mt(e),meta:c})))};lt(r,t),e.fetch=r}return e}function ct(e){return e[it]??e}function lt(e,t){e[it]=t}function ut(e,t){return at.set(e,t),()=>{at.get(e)===t&&at.delete(e)}}function dt(e){let t=at.get(e);return at.delete(e),t}function ft(e){if(e.type===`error`)throw e.value;return e.value}async function pt(e,t,n,r,i={result:null,innerResult:null},a=e.length-1){let o=e[a];if(o){let s,c=async()=>(s?console.error(`You cannot call instrumented handlers more than once`):s=pt(e,t,n,r,i,a-1),await s,C(i.innerResult,`Expected an inner result`),i.innerResult);try{await o(c,t)}catch(e){console.error(`An instrumentation function threw an error:`,e)}s||await c(),await s}else{try{i.result={type:`success`,value:await n()}}catch(e){i.result={type:`error`,value:e}}i.innerResult=r(i.result,t)}return i.result?i.result:(i.result={type:`error`,value:Error(`No result assigned in instrumentation chain.`)},i.innerResult=r(i.result,t),i.result)}function mt(e){return e.type===`error`&&e.value instanceof Error?{status:`error`,error:e.value}:{status:`success`,error:void 0}}function ht(e){let{request:t,context:n,params:r}=e;return{...e,request:_t(t),params:{...r},context:vt(n)}}function gt(e,t){return{currentUrl:ne(e.state.location),...`formMethod`in t?{formMethod:t.formMethod}:{},...`formEncType`in t?{formEncType:t.formEncType}:{},...`formData`in t?{formData:t.formData}:{},...`body`in t?{body:t.body}:{}}}function _t(e){return{method:e.method,url:e.url,headers:{get:(...t)=>e.headers.get(...t)}}}function vt(e){return{get:t=>e.get(t)}}var yt=new URL(`http://localhost`);function bt(e){if(e.createURL)return e.createURL(`/`);try{return new URL(e.createHref(`/`),yt)}catch{return yt}}function xt(e,t){return e.origin===t.origin&&(e.origin!==`null`||e.protocol===t.protocol&&e.host===t.host)}function St(e,t){if(e.startsWith(`//`))return!0;let n=t.protocol.toLowerCase();return e.toLowerCase().startsWith(n)?t.host===``||e.slice(n.length).startsWith(`//`):!1}function Ct(e,t,n,r){let i=null;try{i=e==null?null:new URL(e,n)}catch{}let a=new URL(t,n),o=i!=null&&!xt(i,n),s=!xt(a,n);if(r===`reject`){if(o||s)throw Error(`External navigation is not allowed`)}else if(s&&(i==null||!St(e,i)||!xt(i,a)))throw Error(`External navigation is not allowed`)}var wt=[`POST`,`PUT`,`PATCH`,`DELETE`],Tt=new Set(wt),Et=[`GET`,...wt],Dt=new Set(Et),Ot=new Set([301,302,303,307,308]),kt=new Set([307,308]),At={state:`idle`,location:void 0,matches:void 0,historyAction:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},jt={state:`idle`,data:void 0,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0},Mt={state:`unblocked`,proceed:void 0,reset:void 0,location:void 0},Nt=`remix-router-transitions`,Pt=Symbol(`ResetLoaderData`),Ft=class{#e;#t;#n;#r;constructor(e){this.#e=e,this.#t=ge(e)}get stableRoutes(){return this.#e}get activeRoutes(){return this.#n??this.#e}get branches(){return this.#r??this.#t}get hasHMRRoutes(){return this.#n!=null}setRoutes(e){this.#e=e,this.#t=ge(e)}setHmrRoutes(e){this.#n=e,this.#r=ge(e)}commitHmrRoutes(){this.#n&&(this.#e=this.#n,this.#t=this.#r,this.#n=void 0,this.#r=void 0)}};function It(e){let t=e.window?e.window:typeof window<`u`?window:void 0,n=t!==void 0&&t.document!==void 0&&t.document.createElement!==void 0;C(e.routes.length>0,`You must provide a non-empty routes array to createRouter`);let r=e.hydrationRouteProperties||[],i=e.mapRouteProperties,a=i||(()=>({}));if(e.instrumentations){let t=e.instrumentations;a=e=>({...i?.(e),...ot(t.map(e=>e.route).filter(Boolean),e)})}let o={},s=new Ft(de(e.routes,a,void 0,o)),c=e.basename||`/`;c.startsWith(`/`)||(c=`/${c}`);let l=e.dataStrategy||$t,u={...e.future},d=null,f=new Set,p=null,m=null,h=null,g=null,_=e.hydrationData!=null,y=me(s.activeRoutes,e.history.location,c,!1,s.branches),b=!1,x=null,S,T;if(y==null&&!e.patchRoutesOnNavigation){let t=wn(404,{pathname:e.history.location.pathname}),{matches:n,route:r}=Cn(s.activeRoutes);S=!0,T=!S,y=n,x={[r.id]:t}}else if(y&&!e.hydrationData&&vt(y,s.activeRoutes,e.history.location.pathname).active&&(y=null),!y){S=!1,T=!S,y=[];let t=vt(null,s.activeRoutes,e.history.location.pathname);t.active&&t.matches&&(b=!0,y=t.matches)}else if(y.some(e=>e.route.lazy))S=!1,T=!S;else if(!y.some(e=>Vt(e.route)))S=!0,T=!S;else{let t=e.hydrationData?e.hydrationData.loaderData:null,n=e.hydrationData?e.hydrationData.errors:null,r=y;if(n){let e=y.findIndex(e=>n[e.route.id]!==void 0);r=r.slice(0,e+1)}T=!1,S=!0,r.forEach(e=>{let r=Ht(e.route,t,n);T||=r.renderFallback,S&&=!r.shouldLoad})}let ee,E={historyAction:e.history.action,location:e.history.location,matches:y,initialized:S,renderFallback:T,navigation:At,restoreScrollPosition:e.hydrationData==null&&null,preventScrollReset:!1,revalidation:`idle`,loaderData:e.hydrationData&&e.hydrationData.loaderData||{},actionData:e.hydrationData&&e.hydrationData.actionData||null,errors:e.hydrationData&&e.hydrationData.errors||x,fetchers:new Map,blockers:new Map},D=`POP`,oe=null,se=!1,O,ce=!1,le=new Map,ue=null,fe=!1,pe=!1,ge=new Set,_e=new Map,ve=0,ye=-1,be=new Map,xe=new Set,Se=new Map,Ce=new Map,we=new Set,Te=new Map,Ee,De=null;function Oe(){if(d=e.history.listen(({action:t,location:n,delta:r})=>{if(Ee){Ee(),Ee=void 0;return}w(Te.size===0||r!=null,"You are trying to use a blocker on a POP navigation to a location that was not created by @remix-run/router. This will fail silently in production. This can happen if you are navigating outside the router via `window.history.pushState`/`window.location.hash` instead of using router navigation APIs. This can also happen if you are using createHashRouter and the user manually changes the URL.");let i=ft({currentLocation:E.location,nextLocation:n,historyAction:t});if(i&&r!=null){let t=new Promise(e=>{Ee=e});e.history.go(r*-1),ut(i,{state:`blocked`,location:n,proceed(){ut(i,{state:`proceeding`,proceed:void 0,reset:void 0,location:n}),t.then(()=>e.history.go(r))},reset(){let e=new Map(E.blockers);e.set(i,Mt),je({blockers:e})}}),oe?.resolve(),oe=null;return}return Fe(t,n)}),n){Yn(t,le);let e=()=>Xn(t,le);t.addEventListener(`pagehide`,e),ue=()=>t.removeEventListener(`pagehide`,e)}return E.initialized||Fe(`POP`,E.location,{initialHydration:!0}),ee}function ke(){d&&d(),ue&&ue(),f.clear(),O&&O.abort(),E.fetchers.forEach((e,t)=>et(E.fetchers,t)),E.blockers.forEach((e,t)=>lt(t))}function Ae(e){if(f.add(e),p){let{newErrors:t}=p;p=null,e(E,{deletedFetchers:[],newErrors:t,viewTransitionOpts:void 0,flushSync:!1})}return()=>f.delete(e)}function je(e,t={}){e.matches&&=e.matches.map(e=>{let t=o[e.route.id],n=e.route;return n.element!==t.element||n.errorElement!==t.errorElement||n.hydrateFallbackElement!==t.hydrateFallbackElement?{...e,route:t}:e}),E={...E,...e};let n=[],r=[];E.fetchers.forEach((e,t)=>{e.state===`idle`&&(we.has(t)?n.push(t):r.push(t))}),we.forEach(e=>{!E.fetchers.has(e)&&!_e.has(e)&&n.push(e)}),f.size===0&&(p={newErrors:e.errors??null}),[...f].forEach(r=>r(E,{deletedFetchers:n,newErrors:e.errors??null,viewTransitionOpts:t.viewTransitionOpts,flushSync:t.flushSync===!0})),n.forEach(e=>et(E.fetchers,e)),r.forEach(e=>E.fetchers.delete(e))}function Me(t,n,{flushSync:r}={}){let i=E.actionData!=null&&E.navigation.formMethod!=null&&zn(E.navigation.formMethod)&&E.navigation.state===`loading`&&t.state?._isRedirect!==!0,a;a=n.actionData?Object.keys(n.actionData).length>0?n.actionData:null:i?E.actionData:null;let o=n.loaderData?bn(E.loaderData,n.loaderData,n.matches||[],n.errors):E.loaderData,c=E.blockers;c.size>0&&!fe&&(c=new Map(c),c.forEach((e,t)=>c.set(t,Mt)));let l=!fe&&_t(t,n.matches||E.matches),u=se===!0||E.navigation.formMethod!=null&&zn(E.navigation.formMethod)&&t.state?._isRedirect!==!0;s.commitHmrRoutes(),fe||D===`POP`||(D===`PUSH`?e.history.push(t,t.state):D===`REPLACE`&&e.history.replace(t,t.state));let d;if(D===`POP`){let e=le.get(E.location.pathname);e&&e.has(t.pathname)?d={currentLocation:E.location,nextLocation:t}:le.has(t.pathname)&&(d={currentLocation:t,nextLocation:E.location})}else if(ce){let e=le.get(E.location.pathname);e?e.add(t.pathname):(e=new Set([t.pathname]),le.set(E.location.pathname,e)),d={currentLocation:E.location,nextLocation:t}}je({...n,actionData:a,loaderData:o,historyAction:D,location:t,initialized:!0,renderFallback:!1,navigation:At,revalidation:`idle`,restoreScrollPosition:l,preventScrollReset:u,blockers:c},{viewTransitionOpts:d,flushSync:r===!0}),D=`POP`,se=!1,ce=!1,fe=!1,pe=!1,oe?.resolve(),oe=null,De?.resolve(),De=null}async function Ne(t,n){if(oe?.resolve(),oe=null,typeof t==`number`){oe||=Zn();let n=oe.promise;return e.history.go(t),n}let r=dt(ee),{path:i,submission:a,error:o}=zt(!1,Rt(E.location,E.matches,c,t,n?.fromRouteId,n?.relative),n),s;if(n?.mask){let t=typeof n.mask==`string`?re(n.mask):{...E.location.mask,...n.mask};if(s={pathname:t.pathname??``,search:t.search??``,hash:t.hash??``},v.test(s.pathname))throw Error(`External navigation is not allowed`);s.pathname.startsWith(`\\`)&&(s.pathname=s.pathname.replace(/^\\+/,`/`)),Ct(typeof n.mask==`string`?n.mask:ne(n.mask),ne(s),e.history.createURL(`/`),`reject`)}let l=E.location,u=te(l,i,n&&n.state,void 0,s);u={...u,...e.history.encodeLocation(u)},Ct(t==null?e.history.createHref(E.location):typeof t==`string`?t:ne(t),e.history.createHref(u.mask||u),e.history.createURL(`/`),`reject`);let d=n&&n.replace!=null?n.replace:void 0,f=`PUSH`;d===!0?f=`REPLACE`:d===!1||a!=null&&zn(a.formMethod)&&a.formAction===E.location.pathname+E.location.search&&(f=`REPLACE`);let p=n&&`preventScrollReset`in n?n.preventScrollReset===!0:void 0,m=(n&&n.flushSync)===!0,h=ft({currentLocation:l,nextLocation:u,historyAction:f});if(h){ut(h,{state:`blocked`,location:u,proceed(){ut(h,{state:`proceeding`,proceed:void 0,reset:void 0,location:u}),Ne(t,n)},reset(){let e=new Map(E.blockers);e.set(h,Mt),je({blockers:e})}});return}await Fe(f,u,{submission:a,pendingError:o,preventScrollReset:p,replace:n&&n.replace,enableViewTransition:n&&n.viewTransition,flushSync:m,callSiteDefaultShouldRevalidate:n&&n.defaultShouldRevalidate,instrumentationNavigateMetaReceiver:r})}function Pe(){De||=Zn(),Je(),je({revalidation:`loading`});let e=De.promise;return E.navigation.state===`submitting`?e:E.navigation.state===`idle`?(Fe(E.historyAction,E.location,{startUninterruptedRevalidation:!0}),e):(Fe(D||E.historyAction,E.navigation.location,{overrideNavigation:E.navigation,enableViewTransition:ce===!0}),e)}async function Fe(t,n,r){O&&O.abort(),O=null,D=t,fe=(r&&r.startUninterruptedRevalidation)===!0,gt(E.location,E.matches),se=(r&&r.preventScrollReset)===!0,ce=(r&&r.enableViewTransition)===!0;let i=s.activeRoutes,a=r?.initialHydration&&E.matches&&E.matches.length>0&&!b?E.matches:me(i,n,c,!1,s.branches),o=(r&&r.flushSync)===!0;if(a&&E.initialized&&!pe&&Dn(E.location,n)&&!(r&&r.submission&&zn(r.submission.formMethod))){Me(n,{matches:a},{flushSync:o});return}let l=vt(a,i,n.pathname);if(l.active&&l.matches&&(a=l.matches),r?.instrumentationNavigateMetaReceiver){let t=Hn(e.history,n,a);r.instrumentationNavigateMetaReceiver(t)}if(!a){let{error:e,notFoundMatches:t,route:r}=pt(n.pathname);Me(n,{matches:t,loaderData:{},errors:{[r.id]:e}},{flushSync:o});return}let u=r&&r.overrideNavigation?{...r.overrideNavigation,matches:a,historyAction:t}:void 0;O=new AbortController;let d=hn(e.history,n,O.signal,r&&r.submission),f=e.getContext?await e.getContext():new ae,p;if(r&&r.pendingError)p=[Sn(a).route.id,{type:`error`,error:r.pendingError}];else if(r&&r.submission&&zn(r.submission.formMethod)){let i=await Le(d,n,r.submission,a,t,f,l.active,r&&r.initialHydration===!0,{replace:r.replace,flushSync:o});if(i.shortCircuited)return;if(i.pendingActionResult){let[e,t]=i.pendingActionResult;if(Mn(t)&&$e(t.error)&&t.error.status===404){O=null,Me(n,{matches:i.matches,loaderData:{},errors:{[e]:t.error}});return}}a=i.matches||a,p=i.pendingActionResult,u=Wn(n,a,t,r.submission),o=!1,l.active=!1,d=hn(e.history,d.url,d.signal)}let{shortCircuited:m,matches:h,loaderData:g,errors:_,workingFetchers:v}=await ze(d,n,a,t,f,l.active,u,r&&r.submission,r&&r.fetcherSubmission,r&&r.replace,r&&r.initialHydration===!0,o,p,r&&r.callSiteDefaultShouldRevalidate);m||(O=null,Me(n,{matches:h||a,...xn(p),loaderData:g,errors:_,...v?{fetchers:v}:{}}))}async function Le(t,n,i,l,u,d,f,p,m={}){if(Je(),je({navigation:Gn(n,l,u,i)},{flushSync:m.flushSync===!0}),f){let e=await yt(l,n.pathname,t.signal);if(e.type===`aborted`)return{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=Cn(s.activeRoutes);return{matches:t,pendingActionResult:[n.id,{type:`error`,error:e.error}]}}let t=Sn(e.partialMatches).route.id;return{matches:e.partialMatches,pendingActionResult:[t,{type:`error`,error:e.error}]}}if(e.matches)l=e.matches;else{let{notFoundMatches:e,error:t,route:r}=pt(n.pathname);return{matches:e,pendingActionResult:[r.id,{type:`error`,error:t}]}}}let h,g=Vn(l,n);if(!g.route.action&&!g.route.lazy)h={type:`error`,error:wn(405,{method:t.method,pathname:n.pathname,routeId:g.route.id})};else{let e=await Ke(t,n,on(a,o,t,n,l,g,p?[]:r,d),d,null);if(h=e[g.route.id],!h){for(let t of l)if(e[t.route.id]){h=e[t.route.id];break}}if(t.signal.aborted)return{shortCircuited:!0}}if(Nn(h)){let n;return n=m&&m.replace!=null?m.replace:mn(h.response.headers.get(`Location`),new URL(t.url),c,e.history)===E.location.pathname+E.location.search,await Ge(t,h,!0,{submission:i,replace:n}),{shortCircuited:!0}}if(Mn(h)){let e=Sn(l,g.route.id);return(m&&m.replace)!==!0&&(D=`PUSH`),{matches:l,pendingActionResult:[e.route.id,h,g.route.id]}}return{matches:l,pendingActionResult:[g.route.id,h]}}async function ze(t,n,i,l,u,d,f,p,m,h,g,_,v,y){let b=f||Wn(n,i,l,p),x=p||m||Un(b),S=!fe&&!g;if(d){if(S){let e=Be(v);je({navigation:b,...e===void 0?{}:{actionData:e}},{flushSync:_})}let e=await yt(i,n.pathname,t.signal);if(e.type===`aborted`)return{shortCircuited:!0};if(e.type===`error`){if(e.partialMatches.length===0){let{matches:t,route:n}=Cn(s.activeRoutes);return{matches:t,loaderData:{},errors:{[n.id]:e.error}}}let t=Sn(e.partialMatches).route.id;return{matches:e.partialMatches,loaderData:{},errors:{[t]:e.error}}}if(e.matches)i=e.matches;else{let{error:e,notFoundMatches:t,route:r}=pt(n.pathname);return{matches:t,loaderData:{},errors:{[r.id]:e}}}}let C=s.activeRoutes,{dsMatches:w,revalidatingFetchers:T}=Bt(t,u,a,o,e.history,E,i,x,n,g?[]:r,g===!0,pe,ge,we,Se,xe,C,c,e.patchRoutesOnNavigation!=null,s.branches,v,y);if(ye=++ve,!e.dataStrategy&&!w.some(e=>e.shouldLoad)&&!w.some(e=>e.route.middleware&&e.route.middleware.length>0)&&T.length===0){let e=new Map(E.fetchers),t=it(e);return Me(n,{matches:i,loaderData:{},errors:v&&Mn(v[1])?{[v[0]]:v[1].error}:null,...xn(v),...t?{fetchers:e}:{}},{flushSync:_}),{shortCircuited:!0}}if(S){let e={};if(!d){e.navigation=b;let t=Be(v);t!==void 0&&(e.actionData=t)}T.length>0&&(e.fetchers=Ve(T)),je(e,{flushSync:_})}T.forEach(e=>{nt(e.key),e.controller&&_e.set(e.key,e.controller)});let ee=()=>T.forEach(e=>nt(e.key));O&&O.signal.addEventListener(`abort`,ee);let{loaderResults:te,fetcherResults:ne}=await qe(w,T,t,n,u);if(t.signal.aborted)return{shortCircuited:!0};O&&O.signal.removeEventListener(`abort`,ee),T.forEach(e=>_e.delete(e.key));let re=Tn(te);if(re)return await Ge(t,re.result,!0,{replace:h}),{shortCircuited:!0};if(re=Tn(ne),re)return xe.add(re.key),await Ge(t,re.result,!0,{replace:h}),{shortCircuited:!0};let ie=new Map(E.fetchers),{loaderData:D,errors:ae}=yn(E,i,te,v,T,ne,ie);g&&E.errors&&(ae={...E.errors,...ae});let oe=it(ie),se=at(ye,ie),ce=oe||se||T.length>0;return{matches:i,loaderData:D,errors:ae,...ce?{workingFetchers:ie}:{}}}function Be(e){if(e&&!Mn(e[1]))return{[e[0]]:e[1].data};if(E.actionData)return Object.keys(E.actionData).length===0?null:E.actionData}function Ve(e){let t=new Map(E.fetchers);return e.forEach(e=>{let n=t.get(e.key),r=Kn(void 0,n?n.data:void 0);t.set(e.key,r)}),t}async function He(t,n,r,i){nt(t);let a=(i&&i.flushSync)===!0,o=dt(ee),l=s.activeRoutes,u=Rt(E.location,E.matches,c,r,n,i?.relative),d=me(l,u,c,!1,s.branches),f=vt(d,l,u);if(f.active&&f.matches&&(d=f.matches),o&&o(Hn(e.history,u,d)),!d){Xe(t,n,wn(404,{pathname:u}),{flushSync:a});return}let{path:p,submission:m,error:h}=zt(!0,u,i);if(h){Xe(t,n,h,{flushSync:a});return}let g=e.getContext?await e.getContext():new ae,_=(i&&i.preventScrollReset)===!0;if(m&&zn(m.formMethod)){await Ue(t,n,p,d,g,f.active,a,_,m,i&&i.defaultShouldRevalidate);return}Se.set(t,{routeId:n,path:p}),await We(t,n,p,d,g,f.active,a,_,m)}async function Ue(t,n,i,l,u,d,f,p,m,h){Je(),Se.delete(t),Ye(t,qn(m,E.fetchers.get(t)),{flushSync:f});let g=new AbortController,_=hn(e.history,i,g.signal,m);if(d){let e=await yt(l,new URL(_.url).pathname,_.signal,t);if(e.type===`aborted`)return;if(e.type===`error`){Xe(t,n,e.error,{flushSync:f});return}if(e.matches)l=e.matches;else{Xe(t,n,wn(404,{pathname:i}),{flushSync:f});return}}let v=Vn(l,i);if(!v.route.action&&!v.route.lazy){Xe(t,n,wn(405,{method:m.formMethod,pathname:i,routeId:n}),{flushSync:f});return}_e.set(t,g);let y=ve,b=on(a,o,_,i,l,v,r,u),x=await Ke(_,i,b,u,t),S=x[v.route.id];if(!S){for(let e of b)if(x[e.route.id]){S=x[e.route.id];break}}if(_.signal.aborted){_e.get(t)===g&&_e.delete(t);return}if(we.has(t)){if(Nn(S)||Mn(S)){Ye(t,Jn(void 0));return}}else{if(Nn(S)){if(_e.delete(t),ye>y){Ye(t,Jn(void 0));return}return xe.add(t),Ye(t,Kn(m)),Ge(_,S,!1,{fetcherSubmission:m,preventScrollReset:p})}if(Mn(S)){Xe(t,n,S.error);return}}let w=E.navigation.location||E.location,T=hn(e.history,w,g.signal),ee=s.activeRoutes,te=E.navigation.state===`idle`?E.matches:me(ee,E.navigation.location,c,!1,s.branches);C(te,`Didn't find any matches after fetcher action`);let ne=++ve;be.set(t,ne);let{dsMatches:re,revalidatingFetchers:ie}=Bt(T,u,a,o,e.history,E,te,m,w,r,!1,pe,ge,we,Se,xe,ee,c,e.patchRoutesOnNavigation!=null,s.branches,[v.route.id,S],h),ae=Kn(m,S.data),oe=new Map(E.fetchers);oe.set(t,ae),ie.filter(e=>e.key!==t).forEach(e=>{let t=e.key,n=oe.get(t),r=Kn(void 0,n?n.data:void 0);oe.set(t,r),nt(t),e.controller&&_e.set(t,e.controller)}),je({fetchers:oe});let se=()=>ie.forEach(e=>nt(e.key));g.signal.addEventListener(`abort`,se);let{loaderResults:ce,fetcherResults:le}=await qe(re,ie,T,w,u);if(g.signal.aborted){be.get(t)===ne&&be.delete(t);return}g.signal.removeEventListener(`abort`,se),be.delete(t),_e.delete(t),ie.forEach(e=>_e.delete(e.key));let ue=E.fetchers.has(t),de=e=>{if(!ue)return e;let n=new Map(e.fetchers);return n.set(t,Jn(S.data)),{...e,fetchers:n}},fe=Tn(ce);if(fe)return E=de(E),Ge(T,fe.result,!1,{preventScrollReset:p});if(fe=Tn(le),fe)return xe.add(fe.key),E=de(E),Ge(T,fe.result,!1,{preventScrollReset:p});let he=new Map(E.fetchers);ue&&he.set(t,Jn(S.data));let{loaderData:Ce,errors:Te}=yn(E,te,ce,void 0,ie,le,he);at(ne,he),E.navigation.state===`loading`&&ne>ye?(C(D,`Expected pending action`),O&&O.abort(),Me(E.navigation.location,{matches:te,loaderData:Ce,errors:Te,fetchers:he})):(je({errors:Te,loaderData:bn(E.loaderData,Ce,te,Te),fetchers:he}),pe=!1)}async function We(t,n,i,s,c,l,u,d,f){let p=E.fetchers.get(t);Ye(t,Kn(f,p?p.data:void 0),{flushSync:u});let m=new AbortController,h=hn(e.history,i,m.signal);if(l){let e=await yt(s,new URL(h.url).pathname,h.signal,t);if(e.type===`aborted`)return;if(e.type===`error`){Xe(t,n,e.error,{flushSync:u});return}if(e.matches)s=e.matches;else{Xe(t,n,wn(404,{pathname:i}),{flushSync:u});return}}let g=Vn(s,i);_e.set(t,m);let _=ve,v=await Ke(h,i,on(a,o,h,i,s,g,r,c),c,t),y=v[g.route.id];if(!y){for(let e of s)if(v[e.route.id]){y=v[e.route.id];break}}if(_e.get(t)===m&&_e.delete(t),!h.signal.aborted){if(we.has(t)){Ye(t,Jn(void 0));return}if(Nn(y)){if(ye>_){Ye(t,Jn(void 0));return}xe.add(t),await Ge(h,y,!1,{preventScrollReset:d});return}if(Mn(y)){Xe(t,n,y.error);return}Ye(t,Jn(y.data))}}async function Ge(r,i,a,{submission:o,fetcherSubmission:s,preventScrollReset:l,replace:u}={}){a||(oe?.resolve(),oe=null),i.response.headers.has(`X-Remix-Revalidate`)&&(pe=!0);let d=i.response.headers.get(`Location`);C(d,`Expected a Location header on the redirect Response`);let f=d,p=new URL(r.url);d=mn(d,p,c,e.history),Ct(f,d,p,`allow-explicit`);let m=te(E.location,d,{_isRedirect:!0});if(n){let e=!1;if(i.response.headers.has(`X-Remix-Reload-Document`))e=!0;else if(Re(d)){let n=ie(t,d,!0);e=n.origin!==t.location.origin||Ie(n.pathname,c)==null}if(e){u?t.location.replace(d):t.location.assign(d);return}}O=null;let h=u===!0||i.response.headers.has(`X-Remix-Replace`)?`REPLACE`:`PUSH`,{formMethod:g,formAction:_,formEncType:v}=E.navigation;!o&&!s&&g&&_&&v&&(o=Un(E.navigation));let y=o||s;kt.has(i.response.status)&&y&&zn(y.formMethod)?await Fe(h,m,{submission:{...y,formAction:d},preventScrollReset:l||se,enableViewTransition:a?ce:void 0}):await Fe(h,m,{overrideNavigation:Wn(m,[],h,o),fetcherSubmission:s,preventScrollReset:l||se,enableViewTransition:a?ce:void 0})}async function Ke(e,t,n,r,i){let a,o={};try{a=await sn(l,e,t,n,i,r,!1)}catch(e){return n.filter(e=>e.shouldLoad).forEach(t=>{o[t.route.id]={type:`error`,error:e}}),o}if(e.signal.aborted)return o;if(!zn(e.method))for(let e of n){if(a[e.route.id]?.type===`error`)break;!a.hasOwnProperty(e.route.id)&&!E.loaderData.hasOwnProperty(e.route.id)&&(!E.errors||!E.errors.hasOwnProperty(e.route.id))&&e.shouldCallHandler()&&(a[e.route.id]={type:`error`,result:Error(`No result returned from dataStrategy for route ${e.route.id}`)})}for(let[t,r]of Object.entries(a))if(jn(r)){let i=r.result;o[t]={type:`redirect`,response:dn(i,e,t,n,c)}}else o[t]=await un(r);return o}async function qe(e,t,n,r,i){let a=Ke(n,r,e,i,null),o=Promise.all(t.map(async e=>{if(e.matches&&e.match&&e.request&&e.controller){let t=(await Ke(e.request,e.path,e.matches,i,e.key))[e.match.route.id];return{[e.key]:t}}return Promise.resolve({[e.key]:{type:`error`,error:wn(404,{pathname:e.path})}})}));return{loaderResults:await a,fetcherResults:(await o).reduce((e,t)=>Object.assign(e,t),{})}}function Je(){pe=!0,Se.forEach((e,t)=>{_e.has(t)&&ge.add(t),nt(t)})}function Ye(e,t,n={}){let r=new Map(E.fetchers);r.set(e,t),je({fetchers:r},{flushSync:(n&&n.flushSync)===!0})}function Xe(e,t,n,r={}){let i=Sn(E.matches,t),a=new Map(E.fetchers);et(a,e),je({errors:{[i.route.id]:n},fetchers:a},{flushSync:(r&&r.flushSync)===!0})}function Ze(e){return Ce.set(e,(Ce.get(e)||0)+1),we.has(e)&&we.delete(e),E.fetchers.get(e)||jt}function Qe(e,t){nt(e,t?.reason),Ye(e,Jn(null))}function et(e,t){let n=E.fetchers.get(t);_e.has(t)&&!(n&&n.state===`loading`&&be.has(t))&&nt(t),Se.delete(t),be.delete(t),xe.delete(t),we.delete(t),ge.delete(t),e.delete(t)}function tt(e){let t=(Ce.get(e)||0)-1;t<=0?(Ce.delete(e),we.add(e)):Ce.set(e,t),je({fetchers:new Map(E.fetchers)})}function nt(e,t){let n=_e.get(e);n&&(n.abort(t),_e.delete(e))}function rt(e,t){for(let n of e){let e=t.get(n);C(e,`Expected fetcher: ${n}`);let r=Jn(e.data);t.set(n,r)}}function it(e){let t=[],n=!1;for(let r of xe){let i=e.get(r);C(i,`Expected fetcher: ${r}`),i.state===`loading`&&(xe.delete(r),t.push(r),n=!0)}return rt(t,e),n}function at(e,t){let n=[];for(let[r,i]of be)if(i<e){let e=t.get(r);C(e,`Expected fetcher: ${r}`),e.state===`loading`&&(nt(r),be.delete(r),n.push(r))}return rt(n,t),n.length>0}function ct(e,t){let n=E.blockers.get(e)||Mt;return Te.get(e)!==t&&Te.set(e,t),n}function lt(e){E.blockers.delete(e),Te.delete(e)}function ut(e,t){let n=E.blockers.get(e)||Mt;C(n.state===`unblocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`blocked`||n.state===`blocked`&&t.state===`proceeding`||n.state===`blocked`&&t.state===`unblocked`||n.state===`proceeding`&&t.state===`unblocked`,`Invalid blocker state transition: ${n.state} -> ${t.state}`);let r=new Map(E.blockers);r.set(e,t),je({blockers:r})}function ft({currentLocation:e,nextLocation:t,historyAction:n}){if(Te.size===0)return;Te.size>1&&w(!1,`A router only supports one blocker at a time`);let r=Array.from(Te.entries()),[i,a]=r[r.length-1],o=E.blockers.get(i);if(!(o&&o.state===`proceeding`)&&a({currentLocation:e,nextLocation:t,historyAction:n}))return i}function pt(e){let t=wn(404,{pathname:e}),n=s.activeRoutes,{matches:r,route:i}=Cn(n);return{notFoundMatches:r,route:i,error:t}}function mt(e,t,n){if(m=e,g=t,h=n||null,!_&&E.navigation===At){_=!0;let e=_t(E.location,E.matches);e!=null&&je({restoreScrollPosition:e})}return()=>{m=null,g=null,h=null}}function ht(e,t){return h&&h(e,t.map(e=>he(e,E.loaderData)))||e.key}function gt(e,t){if(m&&g){let n=ht(e,t);m[n]=g()}}function _t(e,t){if(m){let n=ht(e,t),r=m[n];if(typeof r==`number`)return r}return null}function vt(t,n,r){if(e.patchRoutesOnNavigation){let e=s.branches;if(!t)return{active:!0,matches:me(n,r,c,!0,e)||[]};if(Object.keys(t[0].params).length>0)return{active:!0,matches:me(n,r,c,!0,e)}}return{active:!1,matches:null}}async function yt(t,n,r,i){if(!e.patchRoutesOnNavigation)return{type:`success`,matches:t};let l=t;for(;;){let t=o;try{await e.patchRoutesOnNavigation({signal:r,path:n,matches:l,fetcherKey:i,patch:(e,n)=>{r.aborted||Kt(e,n,s,t,a,!1)}})}catch(e){return{type:`error`,error:e,partialMatches:l}}if(r.aborted)return{type:`aborted`};let u=s.branches,d=me(s.activeRoutes,n,c,!1,u),f=null;if(d&&(Object.keys(d[0].params).length===0||(f=me(s.activeRoutes,n,c,!0,u),!(f&&l.length<f.length&&bt(l,f.slice(0,l.length))))))return{type:`success`,matches:d};if(f||=me(s.activeRoutes,n,c,!0,u),!f||bt(l,f))return{type:`success`,matches:null};l=f}}function bt(e,t){return e.length===t.length&&e.every((e,n)=>e.route.id===t[n].route.id)}function xt(e){o={},s.setHmrRoutes(de(e,a,void 0,o))}function St(e,t,n=!1){Kt(e,t,s,o,a,n),s.hasHMRRoutes||je({})}return ee={get basename(){return c},get future(){return u},get state(){return E},get routes(){return s.stableRoutes},get branches(){return s.branches},get manifest(){return o},get window(){return t},initialize:Oe,subscribe:Ae,enableScrollRestoration:mt,navigate:Ne,fetch:He,revalidate:Pe,createHref:t=>e.history.createHref(t),createURL:t=>e.history.createURL(t),encodeLocation:t=>e.history.encodeLocation(t),getFetcher:Ze,resetFetcher:Qe,deleteFetcher:tt,dispose:ke,getBlocker:ct,deleteBlocker:lt,patchRoutes:St,_internalFetchControllers:_e,_internalSetRoutes:xt,_internalSetStateDoNotUseOrYouWillBreakYourApp(e){je(e)}},e.instrumentations&&(ee=st(ee,e.instrumentations.map(e=>e.router).filter(Boolean))),ee}function Lt(e){return e!=null&&(`formData`in e&&e.formData!=null||`body`in e&&e.body!==void 0)}function Rt(e,t,n,r,i,a){let o,s;if(i){o=[];for(let e of t)if(o.push(e),e.route.id===i){s=e;break}}else o=t,s=t[t.length-1];let c=We(r||`.`,Ue(o),Ie(e.pathname,n)||e.pathname,a===`path`);if(r??(c.search=e.search,c.hash=e.hash),(r==null||r===``||r===`.`)&&s){let e=Bn(c.search);if(s.route.index&&!e)c.search=c.search?c.search.replace(/^\?/,`?index&`):`?index`;else if(!s.route.index&&e){let e=new URLSearchParams(c.search),t=e.getAll(`index`);e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();c.search=n?`?${n}`:``}}return n!==`/`&&(c.pathname=Le({basename:n,pathname:c.pathname})),ne(c)}function zt(e,t,n){if(!n||!Lt(n))return{path:t};if(n.formMethod&&!Rn(n.formMethod))return{path:t,error:wn(405,{method:n.formMethod})};let r=()=>({path:t,error:wn(400,{type:`invalid-body`})}),i=(n.formMethod||`get`).toUpperCase(),a=En(t);if(n.body!==void 0){if(n.formEncType===`text/plain`){if(!zn(i))return r();let e=typeof n.body==`string`?n.body:n.body instanceof FormData||n.body instanceof URLSearchParams?Array.from(n.body.entries()).reduce((e,[t,n])=>`${e}${t}=${n}\n`,``):String(n.body);return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:void 0,text:e}}}if(n.formEncType===`application/json`){if(!zn(i))return r();try{let e=typeof n.body==`string`?JSON.parse(n.body):n.body;return{path:t,submission:{formMethod:i,formAction:a,formEncType:n.formEncType,formData:void 0,json:e,text:void 0}}}catch{return r()}}}C(typeof FormData==`function`,`FormData is not available in this environment`);let o,s;if(n.formData)o=gn(n.formData),s=n.formData;else if(n.body instanceof FormData)o=gn(n.body),s=n.body;else if(n.body instanceof URLSearchParams)o=n.body,s=_n(o);else if(n.body==null)o=new URLSearchParams,s=new FormData;else try{o=new URLSearchParams(n.body),s=_n(o)}catch{return r()}let c={formMethod:i,formAction:a,formEncType:n&&n.formEncType||`application/x-www-form-urlencoded`,formData:s,json:void 0,text:void 0};if(zn(c.formMethod))return{path:t,submission:c};let l=re(t);return e&&l.search&&Bn(l.search)&&o.append(`index`,``),l.search=`?${o}`,{path:ne(l),submission:c}}function Bt(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_,v,y,b,x){let S=b?Mn(b[1])?b[1].error:b[1].data:void 0,C=i.createURL(a.location),w=i.createURL(c),T;if(u&&a.errors){let e=Object.keys(a.errors)[0];T=o.findIndex(t=>t.route.id===e)}else if(b&&Mn(b[1])){let e=b[0];T=o.findIndex(t=>t.route.id===e)-1}let ee=b?b[1].statusCode:void 0,te=ee&&ee>=400,ne={currentUrl:C,currentParams:a.matches[0]?.params||{},nextUrl:w,nextParams:o[0].params,...s,actionResult:S,actionStatus:ee},re=et(o),E=o.map((i,o)=>{let{route:s}=i,f=null;if(T!=null&&o>T)f=!1;else if(s.lazy)f=!0;else if(!Vt(s))f=!1;else if(u){let{shouldLoad:e}=Ht(s,a.loaderData,a.errors);f=e}else Ut(a.loaderData,a.matches[o],i)&&(f=!0);if(f!==null)return an(n,r,e,c,re,i,l,t,f);let p=!1;typeof x==`boolean`?p=x:te?p=!1:d||C.pathname+C.search===w.pathname+w.search?p=!0:C.search===w.search?Wt(a.matches[o],i)&&(p=!0):p=!0;let m={...ne,defaultShouldRevalidate:p};return an(n,r,e,c,re,i,l,t,Gt(i,m),m,x)}),ie=[];return m.forEach((e,s)=>{if(u||!o.some(t=>t.route.id===e.routeId)||p.has(s))return;let c=a.fetchers.get(s),m=c&&c.state!==`idle`&&c.data===void 0,b=me(g,e.path,_??`/`,!1,y);if(!b){if(v&&m)return;ie.push({key:s,routeId:e.routeId,path:e.path,matches:null,match:null,request:null,controller:null});return}if(h.has(s))return;let S=Vn(b,e.path),C=new AbortController,w=hn(i,e.path,C.signal),T=null;if(f.has(s))f.delete(s),T=on(n,r,w,e.path,b,S,l,t);else if(m)d&&(T=on(n,r,w,e.path,b,S,l,t));else{let i;i=typeof x==`boolean`?x:!te&&d;let a={...ne,defaultShouldRevalidate:i};Gt(S,a)&&(T=on(n,r,w,e.path,b,S,l,t,a))}T&&ie.push({key:s,routeId:e.routeId,path:e.path,matches:T,match:S,request:w,controller:C})}),{dsMatches:E,revalidatingFetchers:ie}}function Vt(e){return e.loader!=null||e.middleware!=null&&e.middleware.length>0}function Ht(e,t,n){if(e.lazy)return{shouldLoad:!0,renderFallback:!0};if(!Vt(e))return{shouldLoad:!1,renderFallback:!1};let r=t!=null&&e.id in t,i=n!=null&&n[e.id]!==void 0;if(!r&&i)return{shouldLoad:!1,renderFallback:!1};if(typeof e.loader==`function`&&e.loader.hydrate===!0)return{shouldLoad:!0,renderFallback:!r};let a=!r&&!i;return{shouldLoad:a,renderFallback:a}}function Ut(e,t,n){let r=!t||n.route.id!==t.route.id,i=!e.hasOwnProperty(n.route.id);return r||i}function Wt(e,t){let n=e.route.path;return e.pathname!==t.pathname||n!=null&&n.endsWith(`*`)&&e.params[`*`]!==t.params[`*`]}function Gt(e,t){if(e.route.shouldRevalidate){let n=e.route.shouldRevalidate(t);if(typeof n==`boolean`)return n}return t.defaultShouldRevalidate}function Kt(e,t,n,r,i,a){let o;if(e){let t=r[e];C(t,`No route found to patch children into: routeId = ${e}`),t.children||=[],o=t.children}else o=n.activeRoutes;let s=[],c=[];if(t.forEach(e=>{let t=o.find(t=>qt(e,t));t?c.push({existingRoute:t,newRoute:e}):s.push(e)}),s.length>0){let t=de(s,i,[e||`_`,`patch`,String(o?.length||`0`)],r);o.push(...t)}if(a&&c.length>0)for(let e=0;e<c.length;e++){let{existingRoute:t,newRoute:n}=c[e],r=t,[a]=de([n],i,[],{},!0);Object.assign(r,{element:a.element?a.element:r.element,errorElement:a.errorElement?a.errorElement:r.errorElement,hydrateFallbackElement:a.hydrateFallbackElement?a.hydrateFallbackElement:r.hydrateFallbackElement})}n.hasHMRRoutes||n.setRoutes([...n.activeRoutes])}function qt(e,t){return`id`in e&&`id`in t&&e.id===t.id?!0:e.index!==t.index||e.path!==t.path||e.caseSensitive!==t.caseSensitive?!1:(!e.children||e.children.length===0)&&(!t.children||t.children.length===0)?!0:e.children?.every((e,n)=>t.children?.some(t=>qt(e,t)))??!1}var Jt=new WeakMap,Yt=({key:e,route:t,manifest:n,mapRouteProperties:r})=>{let i=n[t.id];if(C(i,`No route found in manifest`),!i.lazy||typeof i.lazy!=`object`)return;let a=i.lazy[e];if(!a)return;let o=Jt.get(i);o||(o={},Jt.set(i,o));let s=o[e];if(s)return s;let c=(async()=>{let t=se(e),n=i[e]!==void 0;if(t)w(!t,`Route property `+e+` is not a supported lazy route property. This property will be ignored.`),o[e]=Promise.resolve();else if(n)w(!1,`Route "${i.id}" has a static property "${e}" defined. The lazy property will be ignored.`);else{let t=await a();t!=null&&(Object.assign(i,{[e]:t}),Object.assign(i,r(i)))}typeof i.lazy==`object`&&(i.lazy[e]=void 0,Object.values(i.lazy).every(e=>e===void 0)&&(i.lazy=void 0))})();return o[e]=c,c},Xt=new WeakMap;function Zt(e,t,n,r,i){let a=n[e.id];if(C(a,`No route found in manifest`),!e.lazy)return{lazyRoutePromise:void 0,lazyHandlerPromise:void 0};if(typeof e.lazy==`function`){let t=Xt.get(a);if(t)return{lazyRoutePromise:t,lazyHandlerPromise:t};let n=(async()=>{C(typeof e.lazy==`function`,`No lazy route function found`);let t=await e.lazy(),n={};for(let e in t){let r=t[e];if(r===void 0)continue;let i=ce(e),o=a[e]!==void 0;i?w(!i,`Route property `+e+` is not a supported property to be returned from a lazy route function. This property will be ignored.`):o?w(!o,`Route "${a.id}" has a static property "${e}" defined but its lazy function is also returning a value for this property. The lazy route property "${e}" will be ignored.`):n[e]=r}Object.assign(a,n),Object.assign(a,{...r(a),lazy:void 0})})();return Xt.set(a,n),n.catch(()=>{}),{lazyRoutePromise:n,lazyHandlerPromise:n}}let o=Object.keys(e.lazy),s=[],c;for(let a of o){if(i&&i.includes(a))continue;let o=Yt({key:a,route:e,manifest:n,mapRouteProperties:r});o&&(s.push(o),a===t&&(c=o))}let l=s.length>0?Promise.all(s).then(()=>{}):void 0;return l?.catch(()=>{}),c?.catch(()=>{}),{lazyRoutePromise:l,lazyHandlerPromise:c}}async function Qt(e){let t=e.matches.filter(e=>e.shouldLoad),n={};return(await Promise.all(t.map(e=>e.resolve()))).forEach((e,r)=>{n[t[r].route.id]=e}),n}async function $t(e){return e.matches.some(e=>e.route.middleware)?en(e,()=>Qt(e)):Qt(e)}function en(e,t){return tn(e,t,e=>{if(Ln(e))throw e;return e},kn,n);async function n(t,n,r){if(r)return Object.assign(r.value,{[n]:{type:`error`,result:t}});{let{matches:r}=e,i=Math.min(Math.max(r.findIndex(e=>e.route.id===n),0),Math.max(r.findIndex(e=>e.shouldCallHandler()),0)),a=r[i].route.id;for(let e of r.slice(0,i+1))try{await e._lazyPromises?.route}catch{a=e.route.id;break}return{[Sn(r,a).route.id]:{type:`error`,result:t}}}}}async function tn(e,t,n,r,i){let{matches:a,...o}=e;return await nn(o,a.flatMap(e=>e.route.middleware?e.route.middleware.map(t=>[e.route.id,t]):[]),t,n,r,i)}async function nn(e,t,n,r,i,a,o=0){let{request:s}=e;if(s.signal.aborted)throw s.signal.reason??Error(`Request aborted: ${s.method} ${s.url}`);let c=t[o];if(!c)return await n();let[l,u]=c,d,f=async()=>{if(d)throw Error("You may only call `next()` once per middleware");try{return d={value:await nn(e,t,n,r,i,a,o+1)},d.value}catch(e){return d={value:await a(e,l,d)},d.value}};try{let t=await u(e,f),n=t==null?void 0:r(t);return i(n)?n:d?n??d.value:(d={value:await f()},d.value)}catch(e){return await a(e,l,d)}}function rn(e,t,n,r,i){let a=Yt({key:`middleware`,route:r.route,manifest:t,mapRouteProperties:e}),o=Zt(r.route,zn(n.method)?`action`:`loader`,t,e,i);return{middleware:a,route:o.lazyRoutePromise,handler:o.lazyHandlerPromise}}function an(e,t,n,r,i,a,o,s,c,l=null,u){let d=!1,f=rn(e,t,n,a,o);return{...a,_lazyPromises:f,shouldLoad:c,shouldRevalidateArgs:l,shouldCallHandler(e){return d=!0,l?typeof u==`boolean`?Gt(a,{...l,defaultShouldRevalidate:u}):typeof e==`boolean`?Gt(a,{...l,defaultShouldRevalidate:e}):Gt(a,l):c},resolve(e){let{lazy:t,loader:o,middleware:l}=a.route,u=d||c||e&&!zn(n.method)&&(t||o),p=l&&l.length>0&&!o&&!t;return u&&(zn(n.method)||!p)?cn({request:n,path:r,pattern:i,match:a,lazyHandlerPromise:f?.handler,lazyRoutePromise:f?.route,handlerOverride:e,scopedContext:s}):Promise.resolve({type:`data`,result:void 0})}}}function on(e,t,n,r,i,a,o,s,c=null){return i.map(l=>l.route.id===a.route.id?an(e,t,n,r,et(i),l,o,s,!0,c):{...l,shouldLoad:!1,shouldRevalidateArgs:c,shouldCallHandler:()=>!1,_lazyPromises:rn(e,t,n,l,o),resolve:()=>Promise.resolve({type:`data`,result:void 0})})}async function sn(e,t,n,r,i,a,o){r.some(e=>e._lazyPromises?.middleware)&&await Promise.all(r.map(e=>e._lazyPromises?.middleware));let s={request:t,url:tt(t,n),pattern:et(r),params:r[0].params,context:a,matches:r},c=o?()=>{throw Error("You cannot call `runClientMiddleware()` from a static handler `dataStrategy`. Middleware is run outside of `dataStrategy` during SSR in order to bubble up the Response. You can enable middleware via the `respond` API in `query`/`queryRoute`")}:e=>{let t=s;return en(t,()=>e({...t,fetcherKey:i,runClientMiddleware:()=>{throw Error("Cannot call `runClientMiddleware()` from within an `runClientMiddleware` handler")}}))},l=await e({...s,fetcherKey:i,runClientMiddleware:c});try{await Promise.all(r.flatMap(e=>[e._lazyPromises?.handler,e._lazyPromises?.route]))}catch{}return l}async function cn({request:e,path:t,pattern:n,match:r,lazyHandlerPromise:i,lazyRoutePromise:a,handlerOverride:o,scopedContext:s}){let c,l,u=zn(e.method),d=u?`action`:`loader`,f=i=>{let a,c=new Promise((e,t)=>a=t);l=()=>a(),e.signal.addEventListener(`abort`,l);let u=a=>typeof i==`function`?i({request:e,url:tt(e,t),pattern:n,params:r.params,context:s},...a===void 0?[]:[a]):Promise.reject(Error(`You cannot call the handler for a route which defines a boolean "${d}" [routeId: ${r.route.id}]`)),f=(async()=>{try{return{type:`data`,result:await(o?o(e=>u(e)):u())}}catch(e){return{type:`error`,result:e}}})();return Promise.race([f,c])};try{let t=u?r.route.action:r.route.loader;if(i||a){if(t){let e,[n]=await Promise.all([f(t).catch(t=>{e=t}),i,a]);if(e!==void 0)throw e;c=n}else{await i;let t=u?r.route.action:r.route.loader;if(t)[c]=await Promise.all([f(t),a]);else if(d===`action`){let t=new URL(e.url),n=t.pathname+t.search;throw wn(405,{method:e.method,pathname:n,routeId:r.route.id})}else return{type:`data`,result:void 0}}}else if(t)c=await f(t);else{let t=new URL(e.url);throw wn(404,{pathname:t.pathname+t.search})}}catch(e){return{type:`error`,result:e}}finally{l&&e.signal.removeEventListener(`abort`,l)}return c}async function ln(e){let t=e.headers.get(`Content-Type`);return t&&/\bapplication\/json\b/.test(t)?e.body==null?null:e.json():e.text()}async function un(e){let{result:t,type:n}=e;if(Fn(t)){let e;try{e=await ln(t)}catch(e){return{type:`error`,error:e}}return n===`error`?{type:`error`,error:new Qe(t.status,t.statusText,e),statusCode:t.status,headers:t.headers}:{type:`data`,data:e,statusCode:t.status,headers:t.headers}}return n===`error`?Pn(t)?t.data instanceof Error?{type:`error`,error:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:On(t),statusCode:$e(t)?t.status:void 0,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`error`,error:t,statusCode:$e(t)?t.status:void 0}:Pn(t)?{type:`data`,data:t.data,statusCode:t.init?.status,headers:t.init?.headers?new Headers(t.init.headers):void 0}:{type:`data`,data:t}}function dn(e,t,n,r,i){let a=e.headers.get(`Location`);if(C(a,`Redirects returned/thrown from loaders/actions must have a Location header`),!Re(a)){let o=r.slice(0,r.findIndex(e=>e.route.id===n)+1);a=Rt(new URL(t.url),o,i,a),e.headers.set(`Location`,a)}return e}var fn=[`about:`,`blob:`,`chrome:`,`chrome-untrusted:`,`content:`,`data:`,`devtools:`,`file:`,`filesystem:`,`javascript:`];function pn(e){try{return fn.includes(new URL(e).protocol)}catch{return!1}}function mn(e,t,n,r){if(Re(e)){let r=e,i=v.test(r)?new URL(y(r,t.protocol)):new URL(r);if(pn(i.toString()))throw Error(`Invalid redirect location`);let a=Ie(i.pathname,n)!=null;if(i.origin===t.origin&&a)return Ge(i.pathname)+i.search+i.hash}try{if(pn(r.createURL(e).toString()))throw Error(`Invalid redirect location`)}catch{}return e}function hn(e,t,n,r){let i=e.createURL(En(t)).toString(),a={signal:n};if(r&&zn(r.formMethod)){let{formMethod:e,formEncType:t}=r;a.method=e.toUpperCase(),t===`application/json`?(a.headers=new Headers({"Content-Type":t}),a.body=JSON.stringify(r.json)):a.body=t===`text/plain`?r.text:t===`application/x-www-form-urlencoded`&&r.formData?gn(r.formData):r.formData}return new Request(i,a)}function gn(e){let t=new URLSearchParams;for(let[n,r]of e.entries())t.append(n,typeof r==`string`?r:r.name);return t}function _n(e){let t=new FormData;for(let[n,r]of e.entries())t.append(n,r);return t}function vn(e,t,n,r=!1,i=!1){let a={},o=null,s,c=!1,l={},u=n&&Mn(n[1])?n[1].error:void 0;return e.forEach(n=>{if(!(n.route.id in t))return;let d=n.route.id,f=t[d];if(C(!Nn(f),`Cannot handle redirect results in processLoaderData`),Mn(f)){let t=f.error;if(u!==void 0&&(t=u,u=void 0),o||={},i)o[d]=t;else{let n=Sn(e,d);o[n.route.id]??(o[n.route.id]=t)}r||(a[d]=Pt),c||(c=!0,s=$e(f.error)?f.error.status:500),f.headers&&(l[d]=f.headers)}else a[d]=f.data,f.statusCode&&f.statusCode!==200&&!c&&(s=f.statusCode),f.headers&&(l[d]=f.headers)}),u!==void 0&&n&&(o={[n[0]]:u},n[2]&&(a[n[2]]=void 0)),{loaderData:a,errors:o,statusCode:s||200,loaderHeaders:l}}function yn(e,t,n,r,i,a,o){let{loaderData:s,errors:c}=vn(t,n,r);return i.filter(e=>!e.matches||e.matches.some(e=>e.shouldLoad)).forEach(t=>{let{key:n,match:r,controller:i}=t;if(i&&i.signal.aborted)return;let s=a[n];if(C(s,`Did not find corresponding fetcher result`),Mn(s)){let t=Sn(e.matches,r?.route.id);c&&c[t.route.id]||(c={...c,[t.route.id]:s.error}),o.delete(n)}else if(Nn(s))C(!1,`Unhandled fetcher revalidation redirect`);else{let e=Jn(s.data);o.set(n,e)}}),{loaderData:s,errors:c}}function bn(e,t,n,r){let i=Object.entries(t).filter(([,e])=>e!==Pt).reduce((e,[t,n])=>(e[t]=n,e),{});for(let a of n){let n=a.route.id;if(!t.hasOwnProperty(n)&&e.hasOwnProperty(n)&&a.route.loader&&(i[n]=e[n]),r&&r.hasOwnProperty(n))break}return i}function xn(e){return e?Mn(e[1])?{actionData:{}}:{actionData:{[e[0]]:e[1].data}}:{}}function Sn(e,t){return(t?e.slice(0,e.findIndex(e=>e.route.id===t)+1):[...e]).reverse().find(e=>e.route.ErrorBoundary!=null||e.route.errorElement!=null)||e[0]}function Cn(e){let t=e.length===1?e[0]:e.find(e=>e.index||!e.path||e.path===`/`)||{id:`__shim-error-route__`};return{matches:[{params:{},pathname:``,pathnameBase:``,route:t}],route:t}}function wn(e,{pathname:t,routeId:n,method:r,type:i,message:a}={}){let o=`Unknown Server Error`,s=`Unknown @remix-run/router error`;return e===400?(o=`Bad Request`,r&&t&&n?s=`You made a ${r} request to "${t}" but did not provide a \`loader\` for route "${n}", so there is no way to handle the request.`:i===`invalid-body`&&(s=`Unable to encode submission body`)):e===403?(o=`Forbidden`,s=`Route "${n}" does not match URL "${t}"`):e===404?(o=`Not Found`,s=`No route matches URL "${t}"`):e===405&&(o=`Method Not Allowed`,r&&t&&n?s=`You made a ${r.toUpperCase()} request to "${t}" but did not provide an \`action\` for route "${n}", so there is no way to handle the request.`:r&&(s=`Invalid request method "${r.toUpperCase()}"`)),new Qe(e||500,o,Error(s),!0)}function Tn(e){let t=Object.entries(e);for(let e=t.length-1;e>=0;e--){let[n,r]=t[e];if(Nn(r))return{key:n,result:r}}}function En(e){return ne({...typeof e==`string`?re(e):e,hash:``})}function Dn(e,t){return e.pathname!==t.pathname||e.search!==t.search?!1:e.hash===``?t.hash!==``:e.hash===t.hash||t.hash!==``}function On(e){return new Qe(e.init?.status??500,e.init?.statusText??`Internal Server Error`,e.data)}function kn(e){return typeof e==`object`&&!!e&&Object.entries(e).every(([e,t])=>typeof e==`string`&&An(t))}function An(e){return typeof e==`object`&&!!e&&`type`in e&&`result`in e&&(e.type===`data`||e.type===`error`)}function jn(e){return Fn(e.result)&&Ot.has(e.result.status)}function Mn(e){return e.type===`error`}function Nn(e){return(e&&e.type)===`redirect`}function Pn(e){return typeof e==`object`&&!!e&&`type`in e&&`data`in e&&`init`in e&&e.type===`DataWithResponseInit`}function Fn(e){return e!=null&&typeof e.status==`number`&&typeof e.statusText==`string`&&typeof e.headers==`object`&&e.body!==void 0}function In(e){return Ot.has(e)}function Ln(e){return Fn(e)&&In(e.status)&&e.headers.has(`Location`)}function Rn(e){return Dt.has(e.toUpperCase())}function zn(e){return Tt.has(e.toUpperCase())}function Bn(e){return new URLSearchParams(e).getAll(`index`).some(e=>e===``)}function Vn(e,t){let n=typeof t==`string`?re(t).search:t.search;if(e[e.length-1].route.index&&Bn(n||``))return e[e.length-1];let r=He(e);return r[r.length-1]}function Hn(e,t,n){return{url:tt(e.createURL(t),t),pattern:n?et(n):``,params:n?.[0]?.params?{...n[0].params}:{}}}function Un(e){let{formMethod:t,formAction:n,formEncType:r,text:i,formData:a,json:o}=e;if(t&&n&&r){if(i!=null)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:void 0,text:i};if(a!=null)return{formMethod:t,formAction:n,formEncType:r,formData:a,json:void 0,text:void 0};if(o!==void 0)return{formMethod:t,formAction:n,formEncType:r,formData:void 0,json:o,text:void 0}}}function Wn(e,t,n,r){return r?{state:`loading`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}:{state:`loading`,location:e,matches:t,historyAction:n,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0}}function Gn(e,t,n,r){return{state:`submitting`,location:e,matches:t,historyAction:n,formMethod:r.formMethod,formAction:r.formAction,formEncType:r.formEncType,formData:r.formData,json:r.json,text:r.text}}function Kn(e,t){return e?{state:`loading`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t}:{state:`loading`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:t}}function qn(e,t){return{state:`submitting`,formMethod:e.formMethod,formAction:e.formAction,formEncType:e.formEncType,formData:e.formData,json:e.json,text:e.text,data:t?t.data:void 0}}function Jn(e){return{state:`idle`,formMethod:void 0,formAction:void 0,formEncType:void 0,formData:void 0,json:void 0,text:void 0,data:e}}function Yn(e,t){try{let n=e.sessionStorage.getItem(Nt);if(n){let e=JSON.parse(n);for(let[n,r]of Object.entries(e||{}))r&&Array.isArray(r)&&t.set(n,new Set(r||[]))}}catch{}}function Xn(e,t){if(t.size>0){let n={};for(let[e,r]of t)n[e]=[...r];try{e.sessionStorage.setItem(Nt,JSON.stringify(n))}catch(e){w(!1,`Failed to save applied view transitions in sessionStorage (${e}).`)}}}function Zn(){let e,t,n=new Promise((r,i)=>{e=async e=>{r(e);try{await n}catch{}},t=async e=>{i(e);try{await n}catch{}}});return{promise:n,resolve:e,reject:t}}var Qn=D.createContext(null);Qn.displayName=`DataRouter`;var $n=D.createContext(null);$n.displayName=`DataRouterState`;var er=D.createContext(!1);function tr(){return D.useContext(er)}var nr=D.createContext({isTransitioning:!1});nr.displayName=`ViewTransition`;var rr=D.createContext(new Map);rr.displayName=`Fetchers`;var ir=D.createContext(null);ir.displayName=`Await`;var ar=D.createContext(null);ar.displayName=`Navigation`;var or=D.createContext(null);or.displayName=`Location`;var sr=D.createContext({outlet:null,matches:[],isDataRoute:!1});sr.displayName=`Route`;var cr=D.createContext(null);cr.displayName=`RouteError`;var lr=`REACT_ROUTER_ERROR`,ur=`REDIRECT`,dr=`ROUTE_ERROR_RESPONSE`;function fr(e){if(e.startsWith(`${lr}:${ur}:{`))try{let t=JSON.parse(e.slice(28));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`&&typeof t.location==`string`&&typeof t.reloadDocument==`boolean`&&typeof t.replace==`boolean`)return t}catch{}}function pr(e){if(e.startsWith(`${lr}:${dr}:{`))try{let t=JSON.parse(e.slice(40));if(typeof t==`object`&&t&&typeof t.status==`number`&&typeof t.statusText==`string`)return new Qe(t.status,t.statusText,t.data)}catch{}}function mr(e,{relative:t}={}){C(hr(),`useHref() may be used only in the context of a <Router> component.`);let{basename:n,navigator:r}=D.useContext(ar),{hash:i,pathname:a,search:o}=Cr(e,{relative:t}),s=a;return n!==`/`&&(s=a===`/`?n:Ke([n,a])),r.createHref({pathname:s,search:o,hash:i})}function hr(){return D.useContext(or)!=null}function gr(){return C(hr(),`useLocation() may be used only in the context of a <Router> component.`),D.useContext(or).location}var _r=`You should call navigate() in a React.useEffect(), not when your component is first rendered.`;function vr(){let{isDataRoute:e}=D.useContext(sr);return e?zr():yr()}function yr(){C(hr(),`useNavigate() may be used only in the context of a <Router> component.`);let e=D.useContext(Qn),{basename:t,navigator:n}=D.useContext(ar),{matches:r}=D.useContext(sr),{pathname:i}=gr(),a=JSON.stringify(Ue(r)),o=D.useRef(!1);return D.useLayoutEffect(()=>{o.current=!0}),D.useCallback((r,s={})=>{if(w(o.current,_r),!o.current)return;if(typeof r==`number`){n.go(r);return}let c=We(r,JSON.parse(a),i,s.relative===`path`);e==null&&t!==`/`&&(c.pathname=c.pathname===`/`?t:Ke([t,c.pathname])),Ct(typeof r==`string`?r:ne(r),n.createHref(c),bt(n),`reject`),(s.replace?n.replace:n.push)(c,s.state,s)},[t,n,a,i,e])}var br=D.createContext(null);function xr(e){let t=D.useContext(sr).outlet;return D.useMemo(()=>t&&D.createElement(br.Provider,{value:e},t),[t,e])}function Sr(){let{matches:e}=D.useContext(sr);return e[e.length-1]?.params??{}}function Cr(e,{relative:t}={}){let{matches:n}=D.useContext(sr),{pathname:r}=gr(),i=JSON.stringify(Ue(n));return D.useMemo(()=>We(e,JSON.parse(i),r,t===`path`),[e,i,r,t])}function wr(e,t,n){C(hr(),`useRoutes() may be used only in the context of a <Router> component.`);let{navigator:r}=D.useContext(ar),{matches:i}=D.useContext(sr),a=i[i.length-1],o=a?a.params:{};a&&a.pathname;let s=a?a.pathnameBase:`/`;a&&a.route;let c=gr(),l;if(t){let e=typeof t==`string`?re(t):t;C(s===`/`||e.pathname?.startsWith(s),`When overriding the location using \`<Routes location>\` or \`useRoutes(routes, location)\`, the location pathname must begin with the portion of the URL pathname that was matched by all parent routes. The current pathname base is "${s}" but pathname "${e.pathname}" was given in the \`location\` prop.`),l=e}else l=c;let u=l.pathname||`/`,d=u;if(s!==`/`){let e=s.replace(/^\//,``).split(`/`);d=`/`+u.replace(/^\//,``).split(`/`).slice(e.length).join(`/`)}let f=n&&n.state.matches.length?n.state.matches.map(e=>Object.assign(e,{route:n.manifest[e.route.id]||e.route})):pe(e,{pathname:d}),p=jr(f&&f.map(e=>Object.assign({},e,{params:Object.assign({},o,e.params),pathname:Ke([s,r.encodeLocation?r.encodeLocation(e.pathname.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathname]),pathnameBase:e.pathnameBase===`/`?s:Ke([s,r.encodeLocation?r.encodeLocation(e.pathnameBase.replace(/%/g,`%25`).replace(/\?/g,`%3F`).replace(/#/g,`%23`)).pathname:e.pathnameBase])})),i,n);return t&&p?D.createElement(or.Provider,{value:{location:{pathname:`/`,search:``,hash:``,state:null,key:`default`,mask:void 0,...l},navigationType:`POP`}},p):p}function Tr(){let e=Rr(),t=$e(e)?`${e.status} ${e.statusText}`:e instanceof Error?e.message:JSON.stringify(e),n=e instanceof Error?e.stack:null;return D.createElement(D.Fragment,null,D.createElement(`h2`,null,`Unexpected Application Error!`),D.createElement(`h3`,{style:{fontStyle:`italic`}},t),n?D.createElement(`pre`,{style:{padding:`0.5rem`,backgroundColor:`rgba(200,200,200, 0.5)`}},n):null,null)}var Er=D.createElement(Tr,null),Dr=class extends D.Component{constructor(e){super(e),this.state={location:e.location,revalidation:e.revalidation,error:e.error}}static contextType=er;static getDerivedStateFromError(e){return{error:e}}static getDerivedStateFromProps(e,t){return t.location!==e.location||t.revalidation!==`idle`&&e.revalidation===`idle`?{error:e.error,location:e.location,revalidation:e.revalidation}:{error:e.error===void 0?t.error:e.error,location:t.location,revalidation:e.revalidation||t.revalidation}}componentDidCatch(e,t){this.props.onError?this.props.onError(e,t):console.error(`React Router caught the following error during render`,e)}render(){let e=this.state.error;if(this.context&&typeof e==`object`&&e&&`digest`in e&&typeof e.digest==`string`){let t=pr(e.digest);t&&(e=t)}let t=e===void 0?this.props.children:D.createElement(sr.Provider,{value:this.props.routeContext},D.createElement(cr.Provider,{value:e,children:this.props.component}));return this.context?D.createElement(kr,{error:e},t):t}},Or=new WeakMap;function kr({children:e,error:t}){let{basename:n,navigator:r}=D.useContext(ar);if(typeof t==`object`&&t&&`digest`in t&&typeof t.digest==`string`){let e=fr(t.digest);if(e){let i=Or.get(t);if(i)throw i;let a=rt(e.location,n),o=a.absoluteURL||a.to;if(Ct(e.location,o,bt(r),`allow-explicit`),pn(o))throw Error(`Invalid redirect location`);if(nt&&!Or.get(t)){if(a.isExternal||e.reloadDocument)window.location.href=o;else{let n=Promise.resolve().then(()=>window.__reactRouterDataRouter.navigate(a.to,{replace:e.replace}));throw Or.set(t,n),n}}return D.createElement(`meta`,{httpEquiv:`refresh`,content:`0;url=${o}`})}}return e}function Ar({routeContext:e,match:t,children:n}){let r=D.useContext(Qn);return r&&r.static&&r.staticContext&&(t.route.errorElement||t.route.ErrorBoundary)&&(r.staticContext._deepestRenderedBoundaryId=t.route.id),D.createElement(sr.Provider,{value:e},n)}function jr(e,t=[],n){let r=n?.state;if(e==null){if(!r)return null;if(r.errors)e=r.matches;else if(t.length===0&&!r.initialized&&r.matches.length>0)e=r.matches;else return null}let i=e,a=r?.errors;if(a!=null){let e=i.findIndex(e=>e.route.id&&a?.[e.route.id]!==void 0);C(e>=0,`Could not find a matching route for errors on route IDs: ${Object.keys(a).join(`,`)}`),i=i.slice(0,Math.min(i.length,e+1))}let o=!1,s=-1;if(n&&r){o=r.renderFallback;for(let e=0;e<i.length;e++){let t=i[e];if((t.route.HydrateFallback||t.route.hydrateFallbackElement)&&(s=e),t.route.id){let{loaderData:e,errors:a}=r,c=t.route.loader&&!e.hasOwnProperty(t.route.id)&&(!a||a[t.route.id]===void 0);if(t.route.lazy||c){n.isStatic&&(o=!0),i=s>=0?i.slice(0,s+1):[i[0]];break}}}}let c=n?.onError,l=r&&c?(e,t)=>{c(e,{location:r.location,params:r.matches?.[0]?.params??{},pattern:et(r.matches),errorInfo:t})}:void 0;return i.reduceRight((e,n,c)=>{let u,d=!1,f=null,p=null;r&&(u=a&&n.route.id?a[n.route.id]:void 0,f=n.route.errorElement||Er,o&&(s<0&&c===0?(Vr(`route-fallback`,!1,"No `HydrateFallback` element provided to render during initial hydration"),d=!0,p=null):s===c&&(d=!0,p=n.route.hydrateFallbackElement||null)));let m=t.concat(i.slice(0,c+1)),h=()=>{let t;return t=u?f:d?p:n.route.Component?D.createElement(n.route.Component,null):n.route.element?n.route.element:e,D.createElement(Ar,{match:n,routeContext:{outlet:e,matches:m,isDataRoute:r!=null},children:t})};return r&&(n.route.ErrorBoundary||n.route.errorElement||c===0)?D.createElement(Dr,{location:r.location,revalidation:r.revalidation,component:f,error:u,children:h(),routeContext:{outlet:null,matches:m,isDataRoute:!0},onError:l}):h()},null)}function Mr(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function Nr(e){let t=D.useContext(Qn);return C(t,Mr(e)),t}function Pr(e){let t=D.useContext($n);return C(t,Mr(e)),t}function Fr(e){let t=D.useContext(sr);return C(t,Mr(e)),t}function Ir(e){let t=Fr(e),n=t.matches[t.matches.length-1];return C(n.route.id,`${e} can only be used on routes that contain a unique "id"`),n.route.id}function Lr(){return Ir(`useRouteId`)}function Rr(){let e=D.useContext(cr),t=Pr(`useRouteError`),n=Ir(`useRouteError`);return e===void 0?t.errors?.[n]:e}function zr(){let{router:e}=Nr(`useNavigate`),t=Ir(`useNavigate`),n=D.useRef(!1);return D.useLayoutEffect(()=>{n.current=!0}),D.useCallback(async(r,i={})=>{w(n.current,_r),n.current&&(typeof r==`number`?await e.navigate(r):await e.navigate(r,{fromRouteId:t,...i}))},[e,t])}var Br={};function Vr(e,t,n){!t&&!Br[e]&&(Br[e]=!0,w(!1,n))}var Hr={};function Ur(e,t){!e&&!Hr[t]&&(Hr[t]=!0,console.warn(t))}var Wr=[`HydrateFallback`,`hydrateFallbackElement`],Gr=class{status=`pending`;promise;resolve;reject;constructor(){this.promise=new Promise((e,t)=>{this.resolve=t=>{this.status===`pending`&&(this.status=`resolved`,e(t))},this.reject=e=>{this.status===`pending`&&(this.status=`rejected`,t(e))}})}};function Kr({router:e,flushSync:t,onError:n,useTransitions:r}){r=tr()||r;let[i,a]=D.useState(e.state),[o,s]=(0,D.useOptimistic)(i),[c,l]=D.useState(),[u,d]=D.useState({isTransitioning:!1}),[f,p]=D.useState(),[m,h]=D.useState(),[g,_]=D.useState(),v=D.useRef(new Map),y=D.useCallback((i,{deletedFetchers:o,newErrors:c,flushSync:u,viewTransitionOpts:g})=>{c&&n&&Object.values(c).forEach(e=>n(e,{location:i.location,params:i.matches[0]?.params??{},pattern:et(i.matches)})),i.fetchers.forEach((e,t)=>{e.data!==void 0&&v.current.set(t,e.data)}),o.forEach(e=>v.current.delete(e)),Ur(u===!1||t!=null,'You provided the `flushSync` option to a router update, but you are not using the `<RouterProvider>` from `react-router/dom` so `ReactDOM.flushSync()` is unavailable. Please update your app to `import { RouterProvider } from "react-router/dom"` and ensure you have `react-dom` installed as a dependency to use the `flushSync` option.');let y=e.window!=null&&e.window.document!=null&&typeof e.window.document.startViewTransition==`function`;if(Ur(g==null||y,"You provided the `viewTransition` option to a router update, but you do not appear to be running in a DOM environment as `window.startViewTransition` is not available."),!g||!y){t&&u?t(()=>a(i)):r===!1?a(i):D.startTransition(()=>{r===!0&&s(e=>qr(e,i)),a(i)});return}if(t&&u){t(()=>{m&&(f?.resolve(),m.skipTransition()),d({isTransitioning:!0,flushSync:!0,currentLocation:g.currentLocation,nextLocation:g.nextLocation})});let n=e.window.document.startViewTransition(()=>{t(()=>a(i))});n.finished.finally(()=>{t(()=>{p(void 0),h(void 0),l(void 0),d({isTransitioning:!1})})}),t(()=>h(n));return}m?(f?.resolve(),m.skipTransition(),_({state:i,currentLocation:g.currentLocation,nextLocation:g.nextLocation})):(l(i),d({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}))},[e.window,t,m,f,r,s,n]);D.useLayoutEffect(()=>e.subscribe(y),[e,y]),D.useEffect(()=>{u.isTransitioning&&!u.flushSync&&p(new Gr)},[u]),D.useEffect(()=>{if(f&&c&&e.window){let t=c,n=f.promise,i=e.window.document.startViewTransition(async()=>{r===!1?a(t):D.startTransition(()=>{r===!0&&s(e=>qr(e,t)),a(t)}),await n});i.finished.finally(()=>{p(void 0),h(void 0),l(void 0),d({isTransitioning:!1})}),h(i)}},[c,f,e.window,r,s]),D.useEffect(()=>{f&&c&&o.location.key===c.location.key&&f.resolve()},[f,m,o.location,c]),D.useEffect(()=>{!u.isTransitioning&&g&&(l(g.state),d({isTransitioning:!0,flushSync:!1,currentLocation:g.currentLocation,nextLocation:g.nextLocation}),_(void 0))},[u.isTransitioning,g]);let b=D.useMemo(()=>({createHref:e.createHref,createURL:e.createURL,encodeLocation:e.encodeLocation,go:t=>e.navigate(t),push:(t,n,r)=>e.navigate(t,{state:n,preventScrollReset:r?.preventScrollReset}),replace:(t,n,r)=>e.navigate(t,{replace:!0,state:n,preventScrollReset:r?.preventScrollReset})}),[e]),x=e.basename||`/`,S=D.useMemo(()=>({router:e,navigator:b,static:!1,basename:x,onError:n}),[e,b,x,n]);return D.createElement(D.Fragment,null,D.createElement(Qn.Provider,{value:S},D.createElement($n.Provider,{value:o},D.createElement(rr.Provider,{value:v.current},D.createElement(nr.Provider,{value:u},D.createElement(Qr,{basename:x,location:o.location,navigationType:o.historyAction,navigator:b,useTransitions:r},D.createElement(Jr,{routes:e.routes,manifest:e.manifest,future:e.future,state:o,isStatic:!1,onError:n})))))),null)}function qr(e,t){return{...e,navigation:t.navigation.state===`idle`?e.navigation:t.navigation,revalidation:t.revalidation===`idle`?e.revalidation:t.revalidation,actionData:t.navigation.state===`submitting`?e.actionData:t.actionData,fetchers:t.fetchers}}var Jr=D.memo(Yr);function Yr({routes:e,manifest:t,future:n,state:r,isStatic:i,onError:a}){return wr(e,void 0,{manifest:t,state:r,isStatic:i,onError:a,future:n})}function Xr({to:e,replace:t,state:n,relative:r}){C(hr(),`<Navigate> may be used only in the context of a <Router> component.`);let{static:i,navigator:a}=D.useContext(ar);w(!i,`<Navigate> must not be used on the initial render in a <StaticRouter>. This is a no-op, but you should modify your code so the <Navigate> is only ever rendered in response to some user interaction or state change.`);let{matches:o}=D.useContext(sr),{pathname:s}=gr(),c=vr(),l=We(e,Ue(o),s,r===`path`);Ct(typeof e==`string`?e:ne(e),a.createHref(l),bt(a),`reject`);let u=JSON.stringify(l);return D.useEffect(()=>{c(JSON.parse(u),{replace:t,state:n,relative:r})},[c,u,r,t,n]),null}function Zr(e){return xr(e.context)}function Qr({basename:e=`/`,children:t=null,location:n,navigationType:r=`POP`,navigator:i,static:a=!1,useTransitions:o}){C(!hr(),`You cannot render a <Router> inside another <Router>. You should never have more than one in your app.`);let s=e.replace(/^\/*/,`/`),c=D.useMemo(()=>({basename:s,navigator:i,static:a,useTransitions:o,future:{}}),[s,i,a,o]);typeof n==`string`&&(n=re(n));let{pathname:l=`/`,search:u=``,hash:d=``,state:f=null,key:p=`default`,mask:m}=n,h=D.useMemo(()=>{let e=Ie(l,s);return e==null?null:{location:{pathname:e,search:u,hash:d,state:f,key:p,mask:m},navigationType:r}},[s,l,u,d,f,p,r,m]);return w(h!=null,`<Router basename="${s}"> is not able to match the URL "${l}${u}${d}" because it does not start with the basename, so the <Router> won't render anything.`),h==null?null:D.createElement(ar.Provider,{value:c},D.createElement(or.Provider,{children:t,value:h}))}D.Component;var $r=`application/x-www-form-urlencoded`;function ei(e){return typeof HTMLElement<`u`&&e instanceof HTMLElement}function ti(e){return ei(e)&&e.tagName.toLowerCase()===`button`}function ni(e){return ei(e)&&e.tagName.toLowerCase()===`form`}function ri(e){return ei(e)&&e.tagName.toLowerCase()===`input`}function ii(e){return!!(e.metaKey||e.altKey||e.ctrlKey||e.shiftKey)}function ai(e,t){return e.button===0&&(!t||t===`_self`)&&!ii(e)}function oi(e=``){return new URLSearchParams(typeof e==`string`||Array.isArray(e)||e instanceof URLSearchParams?e:Object.keys(e).reduce((t,n)=>{let r=e[n];return t.concat(Array.isArray(r)?r.map(e=>[n,e]):[[n,r]])},[]))}function si(e,t){let n=oi(e);return t&&t.forEach((e,r)=>{n.has(r)||t.getAll(r).forEach(e=>{n.append(r,e)})}),n}var ci=null;function li(){if(ci===null)try{new FormData(document.createElement(`form`),0),ci=!1}catch{ci=!0}return ci}var ui=new Set([`application/x-www-form-urlencoded`,`multipart/form-data`,`text/plain`]);function di(e){return e!=null&&!ui.has(e)?(w(!1,`"${e}" is not a valid \`encType\` for \`<Form>\`/\`<fetcher.Form>\` and will default to "${$r}"`),null):e}function fi(e,t){let n,r,i,a,o;if(ni(e)){let o=e.getAttribute(`action`);r=o?Ie(o,t):null,n=e.getAttribute(`method`)||`get`,i=di(e.getAttribute(`enctype`))||$r,a=new FormData(e)}else if(ti(e)||ri(e)&&(e.type===`submit`||e.type===`image`)){let o=e.form;if(o==null)throw Error(`Cannot submit a <button> or <input type="submit"> without a <form>`);let s=e.getAttribute(`formaction`)||o.getAttribute(`action`);if(r=s?Ie(s,t):null,n=e.getAttribute(`formmethod`)||o.getAttribute(`method`)||`get`,i=di(e.getAttribute(`formenctype`))||di(o.getAttribute(`enctype`))||$r,a=new FormData(o,e),!li()){let{name:t,type:n,value:r}=e;if(n===`image`){let e=t?`${t}.`:``;a.append(`${e}x`,`0`),a.append(`${e}y`,`0`)}else t&&a.append(t,r)}}else if(ei(e))throw Error(`Cannot submit element that is not <form>, <button>, or <input type="submit|image">`);else n=`get`,r=null,i=$r,o=e;return a&&i===`text/plain`&&(o=a,a=void 0),{action:r,method:n.toLowerCase(),encType:i,formData:a,body:o}}function pi(e,t){if(e===!1||e==null)throw Error(t)}function mi(e,t){let n=typeof e==`string`?new URL(e,typeof window>`u`?`server://singlefetch/`:window.location.origin):e;return n.pathname=n.pathname.endsWith(`/`)?`${n.pathname}_.${t}`:`${n.pathname}.${t}`,n}var hi=g(),gi=`modulepreload`,_i=function(e){return`/`+e},vi={},yi=function(e,t,n){let r=Promise.resolve();if(t&&t.length>0){let e=document.getElementsByTagName(`link`),i=document.querySelector(`meta[property=csp-nonce]`),a=i?.nonce||i?.getAttribute(`nonce`);function o(e){return Promise.all(e.map(e=>Promise.resolve(e).then(e=>({status:`fulfilled`,value:e}),e=>({status:`rejected`,reason:e}))))}function s(e){return import.meta.resolve?import.meta.resolve(e):new URL(e,import.meta.url).href}r=o(t.map(t=>{if(t=_i(t,n),t=s(t),t in vi)return;vi[t]=!0;let r=t.endsWith(`.css`);for(let n=e.length-1;n>=0;n--){let i=e[n];if(i.href===t&&(!r||i.rel===`stylesheet`))return}let i=document.createElement(`link`);if(i.rel=r?`stylesheet`:gi,r||(i.as=`script`),i.crossOrigin=``,i.href=t,a&&i.setAttribute(`nonce`,a),document.head.appendChild(i),r)return new Promise((e,n)=>{i.addEventListener(`load`,e),i.addEventListener(`error`,()=>n(Error(`Unable to preload CSS for ${t}`)))})}))}function i(e){let t=new Event(`vite:preloadError`,{cancelable:!0});if(t.payload=e,window.dispatchEvent(t),!t.defaultPrevented)throw e}return r.then(t=>{for(let e of t||[])e.status===`rejected`&&i(e.reason);return e().catch(i)})};async function bi(e,t){if(e.id in t)return t[e.id];try{let n=await yi(()=>import(e.module),[]);return t[e.id]=n,n}catch(t){return console.error(`Error loading route module \`${e.module}\`, reloading page...`),console.error(t),window.__reactRouterContext&&window.__reactRouterContext.isSpaMode,window.location.reload(),new Promise(()=>{})}}function xi(e){return e!=null&&typeof e.page==`string`}function Si(e){return e==null?!1:e.href==null?e.rel===`preload`&&typeof e.imageSrcSet==`string`&&typeof e.imageSizes==`string`:typeof e.rel==`string`&&typeof e.href==`string`}async function Ci(e,t,n){return Oi((await Promise.all(e.map(async e=>{let r=t.routes[e.route.id];if(r){let e=await bi(r,n);return e.links?e.links():[]}return[]}))).flat(1).filter(Si).filter(e=>e.rel===`stylesheet`||e.rel===`preload`).map(e=>e.rel===`stylesheet`?{...e,rel:`prefetch`,as:`style`}:{...e,rel:`prefetch`}))}function wi(e,t,n,r,i,a){let o=(e,t)=>!n[t]||e.route.id!==n[t].route.id,s=(e,t)=>n[t].pathname!==e.pathname||n[t].route.path?.endsWith(`*`)&&n[t].params[`*`]!==e.params[`*`];return a===`assets`?t.filter((e,t)=>o(e,t)||s(e,t)):a===`data`?t.filter((t,a)=>{let c=r.routes[t.route.id];if(!c||!c.hasLoader)return!1;if(o(t,a)||s(t,a))return!0;if(t.route.shouldRevalidate){let r=t.route.shouldRevalidate({currentUrl:new URL(i.pathname+i.search+i.hash,window.origin),currentParams:n[0]?.params||{},nextUrl:new URL(e,window.origin),nextParams:t.params,defaultShouldRevalidate:!0});if(typeof r==`boolean`)return r}return!0}):[]}function Ti(e,t,{includeHydrateFallback:n}={}){return Ei(e.map(e=>{let r=t.routes[e.route.id];if(!r)return[];let i=[r.module];return r.clientActionModule&&(i=i.concat(r.clientActionModule)),r.clientLoaderModule&&(i=i.concat(r.clientLoaderModule)),n&&r.hydrateFallbackModule&&(i=i.concat(r.hydrateFallbackModule)),r.imports&&(i=i.concat(r.imports)),i}).flat(1))}function Ei(e){return[...new Set(e)]}function Di(e){let t={},n=Object.keys(e).sort();for(let r of n)t[r]=e[r];return t}function Oi(e,t){let n=new Set,r=new Set(t);return e.reduce((e,i)=>{if(t&&!xi(i)&&i.as===`script`&&i.href&&r.has(i.href))return e;let a=JSON.stringify(Di(i));return n.has(a)||(n.add(a),e.push({key:a,link:i})),e},[])}function ki(){let e=D.useContext(Qn);return pi(e,`You must render this element inside a <DataRouterContext.Provider> element`),e}function Ai(){let e=D.useContext($n);return pi(e,`You must render this element inside a <DataRouterStateContext.Provider> element`),e}var ji=D.createContext(void 0);ji.displayName=`FrameworkContext`;function Mi(){let e=D.useContext(ji);return pi(e,`You must render this element inside a <HydratedRouter> element`),e}function Ni(e,t){let n=D.useContext(ji),[r,i]=D.useState(!1),[a,o]=D.useState(!1),{onFocus:s,onBlur:c,onMouseEnter:l,onMouseLeave:u,onTouchStart:d}=t,f=D.useRef(null);D.useEffect(()=>{if(e===`render`&&o(!0),e===`viewport`){let e=new IntersectionObserver(e=>{e.forEach(e=>{o(e.isIntersecting)})},{threshold:.5});return f.current&&e.observe(f.current),()=>{e.disconnect()}}},[e]),D.useEffect(()=>{if(r){let e=setTimeout(()=>{o(!0)},100);return()=>{clearTimeout(e)}}},[r]);let p=()=>{i(!0)},m=()=>{i(!1),o(!1)};return n?e===`intent`?[a,f,{onFocus:Pi(s,p),onBlur:Pi(c,m),onMouseEnter:Pi(l,p),onMouseLeave:Pi(u,m),onTouchStart:Pi(d,p)}]:[a,f,{}]:[!1,f,{}]}function Pi(e,t){return n=>{e&&e(n),n.defaultPrevented||t(n)}}function Fi({page:e,...t}){let n=tr(),{nonce:r}=Mi(),{router:i}=ki(),a=D.useMemo(()=>pe(i.routes,e,i.basename),[i.routes,e,i.basename]);return a?(t.nonce==null&&r&&(t={...t,nonce:r}),n?D.createElement(Li,{page:e,matches:a,...t}):D.createElement(Ri,{page:e,matches:a,...t})):null}function Ii(e){let{manifest:t,routeModules:n}=Mi(),[r,i]=D.useState([]);return D.useEffect(()=>{let r=!1;return Ci(e,t,n).then(e=>{r||i(e)}),()=>{r=!0}},[e,t,n]),r}function Li({page:e,matches:t,...n}){let r=gr(),i=D.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=mi(e,`rsc`),i=!1,a=[];for(let e of t)typeof e.route.shouldRevalidate==`function`?i=!0:a.push(e.route.id);return i&&a.length>0&&n.searchParams.set(`_routes`,a.join(`,`)),[n.pathname+n.search]},[e,r,t]);return D.createElement(D.Fragment,null,i.map(e=>D.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})))}function Ri({page:e,matches:t,...n}){let r=gr(),{manifest:i,routeModules:a}=Mi(),{loaderData:o,matches:s}=Ai(),c=D.useMemo(()=>wi(e,t,s,i,r,`data`),[e,t,s,i,r]),l=D.useMemo(()=>wi(e,t,s,i,r,`assets`),[e,t,s,i,r]),u=D.useMemo(()=>{if(e===r.pathname+r.search+r.hash)return[];let n=new Set,s=!1;if(t.forEach(e=>{let t=i.routes[e.route.id];t&&t.hasLoader&&(!c.some(t=>t.route.id===e.route.id)&&e.route.id in o&&a[e.route.id]?.shouldRevalidate||t.hasClientLoader?s=!0:n.add(e.route.id))}),n.size===0)return[];let l=mi(e,`data`);return s&&n.size>0&&l.searchParams.set(`_routes`,t.filter(e=>n.has(e.route.id)).map(e=>e.route.id).join(`,`)),[l.pathname+l.search]},[o,r,i,c,t,e,a]),d=D.useMemo(()=>Ti(l,i),[l,i]),f=Ii(l);return D.createElement(D.Fragment,null,u.map(e=>D.createElement(`link`,{key:e,rel:`prefetch`,as:`fetch`,href:e,...n})),d.map(e=>D.createElement(`link`,{key:e,rel:`modulepreload`,href:e,...n})),f.map(({key:e,link:t})=>D.createElement(`link`,{key:e,nonce:n.nonce,...t,crossOrigin:t.crossOrigin??n.crossOrigin})))}function zi(...e){return t=>{e.forEach(e=>{typeof e==`function`?e(t):e!=null&&(e.current=t)})}}var Bi=typeof window<`u`&&window.document!==void 0&&window.document.createElement!==void 0;try{Bi&&(window.__reactRouterVersion=`8`)}catch{}function Vi(e,t){return It({basename:t?.basename,getContext:t?.getContext,future:t?.future,history:S({window:t?.window}),hydrationData:t?.hydrationData||Hi(),routes:e,mapRouteProperties:ue,hydrationRouteProperties:Wr,dataStrategy:t?.dataStrategy,patchRoutesOnNavigation:t?.patchRoutesOnNavigation,window:t?.window,instrumentations:t?.instrumentations}).initialize()}function Hi(){let e=window?.__staticRouterHydrationData;return e&&e.errors&&(e={...e,errors:Ui(e.errors)}),e}function Ui(e){if(!e)return null;let t=Object.entries(e),n={};for(let[e,r]of t)if(r&&r.__type===`RouteErrorResponse`)n[e]=new Qe(r.status,r.statusText,r.data,r.internal===!0);else if(r&&r.__type===`Error`){if(typeof r.__subType==`string`&&Ze.includes(r.__subType)){let t=window[r.__subType];if(typeof t==`function`)try{let i=new t(r.message);i.stack=``,n[e]=i}catch{}}if(n[e]==null){let t=Error(r.message);t.stack=``,n[e]=t}}else n[e]=r;return n}var k=D.forwardRef(function({onClick:e,discover:t=`render`,prefetch:n=`none`,relative:r,reloadDocument:i,replace:a,mask:o,state:s,target:c,to:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m){let{basename:h,navigator:g,useTransitions:v}=D.useContext(ar),y=typeof l==`string`&&_.test(l),b=rt(l,h);l=b.to;let x=mr(l,{relative:r}),S=gr(),C=null;if(o){let e=We(o,[],S.mask?S.mask.pathname:`/`,!0);h!==`/`&&(e.pathname=e.pathname===`/`?h:Ke([h,e.pathname])),C=g.createHref(e)}let[w,T,ee]=Ni(n,p),te=Ji(l,{replace:a,mask:o,state:s,target:c,preventScrollReset:u,relative:r,viewTransition:d,defaultShouldRevalidate:f,useTransitions:v});function ne(t){e&&e(t),t.defaultPrevented||te(t)}let re=!(b.isExternal||i),E=D.createElement(`a`,{...p,...ee,href:(re?C:void 0)||b.absoluteURL||x,onClick:re?ne:e,ref:zi(m,T),target:c,"data-discover":!y&&t===`render`?`true`:void 0});return w&&!y?D.createElement(D.Fragment,null,E,D.createElement(Fi,{page:x})):E});k.displayName=`Link`;var Wi=D.forwardRef(function({"aria-current":e=`page`,caseSensitive:t=!1,className:n=``,end:r=!1,style:i,to:a,viewTransition:o,children:s,...c},l){let u=Cr(a,{relative:c.relative}),d=gr(),f=D.useContext($n),{navigator:p,basename:m}=D.useContext(ar),h=f!=null&&ea(u)&&o===!0,g=p.encodeLocation?p.encodeLocation(u).pathname:u.pathname,_=d.pathname,v=f&&f.navigation&&f.navigation.location?f.navigation.location.pathname:null;t||(_=_.toLowerCase(),v=v?v.toLowerCase():null,g=g.toLowerCase()),v&&m&&(v=Ie(v,m)||v);let y=g!==`/`&&g.endsWith(`/`)?g.length-1:g.length,b=_===g||!r&&_.startsWith(g)&&_.charAt(y)===`/`,x=v!=null&&(v===g||!r&&v.startsWith(g)&&v.charAt(y)===`/`),S={isActive:b,isPending:x,isTransitioning:h},C=b?e:void 0,w;w=typeof n==`function`?n(S):[n,b?`active`:null,x?`pending`:null,h?`transitioning`:null].filter(Boolean).join(` `);let T=typeof i==`function`?i(S):i;return D.createElement(k,{...c,"aria-current":C,className:w,ref:l,style:T,to:a,viewTransition:o},typeof s==`function`?s(S):s)});Wi.displayName=`NavLink`;var Gi=D.forwardRef(({discover:e=`render`,fetcherKey:t,navigate:n,reloadDocument:r,replace:i,state:a,method:o=`get`,action:s,onSubmit:c,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f,...p},m)=>{let{useTransitions:h}=D.useContext(ar),g=Qi(),v=$i(s,{relative:l}),y=o.toLowerCase()===`get`?`get`:`post`,b=typeof s==`string`&&_.test(s);return D.createElement(`form`,{ref:m,method:y,action:v,onSubmit:r?c:e=>{if(c&&c(e),e.defaultPrevented)return;e.preventDefault();let r=e.nativeEvent.submitter,s=r?.getAttribute(`formmethod`)||o,p=()=>g(r||e.currentTarget,{fetcherKey:t,method:s,navigate:n,replace:i,state:a,relative:l,preventScrollReset:u,viewTransition:d,defaultShouldRevalidate:f});h&&n!==!1?D.startTransition(()=>p()):p()},...p,"data-discover":!b&&e===`render`?`true`:void 0})});Gi.displayName=`Form`;function Ki(e){return`${e} must be used within a data router. See https://reactrouter.com/en/main/routers/picking-a-router.`}function qi(e){let t=D.useContext(Qn);return C(t,Ki(e)),t}function Ji(e,{target:t,replace:n,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c,useTransitions:l}={}){let u=vr(),d=gr(),f=Cr(e,{relative:o});return D.useCallback(p=>{if(ai(p,t)){p.preventDefault();let t=n===void 0?ne(d)===ne(f):n,m=()=>u(e,{replace:t,mask:r,state:i,preventScrollReset:a,relative:o,viewTransition:s,defaultShouldRevalidate:c});l?D.startTransition(()=>m()):m()}},[d,u,f,n,r,i,t,e,a,o,s,c,l])}function Yi(e){w(typeof URLSearchParams<`u`,"You cannot use the `useSearchParams` hook in a browser that does not support the URLSearchParams API. If you need to support Internet Explorer 11, we recommend you load a polyfill such as https://github.com/ungap/url-search-params.");let t=D.useRef(oi(e)),n=D.useRef(!1),r=gr(),i=D.useMemo(()=>si(r.search,n.current?null:t.current),[r.search]),a=vr();return[i,D.useCallback((e,t)=>{let r=oi(typeof e==`function`?e(new URLSearchParams(i)):e);n.current=!0,a(`?`+r,t)},[a,i])]}var Xi=0,Zi=()=>`__${String(++Xi)}__`;function Qi(){let{router:e}=qi(`useSubmit`),{basename:t}=D.useContext(ar),n=Lr(),r=e.fetch,i=e.navigate;return D.useCallback(async(e,a={})=>{let{action:o,method:s,encType:c,formData:l,body:u}=fi(e,t);a.navigate===!1?await r(a.fetcherKey||Zi(),n,a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,relative:a.relative,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,flushSync:a.flushSync}):await i(a.action||o,{defaultShouldRevalidate:a.defaultShouldRevalidate,preventScrollReset:a.preventScrollReset,relative:a.relative,formData:l,body:u,formMethod:a.method||s,formEncType:a.encType||c,replace:a.replace,state:a.state,fromRouteId:n,flushSync:a.flushSync,viewTransition:a.viewTransition})},[r,i,t,n])}function $i(e,{relative:t}={}){let{basename:n}=D.useContext(ar),r=D.useContext(sr);C(r,`useFormAction must be used inside a RouteContext`);let[i]=r.matches.slice(-1),a={...Cr(e||`.`,{relative:t})},o=gr();if(e==null){a.search=o.search;let e=new URLSearchParams(a.search),t=e.getAll(`index`);if(t.some(e=>e===``)){e.delete(`index`),t.filter(e=>e).forEach(t=>e.append(`index`,t));let n=e.toString();a.search=n?`?${n}`:``}}return(!e||e===`.`)&&i.route.index&&(a.search=a.search?a.search.replace(/^\?/,`?index&`):`?index`),n!==`/`&&(a.pathname=a.pathname===`/`?n:Ke([n,a.pathname])),ne(a)}function ea(e,{relative:t}={}){let n=D.useContext(nr);C(n!=null,"`useViewTransitionState` must be used within `react-router/dom`'s `RouterProvider`. Did you accidentally import `RouterProvider` from `react-router`?");let{basename:r}=qi(`useViewTransitionState`),i=Cr(e,{relative:t});if(!n.isTransitioning)return!1;let a=Ie(n.currentLocation.pathname,r)||n.currentLocation.pathname,o=Ie(n.nextLocation.pathname,r)||n.nextLocation.pathname;return Me(i.pathname,o)!=null||Me(i.pathname,a)!=null}var ta=class extends Error{status;name=`GatewayError`;constructor(e,t){super(t),this.status=e}};function na(e){return e instanceof Error?e.message:String(e)}function ra(e){let t=e.key===``?{}:{authorization:`Bearer ${e.key}`};return e.world!==void 0&&(t[`pinecall-env`]=e.world),e.corner&&(t[`pinecall-corner`]=e.corner),t}var ia=null;function aa(e){ia=e}async function oa(e,t,n={}){return pa(await fetch(ma(e,t,n),{headers:ra(e)}))}async function sa(e,t,n){return pa(await fetch(ma(e,t,{}),{method:`PUT`,headers:{...ra(e),"content-type":`application/json`},body:JSON.stringify(n)}))}async function ca(e,t,n){return pa(await fetch(ma(e,t,{}),{method:`POST`,headers:{...ra(e),"content-type":`application/json`},body:JSON.stringify(n)}))}async function la(e,t){return pa(await fetch(ma(e,t,{}),{method:`DELETE`,headers:ra(e)}))}function ua(e,t,n={}){return ma(e,t,n).toString()}var da=204,fa=401;async function pa(e){if(e.ok)return e.status===da?null:e.json();throw e.status===fa&&ia?.(),new ta(e.status,await ha(e))}function ma(e,t,n){let r=new URL(e.base.replace(/\/$/,``)+t,window.location.origin);for(let[e,t]of Object.entries(n))r.searchParams.set(e,String(t));return r}async function ha(e){try{let t=(await e.json()).detail;return typeof t==`string`?t:e.statusText}catch{return e.statusText}}var ga=`pinecall.theme`,_a=`(prefers-color-scheme: light)`;function va(){return window.matchMedia(_a).matches?`light`:`dark`}function ya(e){document.documentElement.dataset.theme=e}function ba(e){return e===`dark`||e===`light`}function xa(){let e=null;try{e=JSON.parse(window.localStorage.getItem(ga)??`null`)}catch{return null}return e===null||!ba(e.theme)||e.systemWas!==va()?(Ca(),null):e.theme}function Sa(e){try{window.localStorage.setItem(ga,JSON.stringify(e))}catch{}}function Ca(){try{window.localStorage.removeItem(ga)}catch{}}function wa(){ya(xa()??va()),window.matchMedia(_a).addEventListener(`change`,()=>{Ca(),ya(va())})}function Ta(){return document.documentElement.dataset.theme===`light`?`light`:`dark`}function Ea(){let e=Ta()===`dark`?`light`:`dark`,t=va();return e===t?Ca():Sa({theme:e,systemWas:t}),ya(e),e}function Da(e){let t=new MutationObserver(e);return t.observe(document.documentElement,{attributes:!0,attributeFilter:[`data-theme`]}),()=>t.disconnect()}var Oa=o((e=>{var t=Symbol.for(`react.transitional.element`),n=Symbol.for(`react.fragment`);function r(e,n,r){var i=null;if(r!==void 0&&(i=``+r),n.key!==void 0&&(i=``+n.key),`key`in n)for(var a in r={},n)a!==`key`&&(r[a]=n[a]);else r=n;return n=r.ref,{$$typeof:t,type:e,key:i,ref:n===void 0?null:n,props:r}}e.Fragment=n,e.jsx=r,e.jsxs=r})),A=o(((e,t)=>{t.exports=Oa()}))(),ka=(0,D.createContext)(null);function Aa({value:e,children:t}){return(0,A.jsx)(ka,{value:e,children:t})}function j(){let e=(0,D.useContext)(ka);if(e===null)throw Error(`this page was mounted without credentials`);return e}function ja(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function Ma(e,t=`|`){return e.map(e=>Qa(e)).join(t)}function Na(e,t){return typeof t==`bigint`?t.toString():t}function Pa(e){return{get value(){{let t=e();return Object.defineProperty(this,"value",{value:t}),t}}}}function Fa(e){return e==null}function Ia(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function La(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}var Ra=Symbol(`evaluating`);function za(e,t,n){let r;Object.defineProperty(e,t,{get(){if(r!==Ra)return r===void 0&&(r=Ra,r=n()),r},set(n){Object.defineProperty(e,t,{value:n})},configurable:!0})}function Ba(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Va(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Ha(e){return JSON.stringify(e)}function Ua(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}var Wa=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Ga(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var Ka=Pa(()=>{if(Ro.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function qa(e){if(Ga(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Ga(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Ja(e){return qa(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}var Ya=new Set([`string`,`number`,`symbol`]);function Xa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Za(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function M(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Qa(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function $a(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}var eo={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]};function to(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);return Za(e,Va(e._zod.def,{get shape(){let e={};for(let r of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,r))throw Error(`Unrecognized key: "${String(r)}"`);t[r]&&Ba(e,r,n.shape[r])}return Ba(this,`shape`,e),e},checks:[]}))}function no(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);return Za(e,Va(e._zod.def,{get shape(){let r={...e._zod.def.shape};for(let e of Reflect.ownKeys(t)){if(!Object.prototype.hasOwnProperty.call(n.shape,e))throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&delete r[e]}return Ba(this,`shape`,r),r},checks:[]}))}function ro(e,t){if(!qa(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=e._zod.def.shape;for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Za(e,Va(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Ba(this,`shape`,n),n}}))}function io(e,t){if(!qa(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Za(e,Va(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t};return Ba(this,`shape`,n),n}}))}function ao(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);return Za(e,Va(e._zod.def,{get shape(){let n={...e._zod.def.shape,...t._zod.def.shape};return Ba(this,`shape`,n),n},get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function oo(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);return Za(t,Va(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(r,t))throw Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t])}else for(let t of Reflect.ownKeys(r))i[t]=e?new e({type:`optional`,innerType:r[t]}):r[t];return Ba(this,`shape`,i),i},checks:[]}))}function so(e,t,n){return Za(t,Va(t._zod.def,{get shape(){let r=t._zod.def.shape,i={...r};if(n)for(let t of Reflect.ownKeys(n)){if(!Object.prototype.hasOwnProperty.call(i,t))throw Error(`Unrecognized key: "${String(t)}"`);n[t]&&(i[t]=new e({type:`nonoptional`,innerType:r[t]}))}else for(let t of Reflect.ownKeys(r))i[t]=new e({type:`nonoptional`,innerType:r[t]});return Ba(this,`shape`,i),i}}))}function co(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function lo(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function uo(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function fo(e){return typeof e==`string`?e:e?.message}function po(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function mo(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:fo(e.inst?._zod.def?.error?.(e))??fo(a?.(e))??fo(t?.error?.(e))??fo(n.customError?.(e))??fo(n.localeError?.(e))??`Invalid input`,{inst:s,schema:c,continue:l,input:u,...d}=e;return d.path??=[],d.message=o,t?.reportInput&&(d.input=u),d}var ho=/[\uD800-\uDBFF]/;function go(e){let t=e.length;if(!ho.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function _o(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function vo(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function yo(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function bo(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):Co(e,n,r.value)}}function xo(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function So(e,t,n){return xo(e,t,n,!1)}function Co(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:xo(this,t,n.bind(this))},set(e){xo(this,t,e)}})}function wo(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}var To,Eo=!1,Do={configurable:!0,get(){Eo=!0}};function Oo(e,t,n){let r=Object.getPrototypeOf(e._zod);if(t in r&&To!==e._zod){To=void 0;return}To=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,Do);let e=Eo;Eo=!1;try{let r=n(this);return Eo?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Eo||=e,r}catch(n){throw delete this[t],Eo||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}})}function ko(e,t,n,r){let i=wo(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}var Ao=`~constantCatch`;function jo(e){let t=()=>e;return t[Ao]=!0,t}var Mo,No={value:void 0,enumerable:!1},Po=`captureStackTrace`in Error?Error:null;function Fo(e){let t=Po;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Po=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}function N(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=new Set}a.prototype=i;let o=n,s=o&&new WeakSet;function c(n,r){if(!n._zod){No.value=new a(r);try{Object.defineProperty(n,"_zod",No)}finally{No.value=void 0}}if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),bo(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?Fo(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var Io=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Lo=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Mo=globalThis).__zod_globalConfig??(Mo.__zod_globalConfig={});var Ro=globalThis.__zod_globalConfig;function zo(e){return e&&Object.assign(Ro,e),Ro}function Bo(){let e=this._zod;return e.message??=JSON.stringify(e.def,Na,2),e.message}function Vo(e){this._zod.message=e}var Ho={get:Bo,set:Vo,enumerable:!0,configurable:!0},Uo={value:void 0,enumerable:!1},Wo={value:void 0,enumerable:!1},Go=new WeakSet([Object.prototype,Error.prototype]),Ko=(e,t)=>{e.name=`$ZodError`,Uo.value=e._zod,Object.defineProperty(e,"_zod",Uo),Wo.value=t,Object.defineProperty(e,"issues",Wo),Uo.value=void 0,Wo.value=void 0,Object.defineProperty(e,"message",Ho);let n=Object.getPrototypeOf(e);Go.has(n)||(Go.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},qo=N(`$ZodError`,Ko),Jo=N(`$ZodError`,Ko,void 0,{Parent:Error});function Yo(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Xo(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Yo(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Zo(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function Qo(e,t){return{callee:t?.callee??e,Err:t?.Err}}var $o=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new Io;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>mo(e,o,zo())));throw Wa(n,a?.callee??t),n}return s.value};return t},es=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>mo(e,o,zo())));throw Wa(n,a?.callee??t),n}return s.value};return t},ts=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new Io;return a.issues.length?{success:!1,error:new(e??qo)(a.issues.map(e=>mo(e,i,zo())))}:{success:!0,data:a.value}},ns=ts(Jo),rs=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?{success:!1,error:new e(a.issues.map(e=>mo(e,i,zo())))}:{success:!0,data:a.value}},is=rs(Jo),as=e=>{let t=$o(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,Qo(n,a))};return n},os=e=>{let t=$o(e),n=(e,r,i,a)=>t(e,r,i,Qo(n,a));return n},ss=e=>{let t=es(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,Qo(n,a))};return n},cs=e=>{let t=es(e),n=async(e,r,i,a)=>await t(e,r,i,Qo(n,a));return n},ls=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ts(e)(t,n,i)},us=e=>(t,n,r)=>ts(e)(t,n,r),ds=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return rs(e)(t,n,i)},fs=e=>async(t,n,r)=>rs(e)(t,n,r),ps=/^[cC][0-9a-z]{6,}$/,ms=/^[0-9a-z]+$/,hs=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,gs=/^[0-9a-vA-V]{20}$/,_s=/^[A-Za-z0-9]{27}$/,vs=/^[a-zA-Z0-9_-]{21}$/;function ys(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}var bs=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,xs=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,Ss=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Cs=/^(?!\.)(?!.*\.\.)([A-Za-z0-9_'+\-\.]*)[A-Za-z0-9_+-]@([A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/,ws=`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`;function Ts(){return new RegExp(ws,`u`)}var Es=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Ds=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,Os=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,ks=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,As=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,js=/^[A-Za-z0-9_-]*$/,Ms=/^https?$/,Ns=/^\+[1-9]\d{6,14}$/,Ps=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function Fs(e){return RegExp(`^${e}$`)}var Is=Fs(Ps);function Ls(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function Rs(e){return RegExp(`^${Ls(e)}$`)}function zs(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${Ls({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${Ls({precision:e.precision})}`:n;return RegExp(`^${Ps}T(?:${r})$`)}var Bs=e=>{let t=e?`[\\s\\S]{${e?.minimum??0},${e?.maximum??``}}`:`[\\s\\S]*`;return RegExp(`^${t}$`)},Vs=/^-?\d+$/,Hs=/^-?\d+(?:\.\d+)?$/,Us=/^(?:true|false)$/i,Ws=/^[^A-Z]*$/,Gs=/^[^a-z]*$/,Ks=N(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),qs=e=>{let t=e.value;return!Fa(t)&&t.length!==void 0},Js={number:`number`,bigint:`bigint`,object:`date`},Ys=N(`$ZodCheckLessThan`,(e,t)=>{Ks.init(e,t);let n=Js[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.maximum:n.exclusiveMaximum)??1/0;t.value<r&&(t.inclusive?n.maximum=t.value:n.exclusiveMaximum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Js[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Xs=N(`$ZodCheckGreaterThan`,(e,t)=>{Ks.init(e,t);let n=Js[typeof t.value];e._zod.onattach.push(e=>{let n=e._zod.bag,r=(t.inclusive?n.minimum:n.exclusiveMinimum)??-1/0;t.value>r&&(t.inclusive?n.minimum=t.value:n.exclusiveMinimum=t.value)}),e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Js[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Zs=N(`$ZodCheckMultipleOf`,(e,t)=>{Ks.init(e,t),e._zod.onattach.push(e=>{var n;(n=e._zod.bag).multipleOf??(n.multipleOf=t.value)}),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):La(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),Qs=N(`$ZodCheckNumberFormat`,(e,t)=>{Ks.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=eo[t.format];e._zod.onattach.push(e=>{let r=e._zod.bag;r.format=t.format,r.minimum=i,r.maximum=a,n&&(r.pattern=Vs)}),e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),$s=N(`$ZodCheckMaxLength`,(e,t)=>{var n;Ks.init(e,t),(n=e._zod.def).when??(n.when=qs),e._zod.onattach.push(e=>{let n=e._zod.bag.maximum??1/0;t.maximum<n&&(e._zod.bag.maximum=t.maximum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?go(r):i)<=t.maximum)return;let a=_o(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ec=N(`$ZodCheckMinLength`,(e,t)=>{var n;Ks.init(e,t),(n=e._zod.def).when??(n.when=qs),e._zod.onattach.push(e=>{let n=e._zod.bag.minimum??-1/0;t.minimum>n&&(e._zod.bag.minimum=t.minimum)}),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?go(r):i)>=t.minimum)return;let a=_o(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),tc=N(`$ZodCheckLengthEquals`,(e,t)=>{var n;Ks.init(e,t),(n=e._zod.def).when??(n.when=qs),e._zod.onattach.push(e=>{let n=e._zod.bag;n.minimum=t.length,n.maximum=t.length,n.length=t.length}),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?go(r):i;if(a===t.length)return;let o=_o(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),nc=N(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Ks.init(e,t),e._zod.onattach.push(e=>{let n=e._zod.bag;n.format=t.format,t.pattern&&(n.patterns??=new Set,n.patterns.add(t.pattern))}),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),rc=N(`$ZodCheckRegex`,(e,t)=>{nc.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),ic=N(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Ws,nc.init(e,t)}),ac=N(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Gs,nc.init(e,t)}),oc=N(`$ZodCheckIncludes`,(e,t)=>{Ks.init(e,t);let n=Xa(t.includes),r=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n);t.pattern=r,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(r)}),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),sc=N(`$ZodCheckStartsWith`,(e,t)=>{Ks.init(e,t);let n=RegExp(`^${Xa(t.prefix)}.*`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),cc=N(`$ZodCheckEndsWith`,(e,t)=>{Ks.init(e,t);let n=RegExp(`.*${Xa(t.suffix)}$`);t.pattern??=n,e._zod.onattach.push(e=>{let t=e._zod.bag;t.patterns??=new Set,t.patterns.add(n)}),e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),lc=N(`$ZodCheckOverwrite`,(e,t)=>{Ks.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}}),uc=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1,e(this),--this.indent}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
10
+ `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
11
+ `)}\n};`)(...Object.values(this.closed))}},dc={major:4,minor:5,patch:4},fc=N(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=dc;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=co(t),a;for(let o of n){if(o._zod.def.when){if(lo(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new Io;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(po(t.issues,n,e),i||=co(t,n))});else{if(t.issues.length===n)continue;po(t.issues,n,e),i||=co(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(co(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Io;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new Io;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return So(this,`~standard`,mc(this))},set"~standard"(e){xo(this,`~standard`,e)}}),pc=e=>e.success?{value:e.data}:{issues:e.error?.issues};function mc(e){return{validate:t=>{try{return pc(ns(e,t))}catch{return is(e,t).then(pc)}},vendor:`zod`,version:1}}var hc=N(`$ZodString`,(e,t)=>{fc.init(e,t),e._zod.pattern=[...e?._zod.bag?.patterns??[]].pop()??Bs(e._zod.bag),e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),gc=N(`$ZodStringFormat`,(e,t)=>{nc.init(e,t),hc.init(e,t)}),_c=N(`$ZodGUID`,(e,t)=>{t.pattern??=xs,gc.init(e,t)}),vc=N(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=Ss(e)}else t.pattern??=Ss();gc.init(e,t)}),yc=N(`$ZodEmail`,(e,t)=>{t.pattern??=Cs,gc.init(e,t)});function bc(e,t){if(!t.normalize&&t.protocol?.source===Ms.source&&!/^https?:\/\//i.test(e))return 1;try{return new URL(e)}catch{return 2}}var xc=/[\t\n\r]/g;function Sc(e){return e.replace(xc,``)}function Cc(e,t){return t.lastIndex=0,t.test(e.hostname)}function wc(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}var Tc=N(`$ZodURL`,(e,t)=>{gc.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=bc(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}t.hostname&&!Cc(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!wc(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:Sc(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Ec=N(`$ZodEmoji`,(e,t)=>{t.pattern??=Ts(),gc.init(e,t)}),Dc=N(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?vs:ys(t.length),gc.init(e,t)}),Oc=N(`$ZodCUID`,(e,t)=>{t.pattern??=ps,gc.init(e,t)}),kc=N(`$ZodCUID2`,(e,t)=>{t.pattern??=ms,gc.init(e,t)}),Ac=N(`$ZodULID`,(e,t)=>{t.pattern??=hs,gc.init(e,t)}),jc=N(`$ZodXID`,(e,t)=>{t.pattern??=gs,gc.init(e,t)}),Mc=N(`$ZodKSUID`,(e,t)=>{t.pattern??=_s,gc.init(e,t)}),Nc=N(`$ZodISODateTime`,(e,t)=>{t.pattern??=zs(t),gc.init(e,t),(t.local||t.precision===-1)&&(e._zod.bag.laxFormat=!0,e._zod.onattach.push(e=>{e._zod.bag.laxFormat=!0}))}),Pc=N(`$ZodISODate`,(e,t)=>{t.pattern??=Is,gc.init(e,t)}),Fc=N(`$ZodISOTime`,(e,t)=>{t.pattern??=Rs(t),gc.init(e,t)}),Ic=N(`$ZodISODuration`,(e,t)=>{t.pattern??=bs,gc.init(e,t)}),Lc=N(`$ZodIPv4`,(e,t)=>{t.pattern??=Es,gc.init(e,t),e._zod.bag.format=`ipv4`}),Rc=/^[0-9a-fA-F:.]+$/;function zc(e){if(!Rc.test(e))return!1;try{return new URL(`http://[${e}]`),!0}catch{return!1}}var Bc=N(`$ZodIPv6`,(e,t)=>{t.pattern??=Ds,gc.init(e,t),e._zod.bag.format=`ipv6`,e._zod.check=n=>{zc(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Vc=N(`$ZodCIDRv4`,(e,t)=>{t.pattern??=Os,gc.init(e,t)});function Hc(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:zc(n)}var Uc=N(`$ZodCIDRv6`,(e,t)=>{t.pattern??=ks,gc.init(e,t),e._zod.check=n=>{Hc(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Wc(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}var Gc=N(`$ZodBase64`,(e,t)=>{t.pattern??=As,gc.init(e,t),e._zod.bag.contentEncoding=`base64`,e._zod.check=n=>{Wc(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}});function Kc(e){if(!js.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Wc(t.padEnd(Math.ceil(t.length/4)*4,`=`))}var qc=N(`$ZodBase64URL`,(e,t)=>{t.pattern??=js,gc.init(e,t),e._zod.bag.contentEncoding=`base64url`,e._zod.check=n=>{Kc(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),Jc=N(`$ZodE164`,(e,t)=>{t.pattern??=Ns,gc.init(e,t)});function Yc(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}var Xc=N(`$ZodJWT`,(e,t)=>{gc.init(e,t),e._zod.check=n=>{Yc(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),Zc=N(`$ZodNumber`,(e,t)=>{fc.init(e,t),e._zod.pattern=e._zod.bag.pattern??Hs,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),Qc=N(`$ZodNumberFormat`,(e,t)=>{Qs.init(e,t),Zc.init(e,t)}),$c=N(`$ZodBoolean`,(e,t)=>{fc.init(e,t),e._zod.pattern=Us,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),el=N(`$ZodUnknown`,(e,t)=>{fc.init(e,t),e._zod.parse=e=>e}),tl=N(`$ZodNever`,(e,t)=>{fc.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function nl(e,t,n){e.issues.length&&t.issues.push(...uo(n,e.issues)),t.value[n]=e.value}var rl=N(`$ZodArray`,(e,t)=>{fc.init(e,t);let n=Ro.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[];for(let e=0;e<a.length;e++){let n=a[e],s=t.element._zod.run({value:n,issues:[]},i);s instanceof Promise?o.push(s.then(t=>nl(t,r,e))):nl(s,r,e)}return o.length?Promise.all(o).then(()=>r):r}});function il(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...uo(n,e.issues))}if(!o&&i===void 0){e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]});return}e.value===void 0?o&&(t.value[n]=void 0):t.value[n]=e.value}}var al=[];function ol(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:al,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=$a(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function sl(e,t,n,r,i,a){let o=[],s=i.keySet,c=i.catchall._zod,l=c.def.type,u=c.optin,d=c.optout;for(let i in t){if(s.has(i))continue;if(i===`__proto__`){l===`never`&&o.push(i);continue}if(l===`never`){o.push(i);continue}let a=c.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>il(e,n,i,t,u,d))):il(a,n,i,t,u,d)}return o.length&&n.issues.push({code:`unrecognized_keys`,keys:o,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}var cl=new WeakMap,ll=N(`$ZodObject`,(e,t)=>{if(fc.init(e,t),!Object.getOwnPropertyDescriptor(t,`shape`)?.get){let e=t.shape;cl.set(t,e),Object.defineProperty(t,"shape",{get:()=>{let n={...e};return Object.defineProperty(t,"shape",{value:n}),cl.set(t,n),n}})}let n=Pa(()=>ol(t));Oo(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||Ba(n,e,new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let r=Ga,i=t.catchall,a,o=Ro.memoizer;o?.attach(e),e._zod.parse=(t,s)=>{a??=n.value;let c=t.value;if(!r(c))return t.issues.push({expected:`object`,code:`invalid_type`,input:c,inst:e}),t;t.value=o?o.alloc(e,t,{},s):{};let l=[],u=a.shape;for(let e of a.allKeys){if(e===`__proto__`)continue;let n=u[e],r=n._zod.optin,i=n._zod.optout,a=n._zod.run({value:c[e],issues:[]},s);a instanceof Promise?l.push(a.then(n=>il(n,t,e,c,r,i))):il(a,t,e,c,r,i)}return i?sl(l,c,t,s,n.value,e):l.length?Promise.all(l).then(()=>t):t}}),ul=N(`$ZodObjectJIT`,(e,t)=>{ll.init(e,t);let n=e._zod.parse,r=Pa(()=>ol(t)),i=Ro.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new uc([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
12
+ for (let i = 0; i < ${e}.issues.length; i++) {
13
+ const iss = ${e}.issues[i];
14
+ iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
15
+ payload.issues.push(iss);
16
+ }`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:Ha(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
17
+ const ${n}_present = ${i};
18
+ if (!${n}.issues.length || ${n}_present) {
19
+ if (${n}.issues.length) {${c(n,r)}
20
+ }
21
+
22
+ if (${e}) {
23
+ newResult[${r}] = ${n}.value;
24
+ }
25
+ }
26
+
27
+ `)}else f?o.write(`
28
+ if (${n}.issues.length) {${c(n,r)}
29
+ }
30
+
31
+ if (${n}.value === undefined) {
32
+ if (${i}) {
33
+ newResult[${r}] = undefined;
34
+ }
35
+ } else {
36
+ newResult[${r}] = ${n}.value;
37
+ }
38
+
39
+ `):o.write(`
40
+ const ${n}_present = ${i};
41
+ if (${n}.issues.length) {${c(n,r)}
42
+ }
43
+ if (!${n}_present && !${n}.issues.length) {
44
+ payload.issues.push({
45
+ code: "invalid_type",
46
+ expected: "nonoptional",
47
+ input: undefined,
48
+ path: [${r}]
49
+ });
50
+ }
51
+
52
+ if (${n}_present) {
53
+ newResult[${r}] = ${n}.value;
54
+ }
55
+
56
+ `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Ga,c=!Ro.jitless,l=c&&Ka.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?sl([],p,i,f,d,e):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function dl(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!co(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>mo(e,r,zo())))}),t)}var fl=N(`$ZodUnion`,(e,t)=>{fc.init(e,t),Oo(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),Oo(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),Oo(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),Oo(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>Ia(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>dl(t,r,e,i)):dl(o,r,e,i)}}),pl=N(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,fl.init(e,t);let n=e._zod.parse;Oo(e,`propValues`,e=>{let t={};for(let n of e.def.options){let r=n._zod.propValues;if(!r||Object.keys(r).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(n)}"`);for(let[e,n]of Object.entries(r)){Object.prototype.hasOwnProperty.call(t,e)||Ba(t,e,new Set);for(let r of n)t[e].add(r)}}return t}),t.options.forEach((e,n)=>{let r=cl.get(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=Pa(()=>{let e=t.options,n=new Map;for(let r of e){let e=r._zod.propValues?.[t.discriminator];if(!e||e.size===0)throw Error(`Invalid discriminated union option at index "${t.options.indexOf(r)}"`);for(let t of e){if(n.has(t))throw Error(`Duplicate discriminator value "${String(t)}"`);n.set(t,r)}}return n});e._zod.parse=(i,a)=>{let o=i.value;if(!Ga(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=r.value.get(o?.[t.discriminator]);return s?s._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()),input:o,path:[t.discriminator],inst:e}),i)}}),ml=N(`$ZodIntersection`,(e,t)=>{fc.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>gl(e,t,n)):gl(e,i,a)}});function hl(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(qa(e)&&qa(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=hl(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=hl(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function gl(e,t,n){let r=new Map,i,a=new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=hl(t.value,n.value);if(!c.valid){if(co(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}var _l=N(`$ZodTuple`,(e,t)=>{fc.init(e,t);let n=t.items,r=Ro.memoizer;r?.attach(e),e._zod.parse=(i,a)=>{let o=i.value;if(!Array.isArray(o))return i.issues.push({input:o,inst:e,expected:`tuple`,code:`invalid_type`}),i;i.value=r?r.alloc(e,i,[],a):[];let s=[],c=vl(n,`optin`),l=vl(n,`optout`);if(!t.rest){if(o.length<c)return i.issues.push({code:`too_small`,minimum:c,inclusive:!0,input:o,inst:e,origin:`array`}),i;o.length>n.length&&i.issues.push({code:`too_big`,maximum:n.length,inclusive:!0,input:o,inst:e,origin:`array`})}let u=Array(n.length);for(let e=0;e<n.length;e++){let t=n[e]._zod.run({value:o[e],issues:[]},a);t instanceof Promise?s.push(t.then(t=>{u[e]=t})):u[e]=t}if(t.rest){let e=n.length-1,r=o.slice(n.length);for(let n of r){e++;let r=t.rest._zod.run({value:n,issues:[]},a);r instanceof Promise?s.push(r.then(t=>yl(t,i,e))):yl(r,i,e)}}return s.length?Promise.all(s).then(()=>bl(u,i,n,o,l)):bl(u,i,n,o,l)}});function vl(e,t){for(let n=e.length-1;n>=0;n--)if(!(t===`optin`?e[n]._zod.optin!==void 0:e[n]._zod.optout===`optional`))return n+1;return 0}function yl(e,t,n){e.issues.length&&t.issues.push(...uo(n,e.issues)),t.value[n]=e.value}function bl(e,t,n,r,i){for(let a=0;a<n.length;a++){let o=e[a],s=a<r.length;if(!s&&a>=i&&n[a]._zod.optin===`optional`){t.value.length=a;break}if(o.issues.length){if(!s&&a>=i){t.value.length=a;break}t.issues.push(...uo(a,o.issues))}t.value[a]=o.value}for(let e=t.value.length-1;e>=r.length&&n[e]._zod.optout===`optional`&&t.value[e]===void 0;e--)t.value.length=e;return t}var xl=N(`$ZodRecord`,(e,t)=>{fc.init(e,t);let n=Ro.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!qa(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>mo(e,i,zo())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...uo(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...uo(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&Hs.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>mo(e,i,zo())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...uo(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...uo(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Sl=N(`$ZodEnum`,(e,t)=>{fc.init(e,t);let n=ja(t.entries),r=new Set(n);e._zod.values=r;let i=n.filter(e=>Ya.has(typeof e));e._zod.pattern=RegExp(i.length?`^(${i.map(e=>Xa(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),Cl=N(`$ZodLiteral`,(e,t)=>{fc.init(e,t);let n=new Set(t.values);e._zod.values=n,e._zod.pattern=RegExp(t.values.length?`^(${t.values.map(e=>typeof e==`string`?Xa(e):e?Xa(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),wl=N(`$ZodTransform`,(e,t)=>{fc.init(e,t),e._zod.optin=`optional`,Ro.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Lo(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new Io;return n.value=i,n}});function Tl(e,t){return e.value=t.issues.length?void 0:t.value,e}var El=N(`$ZodOptional`,(e,t)=>{fc.init(e,t),Oo(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,Oo(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t,void 0]):void 0}),Oo(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ia(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>Tl(e,t)):Tl(e,r)}return t.innerType._zod.run(e,n)}}),Dl=N(`$ZodExactOptional`,(e,t)=>{El.init(e,t),Oo(e,`values`,e=>e.def.innerType._zod.values),Oo(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Ol=N(`$ZodNullable`,(e,t)=>{fc.init(e,t),Oo(e,`optin`,e=>e.def.innerType._zod.optin),Oo(e,`optout`,e=>e.def.innerType._zod.optout),Oo(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ia(t.source)}|null)$`):void 0}),Oo(e,`values`,e=>e.def.innerType._zod.values?new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),kl=N(`$ZodDefault`,(e,t)=>{fc.init(e,t),e._zod.optin=`defaulted`,Oo(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Al(e,t)):Al(r,t)}});function Al(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}var jl=N(`$ZodPrefault`,(e,t)=>{fc.init(e,t),e._zod.optin=`defaulted`,Oo(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Ml=N(`$ZodNonOptional`,(e,t)=>{fc.init(e,t),Oo(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>Nl(t,e)):Nl(i,e)}});function Nl(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function Pl(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>mo(e,r,zo()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}var Fl=N(`$ZodCatch`,(e,t)=>{fc.init(e,t),Oo(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),Oo(e,`optout`,e=>e.def.innerType._zod.optout),Oo(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>Pl(e,r,t,n)):Pl(e,r,t,n)}}),Il=N(`$ZodPipe`,(e,t)=>{fc.init(e,t),Oo(e,`values`,e=>e.def.in._zod.values),Oo(e,`optin`,e=>e.def.in._zod.optin),Oo(e,`optout`,e=>e.def.out._zod.optout),Oo(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Ll(e,t.in,n)):Ll(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ll(e,t.out,n)):Ll(r,t.out,n)}});function Ll(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}var Rl=N(`$ZodReadonly`,(e,t)=>{fc.init(e,t),Oo(e,`propValues`,e=>e.def.innerType._zod.propValues),Oo(e,`values`,e=>e.def.innerType._zod.values),Oo(e,`optin`,e=>e.def.innerType?._zod?.optin),Oo(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(zl):zl(r)}});function zl(e){return e.memo||(e.value=Object.freeze(e.value)),e}var Bl=N(`$ZodLazy`,(e,t)=>{fc.init(e,t),za(e._zod,`innerType`,()=>{let e=t;return e._cachedInner||=t.getter(),e._cachedInner}),Oo(e,`pattern`,e=>e.innerType?._zod?.pattern),Oo(e,`propValues`,e=>e.innerType?._zod?.propValues),Oo(e,`optin`,e=>e.innerType?._zod?.optin??void 0),Oo(e,`optout`,e=>e.innerType?._zod?.optout??void 0),e._zod.parse=(t,n)=>e._zod.innerType._zod.run(t,n)}),Vl=N(`$ZodCustom`,(e,t)=>{Ks.init(e,t),fc.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Hl(t,n,r,e));Hl(i,n,r,e)}});function Hl(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(yo(e))}}var Ul=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}},Wl=`~memo`,Gl=[];function Kl(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}var ql=new WeakMap;function Jl(e,t){let n=ql.get(e);if(n!==void 0)return n;if(t.has(e))return!0;t.add(e);let r=!1,i=e=>{!r&&e?._zod&&Jl(e,t)&&(r=!0)},a=e._zod.def;switch(a.type){case`object`:for(let e of Reflect.ownKeys(a.shape))i(a.shape[e]);i(a.catchall);break;case`array`:i(a.element);break;case`tuple`:for(let e of a.items)i(e);i(a.rest);break;case`record`:case`map`:i(a.keyType),i(a.valueType);break;case`set`:i(a.valueType);break;case`union`:for(let e of a.options)i(e);break;case`intersection`:i(a.left),i(a.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:i(a.innerType);break;case`pipe`:i(a.in),i(a.out);break;case`function`:i(a.input),i(a.output);break;case`lazy`:i(e._zod.innerType);break;case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in a){let t=Object.getOwnPropertyDescriptor(a,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)i(n);else if(Array.isArray(n))for(let e of n)i(e)}}}return t.delete(e),ql.set(e,r),r}function Yl(e,t){let n=e.buckets.get(t);return n||(n=new Map,e.buckets.set(t,n)),n}var Xl,Zl=[],Ql={alloc(e,t,n){let r=Xl;if(!r)return n;Xl=void 0;let i={value:n,issues:null};return r.set(t.value,i),Zl.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&eu(n,e.value))throw new Ul;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r,i;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,a=(o,s)=>{if(n===void 0&&(n=Jl(e,new Set),!n))return e._zod.parse=t,e._zod.run===a&&(e._zod.run=t),t(o,s);let c=o.value;if(typeof c!=`object`||!c)return t(o,s);let l=s[Wl];l||(l={buckets:new Map,backEdges:void 0},s[Wl]=l);let u;r===s?u=i:(u=Yl(l,e),r=s,i=u);let d=u.get(c);if(d)return o.value=d.value,d.issues?d.issues.length&&o.issues.push(...Kl(d.issues)):(o.memo=!0,l.backEdges??(l.backEdges=new Set),l.backEdges.add(d.value)),o;Xl=u;let f=Zl.length,p=t(o,s);Xl=void 0;let m=Zl.length>f?Zl.pop():void 0;return p instanceof Promise?p.then(e=>(m&&(m.issues=e.issues.length?Kl(e.issues):Gl),e)):(m&&(m.issues=p.issues.length?Kl(p.issues):Gl),p)};e._zod.parse=a,e._zod.run===t&&(e._zod.run=a)})}};function $l(){return Ql}function eu(e,t){let n=e[Wl]?.backEdges;return n!==void 0&&typeof t==`object`&&!!t&&n.has(t)}var tu=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,credit_card:`credit card number`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(vo(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${Qa(e.values[0])}`:`Invalid option: expected one of ${Ma(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${Ma(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function nu(){return{localeError:tu()}}var ru,iu=class{constructor(){this._map=new WeakMap,this._idmap=new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=new WeakMap,this._idmap=new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function au(){return new iu}(ru=globalThis).__zod_globalRegistry??(ru.__zod_globalRegistry=au());var ou=globalThis.__zod_globalRegistry;function su(e,t){return new e({type:`string`,...M(t)})}function cu(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...M(t)})}function lu(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...M(t)})}function uu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...M(t)})}function du(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...M(t)})}function fu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...M(t)})}function pu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...M(t)})}function mu(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...M(t)})}function hu(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...M(t)})}function gu(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...M(t)})}function _u(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...M(t)})}function vu(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...M(t)})}function yu(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...M(t)})}function bu(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...M(t)})}function xu(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...M(t)})}function Su(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...M(t)})}function Cu(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...M(t)})}function wu(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...M(t)})}function Tu(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...M(t)})}function Eu(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...M(t)})}function Du(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...M(t)})}function Ou(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...M(t)})}function ku(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...M(t)})}function Au(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...M(t)})}function ju(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...M(t)})}function Mu(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...M(t)})}function Nu(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...M(t)})}function Pu(e,t){return new e({type:`number`,checks:[],...M(t)})}function Fu(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...M(t)})}function Iu(e,t){return new e({type:`boolean`,...M(t)})}function Lu(e){return new e({type:`unknown`})}function Ru(e,t){return new e({type:`never`,...M(t)})}function zu(e,t){return new Ys({check:`less_than`,...M(t),value:e,inclusive:!1})}function Bu(e,t){return new Ys({check:`less_than`,...M(t),value:e,inclusive:!0})}function Vu(e,t){return new Xs({check:`greater_than`,...M(t),value:e,inclusive:!1})}function Hu(e,t){return new Xs({check:`greater_than`,...M(t),value:e,inclusive:!0})}function Uu(e,t){return new Zs({check:`multiple_of`,...M(t),value:e})}function Wu(e,t){return new $s({check:`max_length`,...M(t),maximum:e})}function Gu(e,t){return new ec({check:`min_length`,...M(t),minimum:e})}function Ku(e,t){return new tc({check:`length_equals`,...M(t),length:e})}function qu(e,t){return new rc({check:`string_format`,format:`regex`,...M(t),pattern:e})}function Ju(e){return new ic({check:`string_format`,format:`lowercase`,...M(e)})}function Yu(e){return new ac({check:`string_format`,format:`uppercase`,...M(e)})}function Xu(e,t){return new oc({check:`string_format`,format:`includes`,...M(t),includes:e})}function Zu(e,t){return new sc({check:`string_format`,format:`starts_with`,...M(t),prefix:e})}function Qu(e,t){return new cc({check:`string_format`,format:`ends_with`,...M(t),suffix:e})}function $u(e){return new lc({check:`overwrite`,tx:e})}function ed(e){return $u(t=>t.normalize(e))}function td(){return $u(e=>e.trim())}function nd(){return $u(e=>e.toLowerCase())}function rd(){return $u(e=>e.toUpperCase())}function id(){return $u(e=>Ua(e))}function ad(e,t,n){return new e({type:`array`,element:t,...M(n)})}function od(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...M(n)})}function sd(e,t){let n=cd(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(yo(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(yo(r))}},e(t.value,t)),t);return n}function cd(e,t){let n=new Ks({check:`custom`,...M(t)});return n._zod.check=e,n}function ld(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Ba(e,t,n[t]);return e}function ud(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??ou,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function dd(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function fd(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,fd(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&ld(o.schema,c),t.io===`input`&&Sd(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function pd(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function md(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${pd(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+pd(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
57
+
58
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0]){a(n);continue}if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}if(e.metadataRegistry.get(n[0])?.id){a(n);continue}if(r.cycle){a(n);continue}if(r.count>1&&e.reused===`ref`){a(n);continue}}e.external&&(e.sharedDefsExtractedFor=e.external)}function hd(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;hd(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}var gd=new Set([`type`,`properties`,`required`,`additionalProperties`]),_d=[`oneOf`,`anyOf`];function vd(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function yd(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!gd.has(e))return null;t.push(n)}let n={},r=new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??vd(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ba(n,r,e.length===1?e[0]:yd(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=vd(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function bd(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of gd)if(t in e)return;let n=t.filter(e=>_d.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=yd(t);else{let e=n[0],i=_d.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>yd([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,ld(e,r))}function xd(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):ld(i,s),ld(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())hd(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])bd(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}ld(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Ba(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:wd(t,`input`,e.processors),output:wd(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Sd(e,t){let n=t??{seen:new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return Sd(r.element,n);if(r.type===`set`)return Sd(r.valueType,n);if(r.type===`lazy`)return Sd(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return Sd(r.innerType,n);if(r.type===`intersection`)return Sd(r.left,n)||Sd(r.right,n);if(r.type===`record`||r.type===`map`)return Sd(r.keyType,n)||Sd(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Sd(r.in,n)||Sd(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Sd(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Sd(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Sd(e,n))return!0;return!!(r.rest&&Sd(r.rest,n))}return!1}var Cd=(e,t={})=>n=>{let r=ud({...n,processors:t});return fd(e,r),md(r,e),xd(r,e)},wd=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=ud({...i??{},target:a,io:t,processors:n});return fd(e,o),md(o,e),xd(o,e)},Td={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Ed=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=e._zod.bag;if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Td[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c];e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Dd=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,format:s,multipleOf:c,exclusiveMaximum:l,exclusiveMinimum:u}=e._zod.bag;i.type=typeof s==`string`&&s.includes(`int`)?`integer`:`number`;let d=typeof u==`number`&&u>=(a??-1/0),f=typeof l==`number`&&l<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;d?p?(i.minimum=u,i.exclusiveMinimum=!0):i.exclusiveMinimum=u:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=l,i.exclusiveMaximum=!0):i.exclusiveMaximum=l:typeof o==`number`&&(i.maximum=o),typeof c==`number`&&(Number.isFinite(c)&&c!==0?i.multipleOf=Math.abs(c):dd(e,t,i,r,`A multipleOf divisor of ${c} cannot be represented in JSON Schema`))},Od=(e,t,n,r)=>{n.type=`boolean`},kd=(e,t,n,r)=>{dd(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},Ad=(e,t,n,r)=>{dd(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},jd=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},Md=(e,t,n,r)=>{dd(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},Nd=(e,t,n,r)=>{dd(e,t,n,r,`Void cannot be represented in JSON Schema`)},Pd=(e,t,n,r)=>{n.not={}},Fd=(e,t,n,r)=>{},Id=(e,t,n,r)=>{},Ld=(e,t,n,r)=>{dd(e,t,n,r,`Date cannot be represented in JSON Schema`)},Rd=(e,t,n,r)=>{let i=e._zod.def,a=ja(i.entries);if(a.length===0){n.not={};return}a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a},zd=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(dd(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(dd(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},Bd=(e,t,n,r)=>{dd(e,t,n,r,`NaN cannot be represented in JSON Schema`)},Vd=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},Hd=(e,t,n,r)=>{let i=n,a={type:`string`,format:`binary`,contentEncoding:`binary`},{minimum:o,maximum:s,mime:c}=e._zod.bag;o!==void 0&&(a.minLength=o),s!==void 0&&(a.maxLength=s),c?c.length===1?(a.contentMediaType=c[0],Object.assign(i,a)):(Object.assign(i,a),i.anyOf=c.map(e=>({contentMediaType:e}))):Object.assign(i,a)},Ud=(e,t,n,r)=>{n.type=`boolean`},Wd=(e,t,n,r)=>{dd(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},Gd=(e,t,n,r)=>{dd(e,t,n,r,`Function types cannot be represented in JSON Schema`)},Kd=(e,t,n,r)=>{dd(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},qd=(e,t,n,r)=>{dd(e,t,n,r,`Map cannot be represented in JSON Schema`)},Jd=(e,t,n,r)=>{dd(e,t,n,r,`Set cannot be represented in JSON Schema`)},Yd=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=e._zod.bag;typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=fd(a.element,t,{...r,path:[...r.path,`items`]})};function Xd(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Xd(t.out):t.type===`catch`?Xd(t.innerType):e._zod.optin}var Zd=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&dd(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Ba(i.properties,e,fd(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=new Set(Object.keys(o)),c=new Set([...s].filter(e=>{let n=a.shape[e];return t.io===`input`?Xd(n)===void 0:n._zod.optout===void 0}));c.size>0&&(i.required=Array.from(c)),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=fd(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Qd=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>fd(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},$d=(e,t,n,r)=>{let i=e._zod.def,a=fd(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=fd(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},ef=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>fd(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?fd(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Xd(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=e._zod.bag;typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function tf(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=tf(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>tf(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i?(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Hs:Vs).source),p):p}var nf=new WeakMap;function rf(e){let t=new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=new Map;for(let r of nf.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=tf(t,a,new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}var af=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=o._zod.bag?.patterns;if(a.mode===`loose`&&s&&s.size>0){let e=fd(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ba(i.patternProperties,t.source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=fd(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=nf.get(t);n||(n=[],nf.set(t,n),t.deferred.push(()=>rf(t))),n.push(e)}i.additionalProperties=fd(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Xd(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},of=(e,t,n,r)=>{let i=e._zod.def,a=fd(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},sf=(e,t,n,r)=>{let i=e._zod.def;fd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},cf=Symbol();function lf(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(dd(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),cf):JSON.parse(o)}var uf=(e,t,n,r)=>{let i=e._zod.def;fd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=lf(i.defaultValue,e,t,n,r);o!==cf&&(n.default=o)},df=(e,t,n,r)=>{let i=e._zod.def;fd(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=lf(i.defaultValue,e,t,n,r);o!==cf&&(n._prefault=o)},ff=(e,t,n,r)=>{let i=e._zod.def;fd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{dd(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},pf=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;fd(o,t,r);let s=t.seen.get(e);s.ref=o},mf=(e,t,n,r)=>{let i=e._zod.def;fd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},hf=(e,t,n,r)=>{let i=e._zod.def;fd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},gf=(e,t,n,r)=>{let i=e._zod.def;fd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},_f=(e,t,n,r)=>{let i=e._zod.innerType;fd(i,t,r);let a=t.seen.get(e);a.ref=i},vf={string:Ed,number:Dd,boolean:Od,bigint:kd,symbol:Ad,null:jd,undefined:Md,void:Nd,never:Pd,any:Fd,unknown:Id,date:Ld,enum:Rd,literal:zd,nan:Bd,template_literal:Vd,file:Hd,success:Ud,custom:Wd,function:Gd,transform:Kd,map:qd,set:Jd,array:Yd,object:Zd,union:Qd,intersection:$d,tuple:ef,record:af,nullable:of,nonoptional:sf,default:uf,prefault:df,catch:ff,pipe:pf,readonly:mf,promise:hf,optional:gf,lazy:_f};function yf(e,t){if(`_idmap`in e){let n=e,r=ud({...t,processors:vf}),i={};for(let e of n._idmap.entries()){let[t,n]=e;fd(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;md(r,n),Ba(a,t,xd(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=ud({...t,processors:vf});return fd(e,n),md(n,e),xd(n,e)}var bf=new WeakSet([Object.prototype,Error.prototype]);function xf(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}var Sf=N(`ZodError`,(e,t)=>{qo.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);bf.has(n)||(bf.add(n),xf(n,`format`,e=>t=>Zo(e,t)),xf(n,`flatten`,e=>t=>Xo(e,t)),xf(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Na,2)}),xf(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Na,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),Cf=$o(Sf),wf=es(Sf),Tf=ts(Sf),Ef=rs(Sf),Df=as(Sf),Of=os(Sf),kf=ss(Sf),Af=cs(Sf),jf=ls(Sf),Mf=us(Sf),Nf=ds(Sf),Pf=fs(Sf);function Ff(){Ro.localeError||zo(nu())}function If(){Ro.memoizer||zo({memoizer:$l()})}var Lf=N(`ZodType`,(e,t)=>(Ff(),fc.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Va(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Za(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(nm(e,t))},superRefine(e,t){return this.check(rm(e,t))},overwrite(e){return this.check($u(e))},optional(){return Ip(this)},exactOptional(){return Rp(this)},nullable(){return Bp(this)},nullish(){return Ip(Bp(this))},nonoptional(e){return Kp(this,e)},array(){return R(this)},or(e){return xp([this,e])},and(e){return Tp(this,e)},transform(e){return Xp(this,Pp(e))},default(e){return Hp(this,e)},prefault(e){return Wp(this,e)},catch(e){return Jp(this,e)},pipe(e){return Xp(this,e)},readonly(){return Qp(this)},describe(e){let t=this.clone();return ou.add(t,{description:e}),t},meta(...e){if(e.length===0)return ou.get(this);let t=this.clone();return ou.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return So(this,`~standard`,{...mc(this),jsonSchema:{input:wd(this,`input`),output:wd(this,`output`)}})},set"~standard"(e){xo(this,`~standard`,e)},parse:function e(t,n){return Cf(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await wf(this,t,n,{callee:e})},safeParse(e,t){return Tf(this,e,t)},async safeParseAsync(e,t){return Ef(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){xo(this,`spa`,e)},encode:function e(t,n){return Df(this,t,n,{callee:e})},decode:function e(t,n){return Of(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await kf(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await Af(this,t,n,{callee:e})},safeEncode(e,t){return jf(this,e,t)},safeDecode(e,t){return Mf(this,e,t)},async safeEncodeAsync(e,t){return Nf(this,e,t)},async safeDecodeAsync(e,t){return Pf(this,e,t)},toJSONSchema(e){return Cd(this,{})(e)},get description(){return ou.get(this)?.description},get _def(){return this._zod.def}}),Rf=N(`_ZodString`,(e,t)=>{hc.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ed(e,t,n,r);let n=e._zod.bag;e.format=n.format??null,e.minLength=n.minimum??null,e.maxLength=n.maximum??null},{regex(...e){return this.check(qu(...e))},includes(...e){return this.check(Xu(...e))},startsWith(...e){return this.check(Zu(...e))},endsWith(...e){return this.check(Qu(...e))},min(...e){return this.check(Gu(...e))},max(...e){return this.check(Wu(...e))},length(...e){return this.check(Ku(...e))},nonempty(...e){return this.check(Gu(1,...e))},lowercase(e){return this.check(Ju(e))},uppercase(e){return this.check(Yu(e))},trim(){return this.check(td())},normalize(...e){return this.check(ed(...e))},toLowerCase(){return this.check(nd())},toUpperCase(){return this.check(rd())},slugify(){return this.check(id())}}),zf=N(`ZodString`,(e,t)=>{hc.init(e,t),Rf.init(e,t)},{email(e){return this.check(cu(Gf,e))},url(e){return this.check(mu(Jf,e))},jwt(e){return this.check(ku(lp,e))},emoji(e){return this.check(hu(Yf,e))},guid(e){return this.check(lu(Kf,e))},uuid(e){return this.check(uu(qf,e))},uuidv4(e){return this.check(du(qf,e))},uuidv6(e){return this.check(fu(qf,e))},uuidv7(e){return this.check(pu(qf,e))},nanoid(e){return this.check(gu(Xf,e))},cuid(e){return this.check(_u(Zf,e))},cuid2(e){return this.check(vu(Qf,e))},ulid(e){return this.check(yu($f,e))},base64(e){return this.check(Eu(op,e))},base64url(e){return this.check(Du(sp,e))},xid(e){return this.check(bu(ep,e))},ksuid(e){return this.check(xu(tp,e))},ipv4(e){return this.check(Su(np,e))},ipv6(e){return this.check(Cu(rp,e))},cidrv4(e){return this.check(wu(ip,e))},cidrv6(e){return this.check(Tu(ap,e))},e164(e){return this.check(Ou(cp,e))},datetime(e){return this.check(Au(Vf,e))},date(e){return this.check(ju(Hf,e))},time(e){return this.check(Mu(Uf,e))},duration(e){return this.check(Nu(Wf,e))}});function P(e){return su(zf,e)}var Bf=N(`ZodStringFormat`,(e,t)=>{gc.init(e,t),Rf.init(e,t)}),Vf=N(`ZodISODateTime`,(e,t)=>{Nc.init(e,t),Bf.init(e,t)}),Hf=N(`ZodISODate`,(e,t)=>{Pc.init(e,t),Bf.init(e,t)}),Uf=N(`ZodISOTime`,(e,t)=>{Fc.init(e,t),Bf.init(e,t)}),Wf=N(`ZodISODuration`,(e,t)=>{Ic.init(e,t),Bf.init(e,t)}),Gf=N(`ZodEmail`,(e,t)=>{yc.init(e,t),Bf.init(e,t)}),Kf=N(`ZodGUID`,(e,t)=>{_c.init(e,t),Bf.init(e,t)}),qf=N(`ZodUUID`,(e,t)=>{vc.init(e,t),Bf.init(e,t)}),Jf=N(`ZodURL`,(e,t)=>{Tc.init(e,t),Bf.init(e,t)}),Yf=N(`ZodEmoji`,(e,t)=>{Ec.init(e,t),Bf.init(e,t)}),Xf=N(`ZodNanoID`,(e,t)=>{Dc.init(e,t),Bf.init(e,t)}),Zf=N(`ZodCUID`,(e,t)=>{Oc.init(e,t),Bf.init(e,t)}),Qf=N(`ZodCUID2`,(e,t)=>{kc.init(e,t),Bf.init(e,t)}),$f=N(`ZodULID`,(e,t)=>{Ac.init(e,t),Bf.init(e,t)}),ep=N(`ZodXID`,(e,t)=>{jc.init(e,t),Bf.init(e,t)}),tp=N(`ZodKSUID`,(e,t)=>{Mc.init(e,t),Bf.init(e,t)}),np=N(`ZodIPv4`,(e,t)=>{Lc.init(e,t),Bf.init(e,t)}),rp=N(`ZodIPv6`,(e,t)=>{Bc.init(e,t),Bf.init(e,t)}),ip=N(`ZodCIDRv4`,(e,t)=>{Vc.init(e,t),Bf.init(e,t)}),ap=N(`ZodCIDRv6`,(e,t)=>{Uc.init(e,t),Bf.init(e,t)}),op=N(`ZodBase64`,(e,t)=>{Gc.init(e,t),Bf.init(e,t)}),sp=N(`ZodBase64URL`,(e,t)=>{qc.init(e,t),Bf.init(e,t)}),cp=N(`ZodE164`,(e,t)=>{Jc.init(e,t),Bf.init(e,t)}),lp=N(`ZodJWT`,(e,t)=>{Xc.init(e,t),Bf.init(e,t)}),up=N(`ZodNumber`,(e,t)=>{Zc.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Dd(e,t,n,r);let n=e._zod.bag;e.minValue=Math.max(n.minimum??-1/0,n.exclusiveMinimum??-1/0)??null,e.maxValue=Math.min(n.maximum??1/0,n.exclusiveMaximum??1/0)??null,e.isInt=(n.format??``).includes(`int`)||Number.isSafeInteger(n.multipleOf??.5),e.isFinite=!0,e.format=n.format??null},{gt(e,t){return this.check(Vu(e,t))},gte(e,t){return this.check(Hu(e,t))},min(e,t){return this.check(Hu(e,t))},lt(e,t){return this.check(zu(e,t))},lte(e,t){return this.check(Bu(e,t))},max(e,t){return this.check(Bu(e,t))},int(e){return this.check(I(e))},safe(e){return this.check(I(e))},positive(e){return this.check(Vu(0,e))},nonnegative(e){return this.check(Hu(0,e))},negative(e){return this.check(zu(0,e))},nonpositive(e){return this.check(Bu(0,e))},multipleOf(e,t){return this.check(Uu(e,t))},step(e,t){return this.check(Uu(e,t))},finite(){return this}});function F(e){return Pu(up,e)}var dp=N(`ZodNumberFormat`,(e,t)=>{Qc.init(e,t),up.init(e,t)});function I(e){return Fu(dp,e)}var fp=N(`ZodBoolean`,(e,t)=>{$c.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Od(e,t,n,r)});function L(e){return Iu(fp,e)}var pp=N(`ZodUnknown`,(e,t)=>{el.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function mp(){return Lu(pp)}var hp=N(`ZodNever`,(e,t)=>{tl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pd(e,t,n,r)});function gp(e){return Ru(hp,e)}var _p=N(`ZodArray`,(e,t)=>{If(),rl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Yd(e,t,n,r),e.element=t.element},{min(e,t){return this.check(Gu(e,t))},nonempty(e){return this.check(Gu(1,e))},max(e,t){return this.check(Wu(e,t))},length(e,t){return this.check(Ku(e,t))},unwrap(){return this.element}});function R(e,t){return ad(_p,e,t)}var vp=N(`ZodObject`,(e,t)=>{If(),ul.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zd(e,t,n,r),ko(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return V(Object.keys(this._zod.def.shape))},catchall(e){return this.clone({...this._zod.def,catchall:e})},passthrough(){return this.clone({...this._zod.def,catchall:mp()})},loose(){return this.clone({...this._zod.def,catchall:mp()})},strict(){return this.clone({...this._zod.def,catchall:gp()})},strip(){return this.clone({...this._zod.def,catchall:void 0})},extend(e){return ro(this,e)},safeExtend(e){return io(this,e)},merge(e){return ao(this,e)},pick(e){return to(this,e)},omit(e){return no(this,e)},partial(...e){return oo(Fp,this,e[0])},exactPartial(...e){return oo(Lp,this,e[0],`exactPartial`)},required(...e){return so(Gp,this,e[0])}});function z(e,t){return new vp({type:`object`,shape:e??{},...M(t)})}function B(e,t){return new vp({type:`object`,shape:e,catchall:gp(),...M(t)})}function yp(e,t){return new vp({type:`object`,shape:e,catchall:mp(),...M(t)})}var bp=N(`ZodUnion`,(e,t)=>{fl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qd(e,t,n,r),e.options=t.options});function xp(e,t){return new bp({type:`union`,options:e,...M(t)})}var Sp=N(`ZodDiscriminatedUnion`,(e,t)=>{bp.init(e,t),pl.init(e,t)});function Cp(e,t,n){return new Sp({type:`union`,options:t,discriminator:e,...M(n)})}var wp=N(`ZodIntersection`,(e,t)=>{ml.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$d(e,t,n,r)});function Tp(e,t){return new wp({type:`intersection`,left:e,right:t})}var Ep=N(`ZodTuple`,(e,t)=>{If(),_l.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ef(e,t,n,r)},{rest(e){return this.clone({...this._zod.def,rest:e})},partial(){let e=this._zod.def;if(e.checks?.length)throw Error(`.partial() cannot be used on tuple schemas containing refinements`);return this.clone({...e,items:e.items.map(e=>new Fp({type:`optional`,innerType:e}))})}});function Dp(e,t,n){let r=t instanceof fc;return new Ep({type:`tuple`,items:e,rest:r?t:null,...M(r?n:t)})}var Op=N(`ZodRecord`,(e,t)=>{If(),xl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>af(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function kp(e,t,n){return!t||!t._zod?new Op({type:`record`,keyType:P(),valueType:e,...M(t)}):new Op({type:`record`,keyType:e,valueType:t,...M(n)})}var Ap=N(`ZodEnum`,(e,t)=>{Sl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rd(e,t,n,r),e.enum=t.entries,e.options=Object.values(t.entries);let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new Ap({...t,checks:[],...M(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new Ap({...t,checks:[],...M(r),entries:i})}});function V(e,t){return new Ap({type:`enum`,entries:Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e,...M(t)})}var jp=N(`ZodLiteral`,(e,t)=>{Cl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zd(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function Mp(e,t){return new jp({type:`literal`,values:Array.isArray(e)?e:[e],...M(t)})}var Np=N(`ZodTransform`,(e,t)=>{If(),wl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Kd(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Lo(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(yo(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(yo(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Pp(e){return new Np({type:`transform`,transform:e})}var Fp=N(`ZodOptional`,(e,t)=>{El.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Ip(e){return new Fp({type:`optional`,innerType:e})}var Lp=N(`ZodExactOptional`,(e,t)=>{Dl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Rp(e){return new Lp({type:`optional`,innerType:e})}var zp=N(`ZodNullable`,(e,t)=>{Ol.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>of(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bp(e){return new zp({type:`nullable`,innerType:e})}var Vp=N(`ZodDefault`,(e,t)=>{kl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Hp(e,t){return new Vp({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ja(t)}})}var Up=N(`ZodPrefault`,(e,t)=>{jl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>df(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Wp(e,t){return new Up({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ja(t)}})}var Gp=N(`ZodNonOptional`,(e,t)=>{Ml.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Kp(e,t){return new Gp({type:`nonoptional`,innerType:e,...M(t)})}var qp=N(`ZodCatch`,(e,t)=>{Fl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ff(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Jp(e,t){return new qp({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:jo(t)})}var Yp=N(`ZodPipe`,(e,t)=>{Il.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pf(e,t,n,r),e.in=t.in,e.out=t.out});function Xp(e,t){return new Yp({type:`pipe`,in:e,out:t})}var Zp=N(`ZodReadonly`,(e,t)=>{Rl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>mf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Qp(e){return new Zp({type:`readonly`,innerType:e})}var $p=N(`ZodLazy`,(e,t)=>{Bl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_f(e,t,n,r),e.unwrap=()=>e._zod.def.getter()});function em(e){return new $p({type:`lazy`,getter:e})}var tm=N(`ZodCustom`,(e,t)=>{Vl.init(e,t),Lf.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Wd(e,t,n,r)});function nm(e,t={}){return od(tm,e,t)}function rm(e,t){return sd(e,t)}var im=z({key:P(),key_id:P(),org:P(),label:P().nullish(),env:V([`production`,`sandbox`]),scopes:R(P()),subject:P().nullish(),name:P().nullish()}),am=`console`;async function om(e,t){return xm(e,{code:t,device:am})}async function sm(e,t){return xm(e,{...t,org:t.org===void 0||t.org===``?null:t.org,device:am})}var cm=z({orgs:R(z({org:P(),slug:P().nullish(),name:P().nullish(),role:P(),status:P(),here:L(),member:L().optional()}))});async function lm(e){return cm.parse(await oa(e,`/v1/login/orgs`)).orgs}async function um(e,t){return im.parse(await ca(e,`/v1/login/org`,{org:t}))}async function dm(e,t,n){return Sm(e,`/v1/invitations/${encodeURIComponent(t)}`,{password:n,device:am})}var fm=z({orgs:R(z({org:P(),slug:P().nullish(),name:P().nullish(),role:P()}))});async function pm(e,t,n){let r=await fetch(new URL(`${e.replace(/\/$/,``)}/v1/login/orgs`,window.location.origin),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t,password:n})});return r.status===404||r.status===405?null:fm.parse(await pa(r)).orgs}var mm=z({orgs:R(z({org:P(),slug:P().nullish(),name:P().nullish()}))});async function hm(e,t){return fetch(new URL(`${e.replace(/\/$/,``)}/v1/login/sso/discover`,window.location.origin),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify({email:t})})}async function gm(e){try{let t=await hm(e,``);return t.status!==404&&t.status!==405}catch{return!1}}async function _m(e,t){return mm.parse(await pa(await hm(e,t))).orgs}function vm(e,t){return new URL(`${e.replace(/\/$/,``)}/v1/login/sso?org=${encodeURIComponent(t)}`,window.location.origin).toString()}function ym(e){return new URL(`${e.replace(/\/$/,``)}/v1/login/google`,window.location.origin).toString()}function bm(e){return`${e.replace(/\/$/,``)}/v1/login/google/callback`}async function xm(e,t){return Sm(e,`/v1/login`,t)}async function Sm(e,t,n){let r=await fetch(new URL(`${e.replace(/\/$/,``)}${t}`,window.location.origin),{method:`POST`,headers:{"content-type":`application/json`},body:JSON.stringify(n)});return im.parse(await pa(r))}function Cm({children:e,foot:t}){return(0,A.jsxs)(`div`,{className:`login`,children:[(0,A.jsxs)(`div`,{className:`login-side`,children:[(0,A.jsx)(`img`,{className:`login-logo login-logo-daylight`,src:`/pinecall-logo.png`,alt:`Pinecall`}),(0,A.jsx)(`img`,{className:`login-logo login-logo-dark`,src:`/pinecall-logo-dark.png`,alt:`Pinecall`}),(0,A.jsx)(`div`,{className:`login-form`,children:e}),(0,A.jsx)(`p`,{className:`login-foot`,children:t??(0,A.jsxs)(A.Fragment,{children:[`Working from a terminal? Run `,(0,A.jsx)(`span`,{className:`login-command`,children:`pinecall link`}),` in your project's folder.`]})})]}),(0,A.jsx)(Tm,{})]})}var wm=[{initials:`DK`,tint:`violet`,name:`Dana Keller`,line:`Booked · Friday 2 PM, work order #SO-2026-PL-0060`,channel:`phone`},{initials:`TS`,tint:`pink`,name:`Tim Stacy`,line:`Quoted the fifteen dollar dispatch fee`,channel:`web`},{initials:`AR`,tint:`green`,name:`Ana Ruiz`,line:`Callback promised within the hour`,channel:`whatsapp`}];function Tm(){return(0,A.jsxs)(`div`,{className:`login-show`,"aria-hidden":!0,children:[(0,A.jsxs)(`div`,{className:`login-show-words`,children:[(0,A.jsx)(`h2`,{className:`login-show-title`,children:`Every conversation your company has, in one place.`}),(0,A.jsx)(`p`,{className:`login-show-lede`,children:`Web, WhatsApp and phone land in the same inbox — with the transcript, the outcome and the cost on every row.`})]}),(0,A.jsxs)(`div`,{className:`login-show-card`,children:[(0,A.jsxs)(`div`,{className:`login-show-head`,children:[(0,A.jsx)(`span`,{className:`ui-dot ui-dot-green`}),(0,A.jsx)(`span`,{className:`login-show-today`,children:`Today`}),(0,A.jsx)(`span`,{className:`login-show-count`,children:`137 conversations`})]}),wm.map(e=>(0,A.jsxs)(`div`,{className:`login-show-row`,children:[(0,A.jsx)(`span`,{className:`ui-avatar ui-avatar-26 ui-tint-${e.tint}`,children:e.initials}),(0,A.jsxs)(`div`,{className:`ui-row-main`,children:[(0,A.jsx)(`div`,{className:`login-show-name`,children:e.name}),(0,A.jsx)(`div`,{className:`login-show-line`,children:e.line})]}),(0,A.jsx)(`span`,{className:`login-show-channel`,children:e.channel})]},e.name))]})]})}function Em(){return(0,A.jsxs)(Cm,{foot:(0,A.jsx)(A.Fragment,{children:`This is your sandbox, on this machine. Production is watched on the gateway's console.`}),children:[(0,A.jsx)(`h1`,{className:`login-title`,children:`This project is not linked`}),(0,A.jsxs)(`p`,{className:`login-lede`,children:[`The gateway refused the key `,(0,A.jsx)(`span`,{className:`login-command`,children:`pinecall serve`}),` is using. Link the project again, in its folder, then start it once more:`]}),(0,A.jsxs)(`pre`,{className:`login-commands`,children:[`pinecall link`,`
59
+ `,`pinecall serve`]})]})}var Dm=(0,D.createContext)(null);function Om({value:e,children:t}){return(0,A.jsx)(Dm,{value:e,children:t})}function km(){let e=(0,D.useContext)(Dm);if(e===null)throw Error(`the console was mounted without a way out`);return e}var Am=typeof document<`u`&&document.querySelector(`meta[name="pinecall-console"]`)?.getAttribute(`content`)===`local`?`local`:`hosted`;function jm(){return(document.querySelector(`meta[name="pinecall-gateway"]`)?.getAttribute(`content`)??window.location.origin).replace(/\/$/,``)}var Mm={hosted:`production`,local:`sandbox`},Nm=[`hosted`,`local`],Pm=[`hosted`],Fm=[`local`],Im=[{key:`home`,path:``,name:`Home`,in:Nm,group:`gateway`,icon:`home`},{key:`agents`,path:`overview`,name:`Overview`,in:Nm,group:`gateway`,icon:`grid`},{key:`live`,path:`live`,name:`Live`,in:Nm,group:`gateway`,icon:`activity`},{key:`sessions`,path:`sessions`,name:`Sessions`,in:Nm,group:`gateway`,icon:`list`},{key:`personas`,path:`personas`,name:`Personas`,in:Nm,group:`gateway`,icon:`persona`},{key:`simulations`,path:`simulations`,name:`Simulations`,in:Nm,group:`gateway`,icon:`headphones`},{key:`org-evals`,path:`evals`,name:`Evals`,in:Nm,group:`gateway`,icon:`check`},{key:`org-memory`,path:`memory`,name:`Memory`,in:Nm,group:`gateway`,icon:`memory`},{key:`org-docs`,path:`docs`,name:`Docs`,in:Nm,group:`gateway`,icon:`book`},{key:`usage`,path:`usage`,name:`Usage`,in:Pm,group:`gateway`,icon:`chart`},{key:`numbers`,path:`numbers`,name:`Numbers`,in:Pm,group:`settings`,icon:`phone`},{key:`phone`,path:`phone`,name:`Phone testing`,in:Fm,group:`settings`,icon:`phone`},{key:`tokens`,path:`tokens`,name:`Tokens`,in:Pm,group:`settings`,icon:`key`},{key:`providers`,path:`providers`,name:`Providers`,in:Pm,group:`settings`,icon:`plug`},{key:`team`,path:`team`,name:`Team`,in:Pm,group:`settings`,icon:`users`},{key:`lexicon`,path:`lexicon`,name:`Lexicon`,in:Nm,group:`settings`,icon:`words`}],Lm=[{key:`box-orgs`,path:`box/orgs`,name:`Organizations`,in:Pm,group:`box`,icon:`building`,operator:!0},{key:`box-fleet`,path:`box/fleet`,name:`Fleet`,in:Pm,group:`box`,icon:`server`,operator:!0},{key:`box-routes`,path:`box/routes`,name:`Routes`,in:Pm,group:`box`,icon:`route`,operator:!0},{key:`box-usage`,path:`box/usage`,name:`Box usage`,in:Pm,group:`box`,icon:`chart`,operator:!0},{key:`box-settings`,path:`box/settings`,name:`Box settings`,in:Pm,group:`box`,icon:`sliders`,operator:!0}],Rm=[{key:`talk`,path:`talk`,name:`Chat`,in:Nm},{key:`devchat`,path:`dev-chat`,name:`Dev chat`,in:Fm},{key:`calls`,path:`calls`,name:`Calls`,in:Nm},{key:`sessions`,path:`sessions`,name:`Sessions`,in:Nm},{key:`settings`,path:`settings`,name:`Settings`,in:Nm},{key:`pipeline`,path:`pipeline`,name:`Pipeline`,in:Nm},{key:`docs`,path:`docs`,name:`Docs`,in:Nm},{key:`memory`,path:`memory`,name:`Memory`,in:Nm},{key:`evals`,path:`evals`,name:`Evals`,in:Nm},{key:`widget`,path:`widget`,name:`Widget`,in:Nm}];function zm(e,t=Am,n=!1){return e.filter(e=>e.in.includes(t)&&(n||e.operator!==!0))}function Bm(e,t,n=Am){return e.some(e=>e.key===t&&e.in.includes(n))}var Vm=[...Im,...Lm,...Rm];function Hm(e){let t=(e.split(/[?#]/)[0]??``).replace(/^\/a\/[^/]+\/?/,`/`).replace(/^\/+/,``).replace(/\/$/,``);return t===``?Vm.find(e=>e.path===``):Vm.filter(e=>e.path!==``&&(t===e.path||t.startsWith(`${e.path}/`))).sort((e,t)=>t.path.length-e.path.length)[0]}var Um=`pinecall.key`;function Wm(){return window.localStorage.getItem(Um)}function Gm(e){window.localStorage.setItem(Um,e)}function Km(){window.localStorage.removeItem(Um)}var qm=`pinecall.corner`;function Jm(){return window.sessionStorage.getItem(qm)}function Ym(e){e===null?window.sessionStorage.removeItem(qm):window.sessionStorage.setItem(qm,e)}function H({children:e,pad:t=!1,style:n}){return(0,A.jsx)(`div`,{className:t?`ui-card ui-card-pad`:`ui-card`,style:n,children:e})}function U({title:e,meta:t,action:n,children:r}){return(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[typeof e==`string`?(0,A.jsx)(`span`,{className:`ui-card-title`,children:e}):e,t!==void 0&&(0,A.jsx)(`span`,{className:`ui-card-meta`,children:t}),r,n]})}function Xm({to:e,onClick:t,children:n}){return e===void 0?(0,A.jsx)(`button`,{type:`button`,className:`ui-card-action`,onClick:t,children:n}):(0,A.jsx)(k,{to:e,className:`ui-card-action`,children:n})}function Zm({children:e}){return(0,A.jsx)(`div`,{className:`ui-card-foot`,children:e})}function Qm({children:e}){return(0,A.jsx)(`div`,{className:`ui-empty`,children:e})}function $m({children:e}){return e==null||e===``?null:(0,A.jsx)(`div`,{className:`ui-refused`,children:e})}function eh({lead:e,name:t,tag:n,sub:r,end:i,to:a,onClick:o}){let s=(0,A.jsxs)(A.Fragment,{children:[e,(0,A.jsxs)(`div`,{className:`ui-row-main`,children:[(0,A.jsxs)(`div`,{className:`ui-row-line`,children:[(0,A.jsx)(`span`,{className:`ui-row-name`,children:t}),n]}),r!==void 0&&(0,A.jsx)(`div`,{className:`ui-row-sub`,children:r})]}),i!==void 0&&(0,A.jsx)(`div`,{className:`ui-row-end`,children:i})]});return a===void 0?(0,A.jsx)(`div`,{className:o===void 0?`ui-row`:`ui-row ui-row-link`,onClick:o,children:s}):(0,A.jsx)(k,{to:a,className:`ui-row ui-row-link`,children:s})}function th({name:e,sub:t,end:n,to:r}){let i=(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`ui-row-main`,children:[(0,A.jsx)(`div`,{className:`ui-item-name`,children:e}),t!==void 0&&(0,A.jsx)(`div`,{className:`ui-item-sub`,children:t})]}),n]});return r===void 0?(0,A.jsx)(`div`,{className:`ui-item`,children:i}):(0,A.jsx)(k,{to:r,className:`ui-item`,children:i})}function nh({children:e,ruled:t=!1}){return(0,A.jsx)(`div`,{className:t?`ui-section-label ui-section-label-ruled`:`ui-section-label`,children:e})}function rh({label:e,children:t,keyWidth:n}){return(0,A.jsxs)(`div`,{className:`ui-kv`,children:[(0,A.jsx)(`span`,{className:`ui-kv-key`,style:n===void 0?void 0:{width:n},children:e}),(0,A.jsx)(`span`,{className:`ui-kv-value`,children:t})]})}function ih(e,t,n,r){let i=[`ui-button`];return e!==`secondary`&&i.push(`ui-button-${e}`),t!==`base`&&i.push(`ui-button-${t}`),n&&i.push(`ui-button-pill`),r!==void 0&&i.push(r),i.join(` `)}function W({kind:e=`secondary`,size:t=`base`,pill:n=!1,className:r,type:i=`button`,...a}){return(0,A.jsx)(`button`,{type:i,className:ih(e,t,n,r),...a})}function ah({to:e,kind:t=`secondary`,size:n=`base`,children:r}){return(0,A.jsx)(k,{to:e,className:ih(t,n,!1),children:r})}function oh({danger:e=!1,...t}){return(0,A.jsx)(`button`,{type:`button`,className:e?`ui-text-action ui-text-action-danger`:`ui-text-action`,...t})}function sh({children:e,htmlFor:t}){return(0,A.jsx)(`label`,{className:`ui-label`,htmlFor:t,children:e})}function G({size:e=`form`,className:t,...n}){let r=[`ui-input`];return e===`sm`&&r.push(`ui-input-sm`),e===`lg`&&r.push(`ui-input-lg`),t!==void 0&&r.push(t),(0,A.jsx)(`input`,{className:r.join(` `),...n})}function ch({size:e=`form`,className:t,...n}){let r=[`ui-select`];return e===`sm`&&r.push(`ui-select-sm`),t!==void 0&&r.push(t),(0,A.jsx)(`select`,{className:r.join(` `),...n})}function lh(e){return(0,A.jsx)(`textarea`,{className:`ui-textarea`,...e})}function uh({label:e,grow:t=!1,minWidth:n,children:r}){return(0,A.jsxs)(`div`,{className:t?`ui-form-grow`:void 0,style:n===void 0?void 0:{minWidth:n},children:[(0,A.jsx)(`label`,{className:`ui-label`,children:e}),r]})}function dh({options:e,value:t,onChange:n}){return(0,A.jsx)(`div`,{className:`ui-segmented`,role:`group`,children:e.map(e=>(0,A.jsx)(`button`,{type:`button`,className:e.value===t?`ui-segment ui-segment-on`:`ui-segment`,"aria-pressed":e.value===t,onClick:()=>n(e.value),children:e.label},e.value))})}function fh({options:e,value:t,onChange:n}){return(0,A.jsx)(`div`,{className:`ui-chips`,role:`group`,children:e.map(e=>(0,A.jsx)(`button`,{type:`button`,className:e.value===t?`ui-chip ui-chip-on`:`ui-chip`,"aria-pressed":e.value===t,onClick:()=>n(e.value),children:e.label},e.value))})}function ph({on:e,children:t,...n}){return(0,A.jsx)(`button`,{type:`button`,className:e?`ui-choice ui-choice-on`:`ui-choice`,"aria-pressed":e,...n,children:t})}function mh({on:e,onChange:t,label:n}){return(0,A.jsx)(`button`,{type:`button`,role:`switch`,"aria-checked":e,"aria-label":n,className:e?`ui-switch ui-switch-on`:`ui-switch`,onClick:()=>t(!e),children:(0,A.jsx)(`span`,{className:`ui-switch-knob`})})}function hh({checked:e,onChange:t,children:n}){return(0,A.jsxs)(`label`,{className:`ui-check`,children:[(0,A.jsx)(`input`,{type:`checkbox`,checked:e,onChange:e=>t(e.target.checked)}),n]})}var gh={home:[`M3 10.5 12 3l9 7.5V20a1 1 0 0 1-1 1h-5v-6H9v6H4a1 1 0 0 1-1-1z`],grid:[{rect:[3,3,7,7,1.5]},{rect:[14,3,7,7,1.5]},{rect:[3,14,7,7,1.5]},{rect:[14,14,7,7,1.5]}],activity:[`M22 12h-4l-3 9L9 3l-3 9H2`],list:[`M8 6h13`,`M8 12h13`,`M8 18h13`,`M3 6h.01`,`M3 12h.01`,`M3 18h.01`],check:[{circle:[12,12,9]},`m8.5 12.5 2.5 2.5 4.5-5`],chart:[`M3 3v18h18`,`M7 15v3`,`M12 9v9`,`M17 5v13`],phone:[`M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1 1 .4 1.9.7 2.8a2 2 0 0 1-.5 2.1L8.1 9.9a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.4c.9.3 1.8.6 2.8.7a2 2 0 0 1 1.7 2z`],key:[`m21 2-9.6 9.6`,`m15.5 7.5 3 3L22 7l-3-3`,{circle:[7.5,15.5,5.5]}],plug:[`M12 22v-5`,`M9 8V2`,`M15 8V2`,`M18 8v3a6 6 0 0 1-12 0V8z`],users:[`M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2`,{circle:[9,7,4]},`M22 21v-2a4 4 0 0 0-3-3.9`],bot:[`M12 8V4`,{rect:[4,8,16,12,2]},`M2 14h2`,`M20 14h2`,`M9 13v2`,`M15 13v2`],search:[{circle:[11,11,7]},`m21 21-4.3-4.3`],panel:[{rect:[3,3,18,18,2]},`M9 3v18`],building:[{rect:[4,2,16,20,2]},`M9 22v-4h6v4`,`M8 6h.01`,`M16 6h.01`,`M12 6h.01`,`M12 10h.01`,`M12 14h.01`,`M16 10h.01`,`M16 14h.01`,`M8 10h.01`,`M8 14h.01`],server:[{rect:[2,2,20,8,2]},{rect:[2,14,20,8,2]},`M6 6h.01`,`M6 18h.01`],route:[{circle:[6,19,3]},`M9 19h8.5a3.5 3.5 0 0 0 0-7h-11a3.5 3.5 0 0 1 0-7H15`,{circle:[18,5,3]}],sliders:[`M21 4h-7`,`M10 4H3`,`M21 12h-9`,`M8 12H3`,`M21 20h-5`,`M12 20H3`,`M14 2v4`,`M8 10v4`,`M16 18v4`],words:[`M4 5h16v10H9l-5 4z`,`M8 9h8`,`M8 12h5`],persona:[{circle:[12,8,4]},`M5 21v-1a7 7 0 0 1 14 0v1`],headphones:[`M3 14h3a2 2 0 0 1 2 2v3a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-7a9 9 0 0 1 18 0v7a2 2 0 0 1-2 2h-1a2 2 0 0 1-2-2v-3a2 2 0 0 1 2-2h3`],book:[`M4 4a2 2 0 0 1 2-2h14v18H6a2 2 0 0 0-2 2z`,`M4 20a2 2 0 0 1 2-2h14`,`M8 6h8`,`M8 10h6`],sun:[{circle:[12,12,4]},`M12 2v2`,`M12 20v2`,`m4.93 4.93 1.41 1.41`,`m17.66 17.66 1.41 1.41`,`M2 12h2`,`M20 12h2`,`m6.34 17.66-1.41 1.41`,`m19.07 4.93-1.41 1.41`],moon:[`M20.985 12.486a9 9 0 1 1-9.473-9.472c.405-.022.617.46.402.803a6 6 0 0 0 8.268 8.268c.344-.215.825-.004.803.401`],memory:[`M12 5a3 3 0 1 0-5.997.125 4 4 0 0 0-2.526 5.77 4 4 0 0 0 .556 6.588A4 4 0 1 0 12 18Z`,`M12 5a3 3 0 1 1 5.997.125 4 4 0 0 1 2.526 5.77 4 4 0 0 1-.556 6.588A4 4 0 1 1 12 18Z`,`M12 5v13`]};function _h({name:e,size:t=16}){return(0,A.jsx)(`svg`,{className:`ui-icon`,width:t,height:t,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:1.75,strokeLinecap:`round`,strokeLinejoin:`round`,"aria-hidden":!0,children:gh[e].map((e,t)=>{if(typeof e==`string`)return(0,A.jsx)(`path`,{d:e},t);if(`circle`in e){let[n,r,i]=e.circle;return(0,A.jsx)(`circle`,{cx:n,cy:r,r:i},t)}let[n,r,i,a,o]=e.rect;return(0,A.jsx)(`rect`,{x:n,y:r,width:i,height:a,rx:o},t)})})}function vh({tone:e,small:t=!1,children:n}){return(0,A.jsx)(`span`,{className:`ui-pill ui-pill-${e}${t?` ui-pill-small`:``}`,children:n})}function yh({children:e}){return(0,A.jsx)(`span`,{className:`ui-tag`,children:e})}function bh({tone:e,small:t=!1}){let n=[`ui-dot`];return t&&n.push(`ui-dot-small`),e!==void 0&&n.push(`ui-dot-${e}`),(0,A.jsx)(`span`,{className:n.join(` `),"aria-hidden":!0})}var xh=[`violet`,`green`,`pink`,`amber`,`indigo`];function Sh(e){return[`violet`,`pink`,`green`,`amber`,`indigo`][e%5]??`violet`}function Ch(e){let t=0;for(let n of e)t=(t+(n.codePointAt(0)??0))%9973;return xh[t%xh.length]??`violet`}function wh(e){let t=e.split(/[\s@._-]+/).filter(e=>/[A-Za-z0-9]/.test(e));if(t.length===0)return`?`;if(t.length===1){let e=t[0]??``;return(/^[A-Za-z]/.test(e)?e.slice(0,2):e.slice(0,1)).toUpperCase()}return`${t[0]?.[0]??``}${t[1]?.[0]??``}`.toUpperCase()}function Th({name:e,letters:t,tint:n,size:r=28,round:i=!1}){let a=[`ui-avatar`,`ui-tint-${n??Ch(e)}`];r===26&&a.push(`ui-avatar-26`),(r===36||r===38)&&a.push(`ui-avatar-36`),i&&a.push(`ui-avatar-round`),r===38&&a.push(`ui-avatar-38`);let o=r===20?{width:20,height:20,borderRadius:6,fontSize:9.5}:void 0;return(0,A.jsx)(`span`,{className:a.join(` `),style:o,"aria-hidden":!0,children:t??wh(e)})}function Eh({share:e,color:t,height:n}){let r=`${Math.max(0,Math.min(1,e))*100}%`;return(0,A.jsx)(`span`,{className:`ui-bar`,style:n===void 0?void 0:{height:n},children:(0,A.jsx)(`span`,{className:`ui-bar-fill`,style:{width:r,background:t}})})}function Dh({width:e=1180,tight:t=!1,children:n}){let r=[`ui-page`];return t&&r.push(`ui-page-tight`),e!==1180&&r.push(`ui-page-${e}`),(0,A.jsx)(`div`,{className:r.join(` `),"data-page":!0,children:n})}function Oh({title:e,lede:t,ledeWidth:n,back:r,actions:i}){return(0,A.jsxs)(`div`,{className:`ui-head`,children:[(0,A.jsxs)(`div`,{className:`ui-head-words`,style:n===void 0?void 0:{maxWidth:n},children:[r,(0,A.jsx)(`h1`,{className:`ui-title`,children:e}),t!==void 0&&(0,A.jsx)(`p`,{className:n===void 0?`ui-lede`:`ui-lede ui-lede-long`,children:t})]}),i!==void 0&&(0,A.jsx)(`div`,{className:`ui-head-actions`,children:i})]})}function kh({min:e,children:t}){return(0,A.jsx)(`div`,{className:`ui-stats`,style:{gridTemplateColumns:`repeat(auto-fit,minmax(${e}px,1fr))`},children:t})}function Ah({label:e,value:t,of:n,delta:r,tone:i,size:a=`medium`,accent:o=!1}){let s=[`ui-stat`];a!==`medium`&&s.push(`ui-stat-${a}`),o&&s.push(`ui-stat-accent`);let c=i===`green`?{color:`var(--green)`}:i===`red`?{color:`var(--red)`}:void 0;return(0,A.jsxs)(`div`,{className:s.join(` `),children:[(0,A.jsx)(`div`,{className:`ui-stat-label`,children:e}),a===`big`?(0,A.jsxs)(`div`,{className:`ui-stat-line`,children:[(0,A.jsx)(`span`,{className:`ui-stat-value`,children:t}),r!==void 0&&(0,A.jsx)(`span`,{className:i===`up`?`ui-stat-delta ui-stat-delta-up`:i===`down`?`ui-stat-delta ui-stat-delta-down`:`ui-stat-delta`,children:r})]}):(0,A.jsxs)(`div`,{className:`ui-stat-value`,style:c,children:[t,n!==void 0&&(0,A.jsxs)(`span`,{className:`ui-stat-of`,children:[` `,n]})]})]})}function jh({columns:e,labels:t,padding:n}){return(0,A.jsx)(`div`,{className:`ui-table-head`,style:{gridTemplateColumns:e,padding:n},children:t.map((e,t)=>e.endsWith(`>`)?(0,A.jsx)(`span`,{style:{textAlign:`right`},children:e.slice(0,-1)},t):(0,A.jsx)(`span`,{children:e},t))})}function Mh({columns:e,to:t,onClick:n,padding:r,children:i}){let a={gridTemplateColumns:e,padding:r};return t===void 0?(0,A.jsx)(`div`,{className:n===void 0?`ui-table-row`:`ui-table-row ui-table-row-link`,style:a,onClick:n,children:i}):(0,A.jsx)(k,{to:t,className:`ui-table-row ui-table-row-link`,style:a,children:i})}var Nh=`pinecall.pane.`;function Ph(e){try{let t=Number(window.localStorage.getItem(Nh+e));return Number.isFinite(t)&&t>0?t:null}catch{return null}}function Fh(e,t){try{window.localStorage.setItem(Nh+e,String(Math.round(t)))}catch{}}function Ih(e){try{window.localStorage.removeItem(Nh+e)}catch{}}var Lh=(e,t,n)=>Math.min(n,Math.max(t,e));function Rh({name:e,initial:t,min:n,max:r,side:i}){let[a,o]=(0,D.useState)(()=>Lh(Ph(e)??t,n,r)),s=(0,D.useRef)(null),c=(0,D.useCallback)(e=>{e.preventDefault(),e.currentTarget.setPointerCapture(e.pointerId),s.current={x:e.clientX,width:a}},[a]),l=(0,D.useCallback)(e=>{if(s.current===null)return;let t=e.clientX-s.current.x;o(Lh(s.current.width+(i===`right`?-t:t),n,r))},[i,n,r]),u=(0,D.useCallback)(()=>{s.current!==null&&(s.current=null,Fh(e,a))},[e,a]),d=(0,D.useCallback)(()=>{Ih(e),o(t)},[e,t]);return{width:a,style:{"--pane":`${String(a)}px`},handle:(0,A.jsx)(`div`,{className:i===`right`?`ui-resize ui-resize-right`:`ui-resize ui-resize-left`,role:`separator`,"aria-orientation":`vertical`,"aria-label":`Drag to resize. Double-click to reset.`,title:`Drag to resize · double-click to reset`,onPointerDown:c,onPointerMove:l,onPointerUp:u,onPointerCancel:u,onDoubleClick:d})}}function zh({label:e,tabs:t,on:n,onPick:r}){return(0,A.jsx)(`nav`,{className:`ui-tabs`,"aria-label":e,children:t.map(e=>(0,A.jsxs)(`button`,{type:`button`,className:n===e.tab?`ui-tab ui-tab-on`:`ui-tab`,"aria-current":n===e.tab?`page`:void 0,onClick:()=>r(e.tab),children:[e.name,e.mark]},e.tab))})}function Bh({said:e}){return(0,A.jsxs)(Cm,{foot:(0,A.jsxs)(A.Fragment,{children:[`Your sandbox is on your machine: `,(0,A.jsx)(`span`,{className:`login-command`,children:`pinecall serve`}),` in your project's folder.`]}),children:[(0,A.jsx)(`h1`,{className:`login-title`,children:`No production access`}),(0,A.jsx)(`p`,{className:`login-lede`,children:e}),(0,A.jsx)(oh,{onClick:()=>{Km(),window.location.assign(`/`)},children:`Sign in as somebody else`})]})}var Vh=z({org:P(),slug:P().nullish(),key_id:P(),label:P().nullish(),env:V([`production`,`sandbox`]),scopes:R(P()),subject:P().nullish(),name:P().nullish(),operator:L().optional(),visiting:L().optional(),production:L()}),Hh=(0,D.createContext)(null);function Uh({children:e}){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let e=!1;return r(null),a(null),oa(t,`/v1/whoami`).then(t=>{e||r(Vh.parse(t))},t=>{!e&&t instanceof ta&&t.status===403&&a(t.message)}),()=>{e=!0}},[t]),i===null?(0,A.jsx)(Hh,{value:n,children:e}):(0,A.jsx)(Bh,{said:i})}function Wh(){return(0,D.useContext)(Hh)}function Gh(e){return e.slug??e.org}function Kh(){return Wh()?.scopes??null}var qh=(0,D.createContext)(null);function Jh({value:e,children:t}){return(0,A.jsx)(qh,{value:e,children:t})}function Yh(){let e=(0,D.useContext)(qh);if(e===null)throw Error(`the console was mounted without a world`);return e}var Xh=`ready`,Zh=`no plugin`,Qh=`no key`,$h=`its own`,eg=z({name:P(),does:R(V([`llm`,`stt`,`tts`])),aliases:R(P()),note:P(),standing:V([Xh,Zh,Qh,$h]),ready:L(),env:P().nullable(),extra:P()}),tg=[`llm`,`stt`,`tts`],ng=z({providers:R(eg),defaults:kp(P(),P()),voices:R(P()),models:kp(P(),R(P()))});async function rg(e){return ng.parse(await oa(e,`/v1/providers`))}function ig(e,t){return e.filter(e=>e.does.includes(t)).sort((e,t)=>Number(t.ready)-Number(e.ready)||e.name.localeCompare(t.name))}function ag(e){return e.standing===`no plugin`?`the box needs livekit-agents[${e.extra}]`:e.standing===`no key`?`the box needs ${e.env??`a credential`}`:e.standing===`its own`?`its credentials are its own: a profile, a pair, not one key`:e.note||`ready on this box`}var og=[`everything`,`mine`,`the team's`];function sg(e,t){let n=e.holder?.holder;return n!=null&&n!==t}function cg(e,t,n){if(t===`everything`)return e;let r=t===`the team's`;return e.filter(e=>sg(e,n)===r)}function lg(e,t){let n=new Map;for(let r of e){let e=n.get(r.slug);(e===void 0||sg(e,t)&&!sg(r,t))&&n.set(r.slug,r)}return[...n.values()]}function ug(e){let t=e.holder;return t==null?`the org's`:t.name??t.holder??`the org's`}function dg(e){return e?.subject??null}var fg=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`];function pg(e){if(e.started_at===null||e.ended_at===null)return`—`;let t=Math.max(0,Math.round(e.ended_at-e.started_at));return`${Math.floor(t/60)}m ${String(t%60).padStart(2,`0`)}s`}function mg(e,t=Date.now()/1e3){if(e===null)return`—`;let n=Math.max(0,Math.round(t-e)),r=Math.floor(n/3600),i=Math.floor(n%3600/60),a=String(n%60).padStart(2,`0`);return r>0?`${r}:${String(i).padStart(2,`0`)}:${a}`:`${i}:${a}`}function hg(e){return e==null?`—`:`${e.toFixed(4)} €`}function gg(e){return`€${e.toFixed(2)}`}function _g(e){return e===null?`—`:new Date(e*1e3).toISOString().slice(11,19)}function vg(e){if(e===null)return`—`;let t=new Date(e*1e3);return`${t.getUTCDate()} ${fg[t.getUTCMonth()]}, ${t.toISOString().slice(11,16)}`}function yg(e){if(e===null)return`—`;let t=new Date(e*1e3);return`${t.getUTCDate()} ${fg[t.getUTCMonth()]}`}function bg(e,t=Date.now()/1e3){if(e===null)return`—`;let n=Math.max(0,t-e);return n<60?`just now`:n<3600?`${Math.floor(n/60)} min ago`:n<86400?`${Math.floor(n/3600)} h ago`:n<172800?`Yesterday`:yg(e)}function xg(e){return new Date(e*1e3).toISOString().slice(0,10)}function Sg(e=Date.now()/1e3){return{today:xg(e),yesterday:xg(e-86400)}}function Cg(e,t){return e.filter(e=>e.started_at!==null&&xg(e.started_at)===t)}function wg(e,t){if(t===0)return null;let n=Math.round((e-t)/t*100);return n===0?{text:`steady`,tone:`flat`}:n>0?{text:`+${n}%`,tone:`up`}:{text:`−${Math.abs(n)}%`,tone:`down`}}function Tg(e){return`${Math.round(e*100)}%`}function Eg(e){if(e==null)return`—`;let t=e.replace(/[^\d]/g,``);return e.startsWith(`+1`)&&t.length===11?`+1 (${t.slice(1,4)}) ${t.slice(4,7)}-${t.slice(7)}`:e.startsWith(`+34`)&&t.length===11?`+34 ${t.slice(2,5)} ${t.slice(5,8)} ${t.slice(8)}`:e.startsWith(`+598`)&&t.length===11?`+598 ${t.slice(3,5)} ${t.slice(5,8)} ${t.slice(8)}`:e}function Dg(e){let t=e.caller?.name;if(t!=null&&t!==``)return t;let n=e.direction===`outbound`?e.to:e.from;return n==null?`—`:n.startsWith(`+`)?Eg(n):n}var Og=yp({day:P(),conversations:z({today:F(),yesterday:F()}),resolved_rate:F().nullable(),median_e2e_s:F().nullable(),spend_eur:F(),channels:z({phone:F(),web:F(),whatsapp:F()}),sessions_total:F(),live:F(),agents:R(z({slug:P(),today:F(),score:F().nullable()})),budget:z({limit_eur:F().nullable(),spent_eur_month:F()})}),kg=15e3;function Ag(e){let t=j(),[n,r]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i,a=async()=>{try{let i=Og.parse(await oa(t,`/v1/insights`,e===void 0?{}:{day:e}));n||r(i)}catch(e){e instanceof ta&&[403,404].includes(e.status)&&(window.clearInterval(i),n||r(null))}};return a(),i=window.setInterval(()=>void a(),kg),()=>{n=!0,window.clearInterval(i)}},[t,e]),n}function jg(){let e=j(),[t,n]=(0,D.useState)(Am===`hosted`&&null);return(0,D.useEffect)(()=>{if(Am!==`hosted`)return;let t=!1;return fetch(ua(e,`/v1/ops/whoami`),{headers:ra(e)}).then(e=>{t||n(e.ok)},()=>{t||n(!1)}),()=>{t=!0}},[e]),t}var Mg=B({seq:I(),ts:F(),call:P().nullable(),agent:P(),type:P(),ephemeral:L(),data:kp(P(),mp())});B({type:P(),agent:P(),call:P().nullable(),id:P().nullish(),data:kp(P(),mp())});var Ng=V([`phone`,`web`,`whatsapp`]),Pg=V([`inbound`,`outbound`]),Fg=V([`production`,`sandbox`]),Ig=V([`chat.roster`,`chat.start`,`chat.say`,`chat.end`,`view.render`,`simulate.start`,`goldens.roster`,`goldens.run`,`knowledge.roster`,`knowledge.push`,`knowledge.eval`,`memory.roster`,`memory.eval`,`memory.extraction`,`promote.roster`,`promote.write`,`drift.read`,`reproductions.roster`,`reproductions.read`]),Lg=V([`caller_hung_up`,`agent_hung_up`,`supervisor_ended`,`transferred`,`no_answer`,`busy`,`dial_failed`,`timeout`,`drained`,`app_detached`,`error`]),Rg=V([`caller`,`agent`,`supervisor`,`platform`]),zg=V([`held`,`broken`,`deferred`,`skipped`]),Bg=V([`cold`,`warm`]),Vg=V([`static`,`dynamic`]),Hg=V([`retrieved`,`tool`]),Ug=V([`recall`,`search`]),Wg=B({name:P().regex(/^[a-z][a-z0-9_]*$/),region:Vg}),Gg=V([`listening`,`speaking`,`away`]),Kg=V([`initializing`,`idle`,`listening`,`thinking`,`speaking`]),qg=V([`caller`,`agent`,`supervisor`,`listener`,`sip`]),Jg=V([`audio`,`video`,`screen`]),Yg=V([`microphone`,`camera`,`screen_share`,`screen_share_audio`,`unknown`]),Xg=V([`app`,`participant`]),Zg=V([`public`,`tenant`,`pii`]);V([`public`,`tenant`]);var Qg=B({id:P().nullish(),phone:P().nullish(),name:P().nullish(),email:P().nullish(),external_id:P().nullish()}),$g=B({channel:Ng,number:P().nullable(),label:P().nullish()}),e_=B({id:P(),name:P().nullish()}),t_=B({name:P(),description:P(),parameters:kp(P(),mp()),side_effect:V([`read`,`write`,`irreversible`]).nullish(),confirm:P().nullish(),pii:R(P()).nullish(),timeout_s:F().nullish()}),n_=B({call_id:P(),name:P(),output:mp().nullish(),error:P().nullish(),summary:P().nullish(),duration_s:F().nullish()}),r_=B({id:P().nullish(),text:P(),category:P().nullish(),score:F().nullish(),source:P().nullish()}),i_=B({op:V([`recall`,`remember`,`forget`]),contact:P().nullish(),query:P().nullish(),facts:R(r_),took_ms:F()}),a_=B({id:P(),base:P().nullish(),path:P(),heading:P().nullish(),score:F(),excerpt:P().nullish()}),o_=B({currency:Mp(`EUR`),usd_to_eur:F(),as_of:P()}),s_=B({provider:P(),model:P(),unit:V([`input_tokens`,`cached_input_tokens`,`cache_creation_tokens`,`output_tokens`,`characters`,`audio_seconds`,`requests`,`session_seconds`]),quantity:F(),unit_price_usd:F(),eur:F()}),c_=B({provider:P(),model:P()}),l_=B({eur:F(),rate:o_,rows:R(s_),unpriced:R(c_)}),u_=B({name:P().nullish(),provider:P().nullish(),model:P().nullish(),voice_id:P().nullish()}),d_=B({provider:P(),model:P(),temperature:F().nullish()}),f_=B({min_interruption_words:I().nullish(),endpointing_ms:I().nullish()}),p_=B({word:P(),spoken:P()}),m_=B({name:P(),visibility:Zg}),h_=B({name:P()}),g_=B({name:P(),from:R(Xg)}),__=B({path:P(),text:P()}),v_=B({base:P(),mode:Hg.nullish(),k:I().nullish(),min_score:F().nullish()}),y_=B({say:P().nullish(),reply:P().nullish(),allow_interruptions:L().nullish()}),b_=B({when:P().nullish()}),x_=B({remember:R(P()).nullish(),forget:R(P()).nullish()}),S_=B({prompt:R(Wg).nullish(),language:P().nullish(),greeting:y_.nullish(),voice:u_.nullish(),llm:d_.nullish(),stt:d_.nullish(),turn:f_.nullish(),says:R(p_).nullish(),hears:R(P()).nullish(),knowledge:__.nullish(),docs:v_.nullish(),memory:x_.nullish(),hangup:b_.nullish(),tools:R(t_).nullish(),uses_knowledge:L().nullish(),state_fields:R(m_).nullish(),view:h_.nullish(),events:R(g_).nullish()}),C_=Cp(`verb`,[B({verb:Mp(`say`),text:P()}),B({verb:Mp(`whisper`),text:P()}),B({verb:Mp(`takeover`)}),B({verb:Mp(`release`)}),B({verb:Mp(`transfer`),to:P(),mode:Bg}),B({verb:Mp(`end`),reason:P().nullish()})]);B({config:S_}),B({routes:R($g),sdk:P().nullish(),host:P().nullish(),takes_unclaimed:L().nullish()}),B({instructions:P(),allow_interruptions:L().nullish()}),B({text:P(),allow_interruptions:L().nullish()}),B({to:P(),from:P().nullish(),caller:Qg.nullish(),metadata:kp(P(),mp()).nullish()}),B({digits:P()}),B({name:P(),data:kp(P(),mp())}),B({reason:P().nullish()}),B({}),B({name:P(),data:kp(P(),mp())}),B({}),B({to:P(),mode:Bg}),B({}),B({});var w_=B({status:I(),detail:P()});B({id:P(),result:kp(P(),mp()).nullish(),refused:w_.nullish()}),B({identity:P()}),B({identity:P()}),B({}),B({name:P(),text:P()}),B({to:P(),kind:V([`sip`,`participant`])}),B({topic:P(),data:kp(P(),mp()),to:P().nullish()}),B({state:kp(P(),mp()).nullish(),config:S_.nullish()}),B({state:kp(P(),mp()),changed:R(P()).nullish()}),B({by:e_,verb:C_}),B({tools:R(t_)});var T_=B({model_name:P().nullable().nullish(),model_provider:P().nullable().nullish()}),E_=B({type:Mp(`llm_metrics`),label:P(),request_id:P(),timestamp:F(),duration:F(),ttft:F(),cancelled:L(),completion_tokens:I(),prompt_tokens:I(),prompt_cached_tokens:I(),cache_creation_tokens:I().nullish(),reasoning_tokens:I().nullish(),total_tokens:I(),tokens_per_second:F(),speech_id:P().nullable().nullish(),metadata:T_.nullable().nullish()}),D_=B({type:Mp(`stt_metrics`),label:P(),request_id:P(),timestamp:F(),duration:F(),audio_duration:F(),input_tokens:I().nullish(),output_tokens:I().nullish(),streamed:L(),acquire_time:F().nullish(),connection_reused:L().nullish(),metadata:T_.nullable().nullish()}),O_=B({type:Mp(`tts_metrics`),label:P(),request_id:P(),timestamp:F(),ttfb:F(),duration:F(),audio_duration:F(),cancelled:L(),characters_count:I(),input_tokens:I().nullish(),output_tokens:I().nullish(),streamed:L(),acquire_time:F().nullish(),connection_reused:L().nullish(),segment_id:P().nullable().nullish(),speech_id:P().nullable().nullish(),metadata:T_.nullable().nullish()}),k_=B({type:Mp(`vad_metrics`),label:P(),timestamp:F(),idle_time:F(),inference_duration_total:F(),inference_count:I(),metadata:T_.nullable().nullish()}),A_=B({type:Mp(`eou_metrics`),timestamp:F(),end_of_utterance_delay:F(),transcription_delay:F(),on_user_turn_completed_delay:F(),speech_id:P().nullable().nullish(),metadata:T_.nullable().nullish()}),j_=B({type:Mp(`eot_inference_metrics`),timestamp:F(),total_duration:F(),detection_delay:F(),prediction_duration:F(),num_requests:I().nullish(),metadata:T_.nullable().nullish()}),M_=B({type:Mp(`interruption_metrics`),timestamp:F(),total_duration:F(),prediction_duration:F(),detection_delay:F(),num_interruptions:I(),num_backchannels:I(),num_requests:I(),metadata:T_.nullable().nullish()}),N_=B({audio_tokens:I().nullish(),text_tokens:I().nullish(),image_tokens:I().nullish()}),P_=B({audio_tokens:I().nullish(),text_tokens:I().nullish(),image_tokens:I().nullish(),cached_tokens:I().nullish(),cached_tokens_details:N_.nullable().nullish()}),F_=B({text_tokens:I().nullish(),audio_tokens:I().nullish(),image_tokens:I().nullish()}),I_=B({type:Mp(`realtime_model_metrics`),label:P().nullish(),request_id:P(),timestamp:F(),duration:F().nullish(),session_duration:F().nullish(),ttft:F().nullish(),cancelled:L().nullish(),input_tokens:I().nullish(),output_tokens:I().nullish(),total_tokens:I().nullish(),tokens_per_second:F().nullish(),input_token_details:P_,output_token_details:F_,acquire_time:F().nullish(),connection_reused:L().nullish(),metadata:T_.nullable().nullish()}),L_=B({type:Mp(`avatar_metrics`),timestamp:F(),playback_latency:F().nullish(),session_started_time:F().nullable().nullish(),avatar_joined_time:F().nullable().nullish(),metadata:T_.nullable().nullish()}),R_=B({model_name:P().nullish(),model_provider:P().nullish()}),z_=B({started_speaking_at:F().nullish(),stopped_speaking_at:F().nullish(),transcription_delay:F().nullish(),end_of_turn_delay:F().nullish(),on_user_turn_completed_delay:F().nullish(),stt_metadata:R_.nullish()}),B_=B({started_speaking_at:F().nullish(),stopped_speaking_at:F().nullish(),llm_node_ttft:F().nullish(),llm_node_tps:F().nullish(),llm_node_ttfs:F().nullish(),tts_node_ttfb:F().nullish(),playback_latency:F().nullish(),e2e_latency:F().nullish(),provider_request_ids:R(P()).nullish(),llm_metadata:R_.nullish(),tts_metadata:R_.nullish()}),V_=Cp(`type`,[B({type:Mp(`llm_usage`),provider:P(),model:P(),input_tokens:I().nullish(),input_cached_tokens:I().nullish(),input_cache_creation_tokens:I().nullish(),input_audio_tokens:I().nullish(),input_cached_audio_tokens:I().nullish(),input_text_tokens:I().nullish(),input_cached_text_tokens:I().nullish(),input_image_tokens:I().nullish(),input_cached_image_tokens:I().nullish(),output_tokens:I().nullish(),output_audio_tokens:I().nullish(),output_text_tokens:I().nullish(),output_reasoning_tokens:I().nullish(),session_duration:F().nullish()}),B({type:Mp(`tts_usage`),provider:P(),model:P(),input_tokens:I().nullish(),output_tokens:I().nullish(),characters_count:I().nullish(),audio_duration:F().nullish()}),B({type:Mp(`stt_usage`),provider:P(),model:P(),input_tokens:I().nullish(),output_tokens:I().nullish(),audio_duration:F().nullish()}),B({type:Mp(`interruption_usage`),provider:P(),model:P(),total_requests:I().nullish()}),B({type:Mp(`eot_usage`),provider:P(),model:P(),total_requests:I().nullish()})]),H_=V([`idle`,`ringing`,`dialing`,`active`,`ended`]),U_=Cp(`role`,[B({role:Mp(`user`),speech_id:P(),item_id:P().nullish(),text:P(),language:P().nullish(),transcript_confidence:F().nullish(),metrics:z_}),B({role:Mp(`agent`),speech_id:P(),item_id:P().nullish(),text:P(),interrupted:L(),metrics:B_})]),W_=B({llm:R(E_),stt:R(D_),tts:R(O_),vad:R(k_),eou:R(A_),eot:R(j_),interruption:R(M_),realtime:R(I_),avatar:R(L_)}),G_=B({call_id:P(),name:P(),arguments:kp(P(),mp()),speech_id:P().nullish(),status:V([`running`,`done`,`failed`]),output:mp().nullish(),error:P().nullish(),summary:P().nullish(),duration_s:F().nullish(),seq:I()}),K_=B({hash:P(),chars:I(),seq:I()}),q_=kp(P(),K_),J_=B({tool:P(),call_id:P(),audience:P(),phrase:P(),status:V([`pending`,`granted`,`declined`]),said:P().nullish(),reason:P().nullish()}),Y_=B({active:L(),by:e_.nullable()}),X_=B({to:P(),mode:Bg,status:V([`requested`,`done`,`failed`]),by:V([`agent`,`supervisor`])}),Z_=B({user:P().nullable(),agent:P().nullable()}),Q_=B({from_seq:I(),to_seq:I()}),$_=B({seq:I(),code:P(),message:P()}),ev=B({identity:P(),kind:qg,name:P().nullish(),joined_at:F(),speaking:L(),attributes:kp(P(),mp())}),tv=B({name:P(),sid:P(),participants:R(ev),caller:P().nullable()}),nv=B({seq:I(),name:P(),source:Xg,identity:P().nullish()}),rv=B({seq:I(),name:P(),data:kp(P(),mp())}),iv=B({seq:I(),agent:P(),call:P().nullable(),status:H_,channel:Ng.nullable(),direction:Pg.nullable(),from:P().nullable(),to:P().nullable(),caller:Qg.nullable(),room:tv.nullable(),started_at:F().nullable(),ended_at:F().nullable(),end_reason:Lg.nullable(),outcome:P().nullable(),user_state:Gg.nullable(),agent_state:Kg.nullable(),live:Z_,turns:R(U_),metrics:W_,tools:R(G_),app_state:kp(P(),mp()),events:R(nv),prompt:q_,tools_visible:R(P()),confirms:R(J_),memory:R(i_),sources:R(a_),handoff:Y_,held:L(),muted:L(),transfer:X_.nullable(),usage:R(V_),cost:l_.nullable(),routes:R($g),gaps:R(Q_),errors:R($_),custom:R(rv)}),av=B({changed:R(P())}),ov=B({app:P(),env:Fg,left:L()}),sv=B({routes:R($g),app:P(),sdk:P().nullish(),env:Fg.nullish()}),cv=B({state:Kg}),lv=B({speech_id:P(),text:P(),final:L(),start:F().nullish(),end:F().nullish()}),uv=B({channel:Ng,from:P(),to:P(),run:P().nullable().nullish(),caller:Qg.nullable(),external_id:P().nullish(),asked_by:P().nullish()}),dv=B({reason:Lg,ended_by:Rg,ended_at:F(),duration_s:F()}),fv=B({held:L(),muted:L()}),pv=B({channel:Ng,from:P(),to:P(),route:$g,run:P().nullable().nullish(),caller:Qg.nullable(),external_id:P().nullish()}),mv=B({seqs:R(I()),said:P().nullish()}),hv=B({name:P(),verdict:zg,criteria:P(),reason:P(),evidence:mv}),gv=B({passed:L().nullish(),not_judged:P().nullish(),judges:R(hv),panel:R(P()).nullish(),judge_calls:I(),judge_cost_eur:F().nullish()}),_v=B({channel:Ng,direction:Pg,from:P(),to:P(),run:P().nullable().nullish(),persona:P().nullable().nullish(),caller:Qg.nullable(),started_at:F(),env:Fg.nullish()}),vv=B({reason:Lg,outcome:P(),duration_s:F(),turns:I(),usage:R(V_),cost:l_,recording:P().nullish()}),yv=B({to:P(),mode:Bg,ok:L(),error:P().nullish()}),bv=B({channel:Ng,number:P(),via:V([`overflow`,`widget`]),call:P().nullable(),contact:Qg.nullable()}),xv=B({tool:P(),call_id:P(),audience:P(),said:P().nullish(),reason:V([`no`,`timeout`,`changed`,`cancelled`])}),Sv=B({tool:P(),call_id:P(),audience:P(),said:P(),ttl_s:I()}),Cv=B({tool:P(),call_id:P(),arguments:kp(P(),mp()),audience:P(),phrase:P(),ttl_s:I()}),wv=B({org:P(),quota:V([`minutes`,`messages`,`agents`,`concurrent_calls`,`memory_facts`,`knowledge_chunks`,`numbers`,`seats`]),used:F(),limit:I()}),Tv=B({name:P(),data:kp(P(),mp())}),Ev=B({id:P(),verb:Ig,data:kp(P(),mp())}),Dv=B({query:P(),sources:R(a_),took_ms:F(),speech_id:P().nullish()}),Ov=B({code:P(),message:P(),command:P().nullish(),id:P().nullish(),recoverable:L()}),kv=B({channel:Ng,workers:I(),active:I()}),Av=B({seq:I()}),jv=B({from_seq:I(),to_seq:I(),snapshot:iv.nullable()}),Mv=B({ops:R(i_),speech_id:P().nullish()}),Nv=B({ts:F()}),Pv=B({name:P(),hash:P(),chars:I()}),Fv=Cp(`kind`,[B({kind:Mp(`tool`),tool:P(),call_id:P()}),B({kind:Mp(`event`),name:P(),seq:I()})]),Iv=B({state:kp(P(),mp()),changed:R(P()),cause:Fv.nullish()}),Lv=B({by:e_,reason:P().nullish()}),Rv=B({by:e_}),zv=B({by:e_,text:P()}),Bv=B({by:e_}),Vv=B({by:e_,to:P(),mode:Bg}),Hv=B({by:e_,text:P()}),Uv=B({call_id:P(),name:P(),arguments:kp(P(),mp()),speech_id:P().nullish()}),Wv=B({visible:R(P())}),Gv=B({speech_id:P(),item_id:P().nullish(),text:P(),interrupted:L(),metrics:B_}),Kv=B({speech_id:P(),item_id:P().nullish(),text:P(),language:P().nullish(),transcript_confidence:F().nullish(),metrics:z_}),qv=B({state:Gg}),Jv=B({text:P(),final:L(),language:P().nullish(),confidence:F().nullish()}),Yv=B({name:P(),sid:P(),channel:Ng}),Xv=B({identity:P(),kind:qg,name:P().nullish(),attributes:kp(P(),mp())}),Zv=B({identity:P(),reason:P()}),Qv=B({identity:P(),speaking:L()}),$v=B({identity:P(),kind:Jg,source:Yg}),ey=B({identity:P(),kind:Jg,source:Yg}),ty={"agent.configured":av,"agent.detached":ov,"agent.registered":sv,"agent.state":cv,"agent.transcript":lv,"call.dialing":uv,"call.ended":dv,"call.line":fv,"call.ringing":pv,"call.score":gv,"call.started":_v,"call.summary":vv,"call.transferred":yv,"callback.requested":bv,"confirm.declined":xv,"confirm.granted":Sv,"confirm.request":Cv,"credits.exhausted":wv,custom:Tv,"dev.request":Ev,"docs.sources":Dv,error:Ov,"event.received":B({name:P(),data:kp(P(),mp()),source:Xg,identity:P().nullish()}),"fleet.full":kv,"log.caught_up":Av,"log.gap":jv,"memory.ops":Mv,"metrics.avatar":L_,"metrics.eot":j_,"metrics.eou":A_,"metrics.interruption":M_,"metrics.llm":E_,"metrics.realtime":I_,"metrics.stt":D_,"metrics.tts":O_,"metrics.vad":k_,"participant.joined":Xv,"participant.left":Zv,"participant.speaking":Qv,pong:Nv,"prompt.changed":Pv,"room.opened":Yv,"room.sent":B({topic:P(),to:P().nullish(),bytes:I()}),"state.changed":Iv,"supervisor.ended":Lv,"supervisor.released":Rv,"supervisor.said":zv,"supervisor.took_over":Bv,"supervisor.transferred":Vv,"supervisor.whispered":Hv,"tool.call":Uv,"tool.result":n_,"tools.changed":Wv,"track.published":$v,"track.unpublished":ey,"turn.agent":Gv,"turn.user":Kv,"user.state":qv,"user.transcript":Jv},ny=`call.score`,ry=class extends Error{name=`ProtocolError`};function iy(e){return Mg.parse(e)}function ay(e){if(!oy(e.type))throw new ry(`unknown event type: ${e.type}`);let t=ty[e.type].parse(e.data);return{type:e.type,data:t}}function oy(e){return Object.hasOwn(ty,e)}B({state:iv,last_seq:I(),live:L()});var sy=B({entries:R(Mg),live:L(),next:I().nullable()}),cy=B({held:I(),judged:I(),passed:L(),reason:P().nullable()}),ly=V([`escalated`,`low_score`,`promise`]),uy=B({call:P(),agent:P(),live:L(),last_seq:I(),status:H_,channel:Ng.nullable(),direction:Pg.nullable(),from:P().nullable(),to:P().nullable(),caller:Qg.nullable(),started_at:F().nullable(),ended_at:F().nullable(),end_reason:Lg.nullable(),outcome:P().nullable(),cost:l_.nullable(),score:cy.nullable().nullish(),flags:R(ly).nullish()}),dy=B({calls:R(uy),total:I().nullable().nullish(),next:P().nullable().nullish()}),fy=B({today:I(),yesterday:I()}),py=B({phone:I(),web:I(),whatsapp:I()}),my=B({slug:P(),today:I(),score:F().nullable()}),hy=B({limit_eur:F().nullable(),spent_eur_month:F()});B({day:P(),timezone:P(),conversations:fy,resolved_rate:F().nullable(),median_e2e_s:F().nullable(),spend_eur:F(),channels:py,sessions_total:I(),live:I(),agents:R(my),budget:hy}),B({on:L(),ceiling_eur:F().nullable()}),B({on:L()});var gy=V([`in`,`out`,`call`]),_y=B({text:P().nullable(),at:F(),kind:gy});B({threads:R(B({contact:P(),name:P().nullable(),channel_last:Ng,last:_y,unread:I(),calls:I()})),next:P().nullable()});var vy=B({kind:gy,text:P().nullable(),at:F(),call:P(),channel:Ng,duration_s:F().nullable().nullish(),answered:L().nullable().nullish()});B({contact:P(),name:P().nullable(),messages:R(vy)}),B({text:P()}),B({contact:P(),call:P()}),B({facts:R(B({id:P(),contact:P(),text:P(),category:P().nullable(),written_at:F()})),next:P().nullable()}),B({title:P().nullable(),tagline:P().nullable(),greeting:P().nullable(),accent:P().nullable(),autostart:L()}),B({configured:L(),issuer:P().nullable(),client_id:P().nullable(),domains:R(P()),role:P().nullable(),required:L(),redirect_uri:P()}),B({issuer:P(),client_id:P(),client_secret:P(),domains:R(P()),role:P().nullable().nullish(),required:L().nullish()}),B({configured:L(),host:P().nullable(),port:I().nullable(),security:P().nullable(),username:P().nullable(),from:P().nullable(),verified_at:P().nullable(),last_error:P().nullable()}),B({host:P(),port:I(),security:V([`starttls`,`tls`,`none`]).nullish(),username:P().nullish(),password:P().nullish(),from:P()}),B({configured:L(),source:P().nullable(),host:P().nullable(),port:I().nullable(),security:P().nullable(),username:P().nullable(),from:P().nullable(),verified_at:P().nullable(),last_error:P().nullable()}),B({name:P(),logo_url:P().nullable(),accent:P()}),B({name:P().nullable().nullish(),logo_url:P().nullable().nullish(),accent:P().nullable().nullish()}),B({google:B({configured:L(),client_id:P().nullable(),redirect_uri:P()})}),B({client_id:P(),client_secret:P()}),B({sent:L(),error:P().nullable()}),B({orgs:R(B({org:P(),slug:P(),name:P()}))});var yy=B({holder:P().nullable(),name:P().nullable()}),by=B({agents:R(B({slug:P(),channels:R(Ng),holder:yy.nullable().nullish()}))}),xy=B({apps:R(B({app:P(),agents:R(P()),env:Fg,host:P().nullable(),address:P().nullable(),sdk:P().nullable(),holder:yy.nullable(),connected_at:F()}))}),Sy=B({app:P(),stopped:L()});B({agent:P(),env:Fg,held:L(),holding:yy.nullable().nullish(),yours:L(),waiting:R(yy),calling:R(P())}),B({files:R(__)}),B({questions:R(B({asks:P(),expects:P()})),k:I().nullish()});var Cy=B({asks:P(),expects:P(),found:R(P())}),wy=B({base:P(),model:P(),questions:I(),k:I(),recall_at_k:F(),ndcg_at_10:F(),took_ms:F(),misses:R(Cy)}),Ty=B({base:P(),chunks:I(),took_ms:F()}),Ey=B({bases:R(B({base:P(),chunks:I(),model:P(),pushed_at:F()}))}),Dy=B({facts:R(B({id:P().nullish(),text:P(),category:P().nullish(),source:P().nullish(),valid_from:F(),invalidated_at:F().nullable()}))}),Oy=B({forgotten:I()});B({questions:R(B({holds:R(P()),asks:P(),expects:R(P())})),k:I().nullish()});var ky=B({asks:P(),missing:R(P()),found:R(P())}),Ay=B({model:P(),questions:I(),k:I(),recall_at_k:F(),ndcg_at_10:F(),took_ms:F(),misses:R(ky)}),jy=B({writes:R(P()).nullish(),never:R(P()).nullish(),never_says:R(P()).nullish(),invalidates:R(P()).nullish()});B({cases:R(B({name:P(),said:R(Dp([P(),P()])),holds:R(P()).nullish(),plants:R(P()).nullish(),channel:Ng.nullish(),expect:jy.nullish()}))});var My=B({check:P(),detail:P()}),Ny=B({name:P(),held:L(),wrote:R(P()).nullish(),refused:R(P()).nullish(),broke:R(My).nullish()}),Py=B({agent:P(),model:P(),cases:I(),held:I(),took_ms:F(),results:R(Ny)});B({tool:Ug,input:kp(P(),mp()),speech_id:P().nullish()}),B({output:kp(P(),mp()),took_ms:F()}),B({chunks:R(B({path:P(),heading:P().nullable(),text:P()}))}),B({ops:I(),took_ms:F()}),B({call:P(),agent:P(),to:P(),from:P(),env:Fg});var Fy=B({dial_anywhere:L(),per_minute:I(),per_day:I(),max_duration_s:I()});B({ready:L(),kind:P().nullable(),from_numbers:R(P()),steps_missing:R(P()),guards:Fy}),B({steps:R(P()),dry_run:L(),ready:L(),trunk:P().nullish(),address:P().nullish()});var Iy=B({voice:P().nullish(),tts:P().nullish(),tts_model:P().nullish(),stt:P().nullish(),llm:P().nullish(),greeting:y_.nullish(),hangup:b_.nullish(),turn:f_.nullish(),memory:x_.nullish(),knowledge:P().nullish(),bases:R(v_).nullish()}),Ly=B({holder:P(),version:I(),author:P(),note:P().nullable(),set_at:F(),config:Iy}),Ry=B({world:Fg,yours:Ly.nullable(),team:Ly.nullable(),production:Ly.nullable()});B({config:Iy,if_version:I().nullable().nullish(),note:P().nullable().nullish(),team:L().nullish()});var zy=B({world:Fg,holder:P(),rows:R(Ly)});B({ours:Ly.nullable(),theirs:Ly.nullable(),changed:R(P())}),B({version:I(),team:L().nullish()});var By=B({said:R(p_),heard:R(P())}),Vy=B({holder:P(),version:I(),author:P(),note:P().nullable(),set_at:F(),lexicon:By}),Hy=B({world:Fg,yours:Vy.nullable(),team:Vy.nullable(),production:Vy.nullable()});B({lexicon:By,if_version:I().nullable().nullish(),note:P().nullable().nullish(),team:L().nullish()}),B({world:Fg,holder:P(),rows:R(Vy)}),B({config_version:I().nullable(),lexicon_version:I().nullable(),config:Ly.nullable(),lexicon:Vy.nullable()});var Uy=B({path:P(),chars:I(),chunks:I(),pushed_at:F()}),Wy=B({base:P(),kept:L(),files:R(Uy)}),Gy=B({path:P(),text:P(),chunks:I(),pushed_at:F()});B({text:P()});var Ky=B({base:P(),path:P(),chunks:I(),took_ms:F()}),qy=B({bases:R(B({base:P(),agents:R(P())}))}),Jy=B({personas:R(B({name:P(),about:P(),goal:P(),style:P(),facts:kp(P(),P()),state:kp(P(),mp()),author:P(),set_at:F()}))});B({about:P().nullish(),goal:P(),style:P(),facts:kp(P(),P()).nullish(),state:kp(P(),mp()).nullish(),was:P().nullish()});var Yy=B({runs:R(B({call:P(),agent:P(),started_at:F(),ended_at:F().nullable(),turns:I(),end_reason:Lg.nullable(),outcome:P().nullable(),cost_eur:F().nullable(),score:cy.nullable()})),total:I(),next:P().nullable()}),Xy={acquire_time:`s`,audio_duration:`s`,audio_tokens:`tokens`,avatar_joined_time:`unix s`,cache_creation_tokens:`tokens`,cached_tokens:`tokens`,cached_tokens_details:`object`,cancelled:`flag`,characters_count:`chars`,completion_tokens:`tokens`,connection_reused:`flag`,detection_delay:`s`,duration:`s`,e2e_latency:`s`,end_of_turn_delay:`s`,end_of_utterance_delay:`s`,idle_time:`s`,image_tokens:`tokens`,inference_count:`count`,inference_duration_total:`s`,input_audio_tokens:`tokens`,input_cache_creation_tokens:`tokens`,input_cached_audio_tokens:`tokens`,input_cached_image_tokens:`tokens`,input_cached_text_tokens:`tokens`,input_cached_tokens:`tokens`,input_image_tokens:`tokens`,input_text_tokens:`tokens`,input_token_details:`object`,input_tokens:`tokens`,label:`name`,llm_metadata:`object`,llm_node_tps:`tokens/s`,llm_node_ttfs:`s`,llm_node_ttft:`s`,metadata:`object`,model:`name`,model_name:`name`,model_provider:`name`,num_backchannels:`count`,num_interruptions:`count`,num_requests:`count`,on_user_turn_completed_delay:`s`,output_audio_tokens:`tokens`,output_reasoning_tokens:`tokens`,output_text_tokens:`tokens`,output_token_details:`object`,output_tokens:`tokens`,playback_latency:`s`,prediction_duration:`s`,prompt_cached_tokens:`tokens`,prompt_tokens:`tokens`,provider:`name`,provider_request_ids:`ids`,reasoning_tokens:`tokens`,request_id:`id`,segment_id:`id`,session_duration:`s`,session_started_time:`unix s`,speech_id:`id`,started_speaking_at:`unix s`,stopped_speaking_at:`unix s`,streamed:`flag`,stt_metadata:`object`,text_tokens:`tokens`,timestamp:`unix s`,tokens_per_second:`tokens/s`,total_duration:`s`,total_requests:`count`,total_tokens:`tokens`,transcription_delay:`s`,ttfb:`s`,ttft:`s`,tts_metadata:`object`,tts_node_ttfb:`s`,type:`tag`};function Zy(e){let t=Qy();for(let n of e)t=tb(t,n);return t}function Qy(){return{seq:0,agent:``,call:null,status:`idle`,channel:null,direction:null,from:null,to:null,caller:null,room:null,started_at:null,ended_at:null,end_reason:null,outcome:null,user_state:null,agent_state:null,live:{user:null,agent:null},turns:[],metrics:{llm:[],stt:[],tts:[],vad:[],eou:[],eot:[],interruption:[],realtime:[],avatar:[]},tools:[],app_state:{},events:[],prompt:{},tools_visible:[],confirms:[],memory:[],sources:[],handoff:{active:!1,by:null},held:!1,muted:!1,transfer:null,usage:[],cost:null,routes:[],gaps:[],errors:[],custom:[]}}var $y=`unreadable`;function eb(e,t,n){let r=n instanceof Error?n.message:String(n);return e.errors.push({seq:t.seq,code:$y,message:`${t.type} at seq ${t.seq} is not the shape this reader knows: ${r.split(`
60
+ `)[0]?.trim()??r}`}),e}function tb(e,t){let n;try{n=ay(t)}catch(n){let r=eb(e,t,n);return r.seq=t.seq,r.agent=t.agent,t.call!==null&&(r.call=t.call),r}let r=e;return n.type===`log.gap`?r=lb(e,n):nb(e,t,n),r.seq=t.seq,r.agent=t.agent,t.call!==null&&(r.call=t.call),r}function nb(e,t,n){switch(n.type){case`call.ringing`:e.status=`ringing`,e.direction=`inbound`,rb(e,n.data);return;case`call.dialing`:e.status=`dialing`,e.direction=`outbound`,rb(e,n.data);return;case`call.started`:e.status=`active`,e.direction=n.data.direction,e.started_at=n.data.started_at,rb(e,n.data);return;case`call.ended`:e.status=`ended`,e.ended_at=n.data.ended_at,e.end_reason=n.data.reason,e.live={user:null,agent:null};return;case`call.transferred`:e.transfer={to:n.data.to,mode:n.data.mode,status:n.data.ok?`done`:`failed`,by:e.transfer?.by??`agent`};return;case`call.line`:e.held=n.data.held,e.muted=n.data.muted;return;case`call.summary`:e.usage=[...n.data.usage],e.cost=n.data.cost,e.outcome=n.data.outcome,e.end_reason??=n.data.reason;return;case`user.state`:e.user_state=n.data.state;return;case`agent.state`:e.agent_state=n.data.state;return;case`user.transcript`:e.live.user=n.data.final?null:n.data.text;return;case`agent.transcript`:e.live.agent=n.data.final?null:db(e.live.agent,n.data);return;case`turn.user`:e.turns.push({role:`user`,...n.data}),e.live.user=null;return;case`turn.agent`:e.turns.push({role:`agent`,...n.data}),e.live.agent=null;return;case`memory.ops`:e.memory.push(...n.data.ops);return;case`docs.sources`:e.sources=[...n.data.sources];return;case`metrics.llm`:e.metrics.llm.push(n.data);return;case`metrics.stt`:e.metrics.stt.push(n.data);return;case`metrics.tts`:e.metrics.tts.push(n.data);return;case`metrics.vad`:e.metrics.vad.push(n.data);return;case`metrics.eou`:e.metrics.eou.push(n.data);return;case`metrics.eot`:e.metrics.eot.push(n.data);return;case`metrics.interruption`:e.metrics.interruption.push(n.data);return;case`metrics.realtime`:e.metrics.realtime.push(n.data);return;case`metrics.avatar`:e.metrics.avatar.push(n.data);return;case`tool.call`:e.tools.push({...n.data,status:`running`,seq:t.seq});return;case`tool.result`:ib(e,n.data);return;case`state.changed`:e.app_state={...n.data.state};return;case`prompt.changed`:e.prompt[n.data.name]={hash:n.data.hash,chars:n.data.chars,seq:t.seq};return;case`tools.changed`:e.tools_visible=[...n.data.visible];return;case`confirm.request`:e.confirms.push({tool:n.data.tool,call_id:n.data.call_id,audience:n.data.audience,phrase:n.data.phrase,status:`pending`});return;case`confirm.granted`:ab(e,n.data.call_id,{status:`granted`,said:n.data.said});return;case`confirm.declined`:ab(e,n.data.call_id,{status:`declined`,reason:n.data.reason,...n.data.said===void 0?{}:{said:n.data.said}});return;case`supervisor.took_over`:e.handoff={active:!0,by:n.data.by};return;case`supervisor.released`:e.handoff={active:!1,by:null};return;case`supervisor.transferred`:e.transfer={to:n.data.to,mode:n.data.mode,status:`requested`,by:`supervisor`};return;case`agent.registered`:e.routes=[...n.data.routes];return;case`error`:e.errors.push({seq:t.seq,code:n.data.code,message:n.data.message});return;case`custom`:e.custom.push({seq:t.seq,name:n.data.name,data:{...n.data.data}});return;case`room.opened`:e.room={name:n.data.name,sid:n.data.sid,participants:[],caller:null};return;case`participant.joined`:ob(e,t,n.data);return;case`participant.left`:sb(e,n.data.identity);return;case`participant.speaking`:{let t=cb(e,n.data.identity);t!==void 0&&(t.speaking=n.data.speaking);return}case`event.received`:{let{data:r,...i}=n.data;e.events.push({...i,seq:t.seq});return}case`track.published`:case`track.unpublished`:case`room.sent`:case`supervisor.said`:case`supervisor.whispered`:case`supervisor.ended`:case`agent.configured`:case`pong`:case`log.caught_up`:case`log.gap`:return}}function rb(e,t){e.channel=t.channel,e.from=t.from,e.to=t.to,e.caller=t.caller}function ib(e,t){let n=ub(e.tools,e=>e.call_id===t.call_id);if(n===-1)return;let{call_id:r,name:i,...a}=t,o=e.tools[n];e.tools[n]={...o,...a,status:a.error===void 0?`done`:`failed`}}function ab(e,t,n){let r=ub(e.confirms,e=>e.call_id===t);if(r===-1)return;let i=e.confirms[r];e.confirms[r]={...i,...n}}function ob(e,t,n){e.room!==null&&(e.room.participants.push({...n,joined_at:t.ts,speaking:!1}),n.kind===`caller`&&(e.room.caller=n.identity))}function sb(e,t){if(e.room===null)return;let n=e.room.participants.findIndex(e=>e.identity===t);n!==-1&&e.room.participants.splice(n,1),e.room.caller===t&&(e.room.caller=null)}function cb(e,t){return e.room?.participants.find(e=>e.identity===t)}function lb(e,t){let n=t.data.snapshot===null?e:structuredClone(t.data.snapshot);return n.gaps.push({from_seq:t.data.from_seq,to_seq:t.data.to_seq}),n}function ub(e,t){for(let n=e.length-1;n>=0;--n)if(t(e[n]))return n;return-1}function db(e,t){if(e===null||e===``)return t.text;let n=/\s$/.test(e)||/^\s/.test(t.text);return t.start!=null&&!n?`${e} ${t.text}`:`${e}${t.text}`}var fb=500,pb=8e3,mb=204,hb=class{#e=``;#t=null;#n=null;#r=[];feed(e){this.#e+=e;let t=[],n;for(;(n=this.#e.search(/\r\n|\n|\r/))!==-1;){let e=this.#e.slice(0,n);this.#e=this.#e.slice(n+(this.#e.startsWith(`\r
61
+ `,n)?2:1));let r=this.#i(e);r!==null&&t.push(r)}return t}#i(e){if(e===``){if(this.#r.length===0&&this.#n===null&&this.#t===null)return null;let e={id:this.#t,event:this.#n,data:this.#r.join(`
62
+ `)};return this.#n=null,this.#r=[],e}if(e.startsWith(`:`))return null;let t=e.indexOf(`:`),n=t===-1?e:e.slice(0,t),r=t===-1?``:e.slice(t+1).replace(/^ /,``);return n===`id`?this.#t=r:n===`event`?this.#n=r:n===`data`&&this.#r.push(r),null}};function gb(e,t,n){let r=new AbortController,i=null,a=null,o=fb,s=!0,c=()=>{i===null&&(i=window.setTimeout(()=>{i=null,n.onPaint()},100))},l=e=>{if(e.id!==null&&(a=e.id),e.data!==``){try{n.onEntry(iy(JSON.parse(e.data)))}catch(e){n.onRefused(String(e));return}c()}};return n.onConnection(`connecting`),(async()=>{for(;s;){let i;try{i=await fetch(e,{headers:{...ra(t),accept:`text/event-stream`,...a===null?{}:{"last-event-id":a}},signal:r.signal})}catch{if(!s)return;n.onConnection(`reconnecting`),await _b(o,r.signal),o=Math.min(o*2,pb);continue}if(i.status===mb){n.onConnection(`ended`);return}if(!i.ok||i.body===null){n.onRefused(`the stream answered ${i.status}`),n.onConnection(`ended`);return}n.onConnection(`live`),o=fb;let c=new hb,u=new TextDecoder,d=i.body.getReader();try{for(;;){let{value:e,done:t}=await d.read();if(t)break;for(let t of c.feed(u.decode(e,{stream:!0})))l(t)}}catch{if(!s)return}if(!s)return;n.onConnection(`reconnecting`),await _b(o,r.signal),o=Math.min(o*2,pb)}})(),()=>{s=!1,i!==null&&window.clearTimeout(i),r.abort()}}function _b(e,t){return new Promise(n=>{let r=window.setTimeout(n,e);t.addEventListener(`abort`,()=>{window.clearTimeout(r),n()},{once:!0})})}var vb=3e3;function yb(e=50){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(`connecting`),[o,s]=(0,D.useState)(0),[c,l]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i=async()=>{try{let i=dy.parse(await oa(t,`/v1/sessions`,{limit:e}));n||(r(i.calls),l(null))}catch(e){n||l(String(e))}};i();let o=window.setInterval(()=>void i(),vb),c=gb(ua(t,`/v1/events`),t,{onEntry(e){(e.type===`agent.registered`||e.type===`agent.detached`)&&s(e=>e+1),i()},onPaint:()=>void 0,onConnection:a,onRefused:l});return()=>{n=!0,window.clearInterval(o),c()}},[t,e]),{lines:n,connection:i,agentsChanged:o,error:c}}function bb(e=0){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{let e=!1;return(async()=>{try{let n=by.parse(await oa(t,`/v1/agents`));e||(r(n.agents),a(null))}catch(t){e||a(String(t))}finally{e||s(!0)}})(),()=>{e=!0}},[t,e]),{agents:n,error:i,loaded:o}}var xb=200,Sb=(0,D.createContext)(null);function Cb({children:e}){let t=j(),n=Wh(),r=yb(xb),i=Ag(),a=jg(),o=bb(r.agentsChanged),[s,c]=(0,D.useState)(null);(0,D.useEffect)(()=>{let e=!1;return lm(t).then(t=>{e||c(t)},()=>{e||c(null)}),()=>{e=!0}},[t]);let l=dg(n),u=(0,D.useMemo)(()=>({lines:r.lines,live:r.lines.filter(e=>e.live),connection:r.connection,floorError:r.error,held:o.agents,agents:lg(o.agents,l),agentsLoaded:o.loaded,agentsError:o.error,orgs:s,here:s?.find(e=>e.here)??null,insights:i,operator:a}),[r.lines,r.connection,r.error,o.agents,o.loaded,o.error,s,l,i,a]);return(0,A.jsx)(Sb,{value:u,children:e})}function wb(){let e=(0,D.useContext)(Sb);if(e===null)throw Error(`a screen was mounted outside the shell's org`);return e}var Tb={talk:`talk`,devchat:`talk`,calls:`calls`,sessions:`calls`,pipeline:`pipeline`,settings:`words`,lexicon:`words`,docs:`knowledge`,memory:`memory`,evals:`evals`,widget:`talk`,agents:`calls`,live:`calls`,"org-evals":`evals`,personas:`evals`,simulations:`evals`,"org-memory":`memory`,"org-docs":`knowledge`,numbers:`numbers`,providers:`providers`,team:`team`,usage:`usage`};function Eb(e,t){let n=Tb[t];return n===void 0||e.includes(n)}var Db=[`app`,`calls`,`evals`,`keys`,`knowledge`,`memory`,`numbers`,`pipeline`,`providers`,`supervise`,`talk`,`team`,`usage`,`words`];function Ob(e){let t=Db.filter(t=>!e.includes(t));return t.length===0||t.length===1&&t[0]===`app`?`everything`:e.join(`, `)}var kb=z({fingerprint:P(),label:P().nullable(),kind:V([`person`,`server`]),env:V([`production`,`sandbox`]).nullable(),name:P().nullable(),created_by:P().nullable(),created_at:P(),last_used_at:P().nullable(),revoked_at:P().nullable(),scopes:R(P())}),Ab=z({key:P(),key_id:P(),label:P().nullable(),env:P(),scopes:R(P())});async function jb(e){return R(kb).parse(await oa(e,`/v1/keys`))}async function Mb(e,t){return Ab.parse(await ca(e,`/v1/keys`,t))}async function Nb(e,t){await ca(e,`/v1/keys/${encodeURIComponent(t)}/revoke`,{})}async function Pb(e){return xy.parse(await oa(e,`/v1/apps`)).apps}async function Fb(e,t){Sy.parse(await ca(e,`/v1/apps/${encodeURIComponent(t)}/stop`,{}))}function Ib({held:e,stops:t}){let n=j(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null);(0,D.useEffect)(()=>{let e=!1;return Pb(n).then(t=>{e||i(t)},t=>{e||o(t instanceof Error?t.message:String(t))}),()=>{e=!0}},[n,e]);let s=async e=>{o(null);try{await Fb(n,e),i(await Pb(n))}catch(e){o(e instanceof ta?e.message:String(e))}};return r===null&&a===null?null:(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Processes`,meta:`the machines holding these agents — a stop closes one, and it exits instead of dialling back`}),(0,A.jsx)($m,{children:a}),(0,A.jsxs)(`div`,{className:`ui-card-list`,children:[r?.length===0&&(0,A.jsx)(`div`,{className:`agents-none`,children:`No process is connected.`}),r?.map(e=>(0,A.jsx)(Lb,{app:e,stop:t?s:void 0},e.app))]})]})}function Lb({app:e,stop:t}){let[n,r]=(0,D.useState)(!1),i=e.holder===null?`the org's`:e.holder.name??e.holder.holder??``,a=`${e.host??`an unnamed host`}${e.address===null?``:` (${e.address})`}`;return(0,A.jsx)(`div`,{onMouseLeave:()=>r(!1),children:(0,A.jsx)(th,{name:e.agents.join(`, `)||e.app,sub:`${a} · ${e.sdk??`an unknown sdk`} · ${i} · connected ${bg(e.connected_at)}`,end:t!==void 0&&(0,A.jsx)(oh,{danger:!0,onClick:()=>n?void t(e.app):r(!0),children:n?`Stop it`:`Stop`})})})}var Rb=z({route:z({org:P(),agent:P(),channel:V([`phone`,`web`,`whatsapp`]),number:P().nullable(),label:P().nullable(),env:V([`production`,`sandbox`]),managed:L().default(!1)}),source:V([`operator`,`app`])}),zb=z({kind:V([`twilio`,`sip`]),account:P()}),Bb=z({kind:V([`twilio`,`sip`]),numbers:R(z({number:P(),name:P(),imported:L()}))}),Vb=z({route:Rb.shape.route,steps:R(P()),dry_run:L()});async function Hb(e){return R(Rb).parse(await oa(e,`/v1/numbers`))}async function Ub(e){try{return zb.parse(await oa(e,`/v1/carrier`))}catch(e){if(nx(e,404))return null;throw e}}async function Wb(e,t){await sa(e,`/v1/carrier`,t)}async function Gb(e){await la(e,`/v1/carrier`)}async function Kb(e){return Bb.parse(await oa(e,`/v1/numbers/available`))}async function qb(e,t,n){return Vb.parse(await ca(e,`/v1/numbers${n?`?dry_run=true`:``}`,t))}async function Jb(e,t,n){return Vb.parse(await ca(e,`/v1/numbers/buy${n?`?dry_run=true`:``}`,t))}async function Yb(e,t){await la(e,`/v1/numbers/${encodeURIComponent(t)}`)}var Xb=yp({ready:L(),kind:P().nullish(),from_numbers:R(P()),steps_missing:R(P()),guards:yp({dial_anywhere:L(),per_minute:F(),per_day:F(),max_duration_s:F()})}),Zb=yp({steps:R(P()),dry_run:L(),ready:L()});async function Qb(e){try{return Xb.parse(await oa(e,`/v1/carrier/outbound`))}catch(e){if(nx(e,404)||nx(e,405)||nx(e,403))return null;throw e}}async function $b(e,t){return Zb.parse(await ca(e,`/v1/carrier/outbound${t?`?dry_run=true`:``}`,{}))}var ex=yp({call:P()});async function tx(e,t,n,r){let i=r===void 0||r===``?{to:n}:{to:n,from:r};return ex.parse(await ca(e,`/v1/agents/${encodeURIComponent(t)}/dial`,i)).call}function nx(e,t){return typeof e==`object`&&!!e&&e.status===t}var rx=z({vendors:R(P())});async function ix(e){return rx.parse(await oa(e,`/v1/provider-keys`)).vendors}async function ax(e,t,n){await sa(e,`/v1/provider-keys/${encodeURIComponent(t)}`,{key:n})}async function ox(e,t){await la(e,`/v1/provider-keys/${encodeURIComponent(t)}`)}var sx=`minmax(0,1.5fr) minmax(0,1.3fr) minmax(0,1.1fr) 90px 90px`;function cx(){let e=j(),t=Kh(),[n,r]=(0,D.useState)({numbers:null,free:null,keys:null,catalogue:null,brought:[]}),i=e=>Bm(Im,e)&&t!==null&&Eb(t,e),a=i(`numbers`),o=Bm(Im,`tokens`),s=i(`providers`);return(0,D.useEffect)(()=>{let t=!1;return(async()=>{let[n,i,c,l,u]=await Promise.all([a?Hb(e).catch(()=>null):Promise.resolve(null),a?Kb(e).catch(()=>null):Promise.resolve(null),o?jb(e).catch(()=>null):Promise.resolve(null),s?rg(e).catch(()=>null):Promise.resolve(null),s?ix(e).catch(()=>[]):Promise.resolve([])]);t||r({numbers:n,free:i===null?null:i.numbers.filter(e=>!e.imported).length,keys:c,catalogue:l,brought:u})})(),()=>{t=!0}},[e,a,o,s]),n}function lx(){let{held:e,agents:t,live:n,lines:r,connection:i,agentsError:a,agentsLoaded:o,insights:s}=wb(),c=dg(Wh()),l=Kh(),u=cx(),[d,f]=(0,D.useState)(`everything`),p=Cg(r,Sg().today),m=e.some(e=>sg(e,c)),h=m?cg(e,d,c):t,g=new Set((u.numbers??[]).map(e=>e.route.agent)),_=new Set([...t.map(e=>e.slug),...g]),v=e=>(u.numbers??[]).filter(t=>t.route.agent===e&&t.route.number!==null).map(e=>Eg(e.route.number)),y=u.keys?.filter(e=>e.revoked_at===null)??[],b=u.catalogue?.providers.filter(e=>e.standing===`ready`)??[],x=Am===`hosted`&&l!==null&&l.includes(`app`);return(0,A.jsxs)(Dh,{children:[(0,A.jsx)(Oh,{title:`Overview`,lede:`Which agents this gateway is holding right now — the list changes the moment a socket connects.`,actions:x?(0,A.jsx)(ah,{to:`/tokens`,size:`base`,children:`New server token`}):void 0}),(0,A.jsxs)(kh,{min:170,children:[(0,A.jsx)(Ah,{label:`Agents up`,value:t.length,of:`of ${_.size}`}),u.numbers===null?(0,A.jsx)(Ah,{label:`Calls live`,value:n.length}):(0,A.jsx)(Ah,{label:`Numbers ringing`,value:u.numbers.filter(e=>e.route.number!==null).length,of:u.free===null?void 0:`· ${u.free} free`}),u.keys===null?(0,A.jsx)(Ah,{label:`Calls today`,value:p.length}):(0,A.jsx)(Ah,{label:`Active tokens`,value:y.length,of:`· ${u.keys.length-y.length} revoked`}),u.catalogue!==null&&(0,A.jsx)(Ah,{label:`Providers ready`,value:b.length,of:`of ${u.catalogue.providers.length}`})]}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Agents`,meta:`the list changes the moment a socket connects`,action:(0,A.jsxs)(`span`,{className:`agents-watching`,children:[(0,A.jsx)(bh,{tone:i===`live`?`green`:void 0,small:!0}),i===`live`?`watching`:i]}),children:m&&(0,A.jsx)(`div`,{className:`agents-corners`,children:(0,A.jsx)(fh,{options:og.map(e=>({value:e,label:e})),value:d,onChange:f})})}),(0,A.jsx)($m,{children:a}),o&&h.length===0&&(0,A.jsx)(Qm,{children:d===`everything`?Am===`local`?(0,A.jsxs)(A.Fragment,{children:[`Nothing of yours is running. `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` in a project puts its agents here.`]}):(0,A.jsxs)(A.Fragment,{children:[`Nothing is running in production: `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start --prod`}),` on your server holds it, on a server token.`]}):(0,A.jsxs)(A.Fragment,{children:[`Nothing here is `,d,`.`]})}),h.length>0&&(0,A.jsx)(jh,{columns:sx,padding:`9px 16px`,labels:[`Agent`,`Doors`,`Numbers`,`Today>`,`Score>`]}),h.map((e,t)=>{let i=n.filter(t=>t.agent===e.slug).length,a=r.find(t=>t.agent===e.slug),o=v(e.slug);return(0,A.jsxs)(Mh,{columns:sx,padding:`13px 16px`,to:`/a/${e.slug}/talk`,children:[(0,A.jsxs)(`div`,{className:`agents-name`,children:[(0,A.jsx)(Th,{name:e.slug,letters:e.slug.slice(0,1).toUpperCase(),tint:Sh(t)}),(0,A.jsxs)(`div`,{style:{minWidth:0},children:[(0,A.jsx)(`div`,{className:`ui-cell-strong ui-clip`,children:e.slug}),i>0?(0,A.jsxs)(`div`,{className:`agents-live`,children:[(0,A.jsx)(bh,{tone:`green`,small:!0}),i===1?`1 call live`:`${i} calls live`]}):(0,A.jsxs)(`div`,{className:`agents-idle`,children:[m?`${ug(e)} · `:``,`idle`,a===void 0?``:` · last call ${bg(a.started_at)}`]})]})]}),(0,A.jsx)(`div`,{className:`ui-tags`,children:e.channels.map(e=>(0,A.jsx)(yh,{children:e},e))}),(0,A.jsx)(`span`,{className:`agents-numbers ui-clip`,children:o.length===0?`—`:o.join(`, `)}),(0,A.jsx)(`span`,{className:`agents-figure`,children:s?.agents.find(t=>t.slug===e.slug)?.today??p.filter(t=>t.agent===e.slug).length}),(0,A.jsx)(fx,{share:s?.agents.find(t=>t.slug===e.slug)?.score??null})]},`${e.slug}/${e.holder?.holder??``}`)}),h.length>0&&(0,A.jsx)(Zm,{children:(0,A.jsx)(`span`,{children:h.length>1?`Every agent writes the same log — open one to read its turns.`:`Open the agent to read its turns.`})})]}),(0,A.jsx)(Ib,{held:e,stops:l!==null&&l.includes(`app`)}),(u.keys!==null||u.catalogue!==null)&&(0,A.jsxs)(`div`,{className:`agents-split`,children:[u.keys!==null&&(0,A.jsx)(ux,{tokens:u.keys}),u.catalogue!==null&&(0,A.jsx)(dx,{catalogue:u.catalogue,brought:u.brought})]})]})}function ux({tokens:e}){let t=[...e].sort((e,t)=>Number(e.revoked_at!==null)-Number(t.revoked_at!==null)).slice(0,4);return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Tokens in use`,action:(0,A.jsx)(Xm,{to:`/tokens`,children:`Manage`})}),(0,A.jsxs)(`div`,{className:`ui-card-list`,children:[t.length===0&&(0,A.jsx)(`div`,{className:`agents-none`,children:`No token has been made yet.`}),t.map(e=>(0,A.jsx)(th,{name:e.label??e.fingerprint,sub:e.kind===`person`?`${e.name??`a person`} · their own`:`the org's · ${e.env??``}${e.created_by===null?``:` · made by ${e.created_by}`}`,end:e.revoked_at===null?(0,A.jsx)(vh,{tone:`green`,children:`active`}):(0,A.jsx)(vh,{tone:`muted`,children:`revoked`})},e.fingerprint))]})]})}function dx({catalogue:e,brought:t}){let n=e.providers.filter(e=>e.standing===Xh),r=new Set(Object.values(e.defaults).map(e=>e.split(`/`)[0]??e)),i=[...n].sort((e,n)=>Number(t.includes(n.name))-Number(t.includes(e.name))||Number(r.has(n.name))-Number(r.has(e.name))||e.name.localeCompare(n.name));return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Providers`,meta:`${n.length} ready · ${e.providers.length-n.length} need a key`,action:(0,A.jsx)(Xm,{to:`/providers`,children:`Bring one`})}),(0,A.jsx)(`div`,{className:`ui-card-list`,children:i.slice(0,4).map(n=>(0,A.jsx)(th,{name:n.name.charAt(0).toUpperCase()+n.name.slice(1),sub:mx(n,e),end:t.includes(n.name)?(0,A.jsx)(vh,{tone:`green`,children:`ready`}):(0,A.jsx)(vh,{tone:`amber`,children:`box key`})},n.name))})]})}function fx({share:e}){return e===null?(0,A.jsx)(`span`,{className:`agents-figure agents-score`,children:`—`}):(0,A.jsxs)(`span`,{className:`agents-figure ${e>=.9?`agents-score-good`:e>=.7?`agents-score-fair`:`agents-score-poor`}`,children:[Math.round(e*100),`%`]})}var px={llm:`decides`,stt:`hears`,tts:`speaks`};function mx(e,t){let n=e.does.filter(n=>(t.defaults[n]??``).split(`/`)[0]===e.name);return n.length>0?`${n.map(e=>px[e]).join(`, `)} · the default`:`${e.does.map(e=>px[e]).join(`, `)} · ${e.note}`}var hx=`/v1/ops`,gx=yp({worker:P(),active:F(),max_jobs:F().nullish(),load:F(),draining:L(),cordoned:L(),seen_at:F()}),_x=yp({now:F(),stale_after_s:F(),workers:R(gx)}),vx=yp({route:yp({agent:P(),channel:P(),number:P().nullish(),env:P(),managed:L().nullish()}),source:P()}),yx=yp({cursor:F(),org:P(),agent:P(),call:P(),type:P(),at:F(),minutes:F(),messages:F(),cost_eur:F()}),bx=yp({minutes:F(),messages:F(),input_tokens:F(),output_tokens:F(),characters:F()}),xx=yp({rows:R(yx),totals:kp(P(),bx),next:F().nullish()});async function Sx(e){return _x.parse(await oa(e,`${hx}/fleet`))}async function Cx(e,t,n){let r=`${hx}/fleet/${encodeURIComponent(t)}/cordon`;await(n?ca(e,r,{}):la(e,r))}async function wx(e,t,n){return R(vx).parse(await oa(e,`${hx}/routes`,{org:t,env:n}))}async function Tx(e,t){return yp({overrides:P().nullish()}).parse(await ca(e,`${hx}/routes`,t)).overrides??null}async function Ex(e,t,n){await la(e,`${hx}/routes/${encodeURIComponent(n)}?org=${encodeURIComponent(t)}`)}async function Dx(e,t,n){return xx.parse(await oa(e,`${hx}/usage`,{after:t,limit:n}))}function Ox(e){let[t,n]=(0,D.useState)(void 0),[r,i]=(0,D.useState)(null),a=(0,D.useCallback)(async()=>{try{n(await e()),i(null)}catch(e){i(kx(e))}},[e]);return(0,D.useEffect)(()=>{let t=!1;return e().then(e=>{t||n(e)},e=>{t||i(kx(e))}),()=>{t=!0}},[e]),{value:t,refused:r,reread:a}}function kx(e){return e instanceof ta||e instanceof Error?e.message:String(e)}function Ax(){let[e,t]=(0,D.useState)(!1),[n,r]=(0,D.useState)(null);return{busy:e,refused:n,move:(0,D.useCallback)(async e=>{t(!0),r(null);try{return await e(),!0}catch(e){return r(kx(e)),!1}finally{t(!1)}},[])}}var jx=5e3,Mx=`minmax(0,1.4fr) 150px 130px 120px 90px`;function Nx(){let e=j(),t=Ox((0,D.useCallback)(()=>Sx(e),[e])),n=Ax(),{reread:r}=t;(0,D.useEffect)(()=>{let e=window.setInterval(()=>void r(),jx);return()=>window.clearInterval(e)},[r]);let i=t.value,a=e=>i!==void 0&&i.now-e.seen_at>i.stale_after_s,o=(i?.workers??[]).filter(e=>!a(e)&&!e.cordoned&&!e.draining),s=(i?.workers??[]).reduce((e,t)=>e+t.active,0),c=(i?.workers??[]).reduce((e,t)=>e+(a(t)?0:t.max_jobs??0),0);return(0,A.jsxs)(Dh,{width:1060,tight:!0,children:[(0,A.jsx)(Oh,{title:`Fleet`,lede:`Every worker the hub has heard from. A cordoned worker finishes its calls and is handed no new one — the move before a deploy, and it ends nothing.`}),(0,A.jsx)($m,{children:t.refused??n.refused}),i!==void 0&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(kh,{min:170,children:[(0,A.jsx)(Ah,{size:`small`,label:`Workers taking calls`,value:o.length,of:`of ${i.workers.length}`}),(0,A.jsx)(Ah,{size:`small`,label:`Calls right now`,value:s,of:c>0?`of ${c} seats`:void 0}),(0,A.jsx)(Ah,{size:`small`,label:`Cordoned`,value:i.workers.filter(e=>e.cordoned).length})]}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Workers`,meta:`re-read every ${jx/1e3} s`}),i.workers.length===0?(0,A.jsx)(Qm,{children:`No worker has reported. A hub with none answers every call on itself.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:Mx,labels:[`Worker`,`Calls`,`Load`,`Standing`,``]}),i.workers.map(t=>{let[i,o]=Px(t,a(t));return(0,A.jsxs)(Mh,{columns:Mx,children:[(0,A.jsx)(`span`,{className:a(t)?`ui-cell-faint box-fixed ui-clip`:`ui-cell-strong box-fixed ui-clip`,children:t.worker}),(0,A.jsxs)(`span`,{className:`ui-cell-ink`,children:[t.active,t.max_jobs===null||t.max_jobs===void 0?``:` / ${t.max_jobs}`]}),(0,A.jsxs)(`span`,{className:`box-load`,children:[(0,A.jsx)(Eh,{share:Math.min(1,t.load)}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:t.load.toFixed(2)})]}),(0,A.jsx)(`span`,{children:(0,A.jsx)(vh,{tone:o,children:i})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(oh,{disabled:n.busy,onClick:()=>void n.move(async()=>{await Cx(e,t.worker,!t.cordoned),await r()}),children:t.cordoned?`Uncordon`:`Cordon`})})]},t.worker)})]})]})]})]})}function Px(e,t){return t?[`not heard from`,`gray`]:e.draining?[`draining`,`amber`]:e.cordoned?[`cordoned`,`amber`]:[`taking calls`,`green`]}var Fx=`/v1/ops`,Ix=e=>`${Fx}/orgs/${encodeURIComponent(e)}`,Lx=[`minutes`,`messages`,`agents`,`concurrent_calls`,`memory_facts`,`knowledge_chunks`,`numbers`,`seats`,`budget_eur`],Rx=F().nullish(),zx=yp({id:P(),slug:P(),name:P()}),Bx=yp({dial_anywhere:L(),per_minute:F(),per_day:F(),max_duration_s:F()}),Vx=zx.extend({quotas:yp({minutes:Rx,messages:Rx,agents:Rx,concurrent_calls:Rx,memory_facts:Rx,knowledge_chunks:Rx,numbers:Rx,seats:Rx,budget_eur:Rx}),dialling:Bx.nullish(),holding:yp({memory_facts:F(),knowledge_chunks:F(),numbers:F(),seats:F()})}),Hx=yp({fingerprint:P(),label:P().nullish(),created_at:P(),revoked_at:P().nullish(),env:P(),scopes:R(P()),subject:P().nullish(),name:P().nullish()}),Ux=yp({key:P(),key_id:P(),label:P().nullish(),env:P(),scopes:R(P())}),Wx=yp({id:P(),email:P(),name:P(),role:P(),agents:R(P()),status:P(),operator:L().nullish()}),Gx=yp({member:Wx,token:P().nullish(),expires_at:P().nullish(),mailed:L().nullish()}),Kx=yp({configured:L(),issuer:P().nullish(),domains:R(P()).nullish(),required:L()});async function qx(e){return R(zx).parse(await oa(e,`${Fx}/orgs`))}async function Jx(e,t){return Vx.parse(await oa(e,Ix(t)))}async function Yx(e,t,n){return zx.parse(await ca(e,`${Fx}/orgs`,{slug:t,name:n||null}))}async function Xx(e,t){await la(e,Ix(t))}async function Zx(e,t,n){await sa(e,`${Ix(t)}/quotas`,n)}async function Qx(e,t,n){await sa(e,`${Ix(t)}/dialling`,n)}async function $x(e,t,n){return yp({logs:F(),numbers:R(P())}).parse(await sa(e,`${Ix(t)}/agents`,{agent:n}))}async function eS(e,t){return R(Hx).parse(await oa(e,`${Ix(t)}/keys`))}async function tS(e,t,n){return Ux.parse(await ca(e,`${Ix(t)}/keys`,n))}async function nS(e,t){await ca(e,`${Fx}/keys/${encodeURIComponent(t)}/revoke`,{})}async function rS(e,t){return yp({members:R(Wx),seated:F()}).parse(await oa(e,`${Ix(t)}/members`))}async function iS(e,t,n){return Gx.parse(await ca(e,`${Ix(t)}/members`,n))}async function aS(e,t,n,r){await sa(e,`${Ix(t)}/members/${encodeURIComponent(n)}/operator`,{operator:r})}async function oS(e,t,n){await la(e,`${Ix(t)}/members/${encodeURIComponent(n)}`)}async function sS(e,t){return yp({vendors:R(P())}).parse(await oa(e,`${Ix(t)}/provider-keys`)).vendors}async function cS(e,t,n,r){await sa(e,`${Ix(t)}/provider-keys/${encodeURIComponent(n)}`,{key:r})}async function lS(e,t,n){await la(e,`${Ix(t)}/provider-keys/${encodeURIComponent(n)}`)}async function uS(e,t){try{return Kx.parse(await oa(e,`${Ix(t)}/sso`))}catch{return null}}async function dS(e,t,n){await sa(e,`${Ix(t)}/sso/required`,{required:n})}var fS=`minmax(0,1fr) 96px 140px minmax(0,1.3fr) 92px`,pS=[{name:`app — what a deployed agent runs on`,scopes:[`app`]},{name:`everything — the org's own machine key`,scopes:null}];function mS({named:e}){let t=j(),n=Ox((0,D.useCallback)(()=>eS(t,e),[t,e])),r=Ax(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(`production`),[u,d]=(0,D.useState)(0),[f,p]=(0,D.useState)(null),[m,h]=(0,D.useState)(!1),g=async i=>{i.preventDefault(),await r.move(async()=>{p(await tS(t,e,{label:o.trim(),env:c,scopes:pS[u]?.scopes??null})),h(!1),await n.reread()})&&(s(``),a(!1))},_=(n.value??[]).filter(e=>e.revoked_at===null||e.revoked_at===void 0).length;return(0,A.jsxs)(A.Fragment,{children:[f!==null&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`The key for ${f.label??`this machine`}`,meta:`copy it now: the table keeps its sha256, and it is never shown again`,children:(0,A.jsxs)(`span`,{className:`box-head-moves`,children:[(0,A.jsx)(W,{size:`xs`,onClick:()=>void navigator.clipboard.writeText(f.key).then(()=>h(!0)),children:m?`Copied`:`Copy`}),(0,A.jsx)(W,{size:`xs`,onClick:()=>p(null),children:`Done`})]})}),(0,A.jsx)(`pre`,{className:`ui-code`,children:f.key})]}),(0,A.jsx)($m,{children:n.refused??r.refused}),n.value!==void 0&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Keys`,meta:`${_} live`,action:i?void 0:(0,A.jsx)(W,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>a(!0),children:`Issue a key`})}),i&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void g(e),children:[(0,A.jsx)(uh,{label:`What it is for`,grow:!0,minWidth:200,children:(0,A.jsx)(G,{value:o,placeholder:`prod server`,onChange:e=>s(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(uh,{label:`World`,minWidth:130,children:(0,A.jsxs)(ch,{value:c,onChange:e=>l(e.target.value),children:[(0,A.jsx)(`option`,{value:`production`,children:`production`}),(0,A.jsx)(`option`,{value:`sandbox`,children:`sandbox`})]})}),(0,A.jsx)(uh,{label:`Opens`,minWidth:260,children:(0,A.jsx)(ch,{value:String(u),onChange:e=>d(Number(e.target.value)),children:pS.map((e,t)=>(0,A.jsx)(`option`,{value:t,children:e.name},e.name))})}),(0,A.jsx)(W,{kind:`primary`,size:`form`,type:`submit`,disabled:r.busy||o.trim()===``,children:r.busy?`Issuing…`:`Issue`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`A machine's key names nobody: people get theirs by signing in.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(oh,{onClick:()=>a(!1),children:`Close`})})]})]}),n.value.length===0?(0,A.jsx)(Qm,{children:`No key issued to this org yet.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:fS,labels:[`Key`,`World`,`Whose`,`Opens`,``]}),n.value.map(e=>{let i=e.revoked_at!==null&&e.revoked_at!==void 0;return(0,A.jsxs)(Mh,{columns:fS,children:[(0,A.jsx)(`span`,{className:i?`ui-cell-faint ui-clip`:`ui-cell-strong ui-clip`,title:e.fingerprint,children:e.label??e.fingerprint.slice(0,12)}),(0,A.jsx)(`span`,{children:(0,A.jsx)(vh,{tone:e.env===`production`?`green`:`indigo`,children:e.env})}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.name??`a machine`}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-clip`,title:e.scopes.join(`, `),children:Ob(e.scopes)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:i?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`revoked`}):(0,A.jsx)(oh,{danger:!0,disabled:r.busy,onClick:()=>void r.move(async()=>{await nS(t,e.fingerprint),await n.reread()}),children:`Revoke`})})]},e.fingerprint)})]})]})]})}var hS={minutes:{name:`Minutes`,about:`of call, ever`},messages:{name:`Messages`,about:`written turns, ever`},agents:{name:`Agents`,about:`slugs held at once`},concurrent_calls:{name:`Concurrent calls`,about:`calls at once`},memory_facts:{name:`Memory facts`,about:`facts kept`},knowledge_chunks:{name:`Knowledge chunks`,about:`chunks kept`},numbers:{name:`Numbers`,about:`numbers this box bought`},seats:{name:`Seats`,about:`people invited or active`},budget_eur:{name:`Budget, €`,about:`a month's spend`}},gS={memory_facts:`memory_facts`,knowledge_chunks:`knowledge_chunks`,numbers:`numbers`,seats:`seats`},_S=e=>e.replace(/[^0-9]/g,``);function vS({org:e,onSaved:t}){let n=j(),r=Ax(),i=Ax(),[a,o]=(0,D.useState)(()=>Object.fromEntries(Lx.map(t=>[t,e.quotas[t]===null||e.quotas[t]===void 0?``:String(e.quotas[t])]))),[s,c]=(0,D.useState)(null),l=e.dialling??null,[u,d]=(0,D.useState)(l?.dial_anywhere??!1),[f,p]=(0,D.useState)(String(l?.per_minute??``)),[m,h]=(0,D.useState)(String(l?.per_day??``)),[g,_]=(0,D.useState)(String(l?.max_duration_s??``)),v=async()=>{c(null),await r.move(async()=>{await Zx(n,e.slug,Object.fromEntries(Lx.map(e=>[e,a[e]===``?null:Number(a[e])]))),await t()})&&c(`quotas`)},y=async()=>{c(null),await i.move(async()=>{await Qx(n,e.slug,{dial_anywhere:u,per_minute:Number(f),per_day:Number(m),max_duration_s:Number(g)}),await t()})&&c(`dialling`)};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Quotas`,meta:`empty is no limit · 0 refuses everything`}),(0,A.jsx)(`div`,{className:`box-limits`,children:Lx.map(t=>(0,A.jsxs)(uh,{label:hS[t].name,children:[(0,A.jsx)(G,{inputMode:`numeric`,value:a[t]??``,placeholder:`no limit`,onChange:e=>o({...a,[t]:_S(e.target.value)})}),(0,A.jsxs)(`div`,{className:`box-limit-about`,children:[hS[t].about,gS[t]!==void 0&&` · holding ${e.holding[gS[t]]}`]})]},t))}),(0,A.jsxs)(`div`,{className:`box-save`,children:[(0,A.jsx)(W,{kind:`primary`,size:`md`,disabled:r.busy,onClick:()=>void v(),children:r.busy?`Saving…`:`Save the quotas`}),s===`quotas`&&(0,A.jsx)(`span`,{className:`box-done`,children:`Saved. They bite the next call and the next register.`})]}),(0,A.jsx)($m,{children:r.refused})]}),l!==null&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Outbound calls`,meta:`the fence around the calls this org's agents place`}),(0,A.jsxs)(`div`,{className:`box-anywhere`,children:[(0,A.jsxs)(`span`,{className:`box-anywhere-words`,children:[(0,A.jsx)(`strong`,{children:`Call anybody`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`Off, an agent only calls numbers that already called or wrote to this org — "call back" means back.`})]}),(0,A.jsx)(mh,{on:u,onChange:d,label:`Call anybody`})]}),(0,A.jsxs)(`div`,{className:`box-limits`,children:[(0,A.jsx)(uh,{label:`Calls a minute`,children:(0,A.jsx)(G,{inputMode:`numeric`,value:f,onChange:e=>p(_S(e.target.value))})}),(0,A.jsx)(uh,{label:`Calls a day`,children:(0,A.jsx)(G,{inputMode:`numeric`,value:m,onChange:e=>h(_S(e.target.value))})}),(0,A.jsx)(uh,{label:`Longest call, seconds`,children:(0,A.jsx)(G,{inputMode:`numeric`,value:g,onChange:e=>_(_S(e.target.value))})})]}),(0,A.jsxs)(`div`,{className:`box-save`,children:[(0,A.jsx)(W,{kind:`primary`,size:`md`,disabled:i.busy,onClick:()=>void y(),children:i.busy?`Saving…`:`Save the guards`}),s===`dialling`&&(0,A.jsx)(`span`,{className:`box-done`,children:`Saved. They bite the next dial.`})]}),(0,A.jsx)($m,{children:i.refused})]})]})}var yS=[`admin`,`manager`,`developer`,`supervisor`,`qa`],bS=`minmax(0,1fr) minmax(0,1.3fr) 100px 90px 220px`,xS={active:`green`,invited:`amber`,disabled:`gray`};function SS({named:e,seats:t}){let n=j(),r=Ox((0,D.useCallback)(()=>rS(n,e),[n,e])),i=Ax(),[a,o]=(0,D.useState)(!1),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(`admin`),[h,g]=(0,D.useState)(null),_=async t=>{t.preventDefault(),await i.move(async()=>{c(await iS(n,e,{email:l.trim(),name:d.trim(),role:p,agents:[]})),await r.reread()})&&(u(``),f(``),o(!1))},v=e=>void i.move(async()=>{await e(),await r.reread()});return(0,A.jsxs)(A.Fragment,{children:[s!==null&&(0,A.jsx)(CS,{invited:s,onClose:()=>c(null)}),(0,A.jsx)($m,{children:r.refused??i.refused}),r.value!==void 0&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Members`,meta:`${r.value.seated} seated${t===null?``:` of ${t}`}`,action:a?void 0:(0,A.jsx)(W,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>o(!0),children:`Invite someone`})}),a&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void _(e),children:[(0,A.jsx)(uh,{label:`Email`,grow:!0,minWidth:180,children:(0,A.jsx)(G,{type:`email`,value:l,placeholder:`name@company.com`,onChange:e=>u(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(uh,{label:`Name`,grow:!0,minWidth:150,children:(0,A.jsx)(G,{value:d,placeholder:`Full name`,onChange:e=>f(e.target.value),required:!0})}),(0,A.jsx)(uh,{label:`Role`,minWidth:130,children:(0,A.jsx)(ch,{value:p,onChange:e=>m(e.target.value),children:yS.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),(0,A.jsx)(W,{kind:`primary`,size:`form`,type:`submit`,disabled:i.busy,children:i.busy?`Inviting…`:`Invite`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`The box's invitation takes no seat: it is how an org gets its first admin.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(oh,{onClick:()=>o(!1),children:`Close`})})]})]}),r.value.members.length===0?(0,A.jsx)(Qm,{children:`Nobody has been invited to this org.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:bS,labels:[`Name`,`Email`,`Role`,`Status`,``]}),r.value.members.map(t=>(0,A.jsxs)(Mh,{columns:bS,children:[(0,A.jsxs)(`span`,{className:`ui-cell-strong box-line`,children:[t.name,t.operator===!0&&(0,A.jsx)(vh,{tone:`violet`,small:!0,children:`operator`})]}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:t.email}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:t.role}),(0,A.jsx)(`span`,{children:(0,A.jsx)(vh,{tone:xS[t.status]??`gray`,children:t.status})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:h===t.id?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(oh,{danger:!0,disabled:i.busy,onClick:()=>v(()=>oS(n,e,t.id).finally(()=>g(null))),children:`Remove for good`}),(0,A.jsx)(oh,{onClick:()=>g(null),children:`Cancel`})]}):(0,A.jsxs)(A.Fragment,{children:[t.status===`active`&&(0,A.jsx)(oh,{disabled:i.busy,onClick:()=>v(()=>aS(n,e,t.id,t.operator!==!0)),children:t.operator===!0?`Stop running the box`:`Make operator`}),(0,A.jsx)(oh,{danger:!0,onClick:()=>g(t.id),children:`Remove`})]})})]},t.id))]}),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`Roles and agents are the org's own to change, from its Team screen. An operator's own key opens this box's doors as well as their org's.`})]})]})}function CS({invited:e,onClose:t}){let[n,r]=(0,D.useState)(!1),i=e.token??null,a=i===null?null:`${window.location.origin}/invitations/${encodeURIComponent(i)}`;return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`${e.member.name} is invited`,meta:e.mailed===!0?`the link was mailed to them too`:a===null?`they already have a password here: nothing to send`:`copy it now: it is never shown again`,children:(0,A.jsxs)(`span`,{className:`box-head-moves`,children:[a!==null&&(0,A.jsx)(W,{size:`xs`,onClick:()=>void navigator.clipboard.writeText(a).then(()=>r(!0)),children:n?`Copied`:`Copy`}),(0,A.jsx)(W,{size:`xs`,onClick:t,children:`Done`})]})}),a!==null&&(0,A.jsx)(`pre`,{className:`ui-code`,children:a})]})}function wS({org:e}){let t=j(),n=vr(),r=Ox((0,D.useCallback)(()=>uS(t,e.slug),[t,e.slug])),i=Ax(),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(!1),d=async n=>{n.preventDefault(),c(null),await i.move(async()=>{let n=await $x(t,e.slug,a.trim());c(`${a.trim()} is ${e.slug}'s now: ${n.logs} ${n.logs===1?`log`:`logs`}${n.numbers.length>0?`, and ${n.numbers.join(`, `)}`:``}.`),o(``)})},f=e=>e==null?void 0:`of ${e}`;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(kh,{min:170,children:[(0,A.jsx)(Ah,{size:`small`,label:`Seats`,value:e.holding.seats,of:f(e.quotas.seats)}),(0,A.jsx)(Ah,{size:`small`,label:`Numbers bought`,value:e.holding.numbers,of:f(e.quotas.numbers)}),(0,A.jsx)(Ah,{size:`small`,label:`Memory facts`,value:e.holding.memory_facts,of:f(e.quotas.memory_facts)}),(0,A.jsx)(Ah,{size:`small`,label:`Knowledge chunks`,value:e.holding.knowledge_chunks,of:f(e.quotas.knowledge_chunks)})]}),(0,A.jsx)($m,{children:i.refused}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Sign-in`,meta:`how this org's people prove who they are`}),(0,A.jsxs)(`div`,{className:`box-kvs`,children:[(0,A.jsx)(rh,{label:`Provider`,keyWidth:120,children:r.value?.configured?r.value.issuer??`its own identity provider`:`passwords — no identity provider wired`}),r.value?.configured&&(0,A.jsx)(rh,{label:`Passwords`,keyWidth:120,children:r.value.required?(0,A.jsxs)(`span`,{className:`box-line`,children:[(0,A.jsx)(vh,{tone:`amber`,children:`stopped`}),(0,A.jsx)(oh,{disabled:i.busy,onClick:()=>void i.move(async()=>{await dS(t,e.slug,!1),await r.reread()}),children:`Let passwords work again`})]}):`still work`})]}),r.value?.configured&&r.value.required&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`The break-glass: the day their provider stops answering, the admin who would turn this off is the one locked out.`})]}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Bring an agent here`,meta:`one that registered in the wrong org, with every call it took and its numbers`}),(0,A.jsxs)(`div`,{className:`ui-card-body`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void d(e),children:[(0,A.jsx)(uh,{label:`Agent slug`,grow:!0,minWidth:220,children:(0,A.jsx)(G,{value:a,placeholder:`clinica-norte`,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(W,{size:`form`,type:`submit`,disabled:i.busy||a.trim()===``,children:`Move it here`})]}),s!==null&&(0,A.jsx)(`div`,{className:`box-done box-done-under`,children:s}),(0,A.jsx)(`div`,{className:`ui-note box-note`,children:`The agent must be stopped first: a slug somebody is holding is refused.`})]})]}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Remove this organization`,meta:`refused while a live key or a route still names it`}),(0,A.jsx)(`div`,{className:`ui-card-body box-line`,children:l?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`span`,{className:`ui-note`,children:[`Forget `,e.slug,` for good?`]}),(0,A.jsx)(W,{kind:`danger`,size:`sm`,disabled:i.busy,onClick:()=>void i.move(async()=>{await Xx(t,e.slug),n(`/box/orgs`)}),children:`Yes, remove it`}),(0,A.jsx)(oh,{onClick:()=>u(!1),children:`Cancel`})]}):(0,A.jsxs)(W,{kind:`danger`,size:`sm`,onClick:()=>u(!0),children:[`Remove `,e.slug]})})]})]})}function TS({named:e}){let t=j(),n=Ox((0,D.useCallback)(()=>sS(t,e),[t,e])),r=Ax(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(``),u=async i=>{i.preventDefault(),await r.move(async()=>{await cS(t,e,o.trim(),c.trim()),await n.reread()})&&(s(``),l(``),a(!1))};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)($m,{children:n.refused??r.refused}),n.value!==void 0&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Vendors it brought`,meta:`every other vendor runs on the box's own key`,action:i?void 0:(0,A.jsx)(W,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>a(!0),children:`Bring a key`})}),i&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void u(e),children:[(0,A.jsx)(uh,{label:`Vendor`,minWidth:170,children:(0,A.jsx)(G,{value:o,placeholder:`elevenlabs`,onChange:e=>s(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(uh,{label:`Its key, sent once`,grow:!0,minWidth:240,children:(0,A.jsx)(G,{type:`password`,autoComplete:`off`,value:c,placeholder:`never shown again`,onChange:e=>l(e.target.value),required:!0})}),(0,A.jsx)(W,{kind:`primary`,size:`form`,type:`submit`,disabled:r.busy,children:r.busy?`Keeping…`:`Keep it`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`No door a person reads ever answers with a provider key: a lost one is set again.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(oh,{onClick:()=>a(!1),children:`Close`})})]})]}),n.value.length===0?(0,A.jsx)(Qm,{children:`None: every call of this org runs on the keys of the box.`}):n.value.map(i=>(0,A.jsx)(eh,{name:i,sub:`this org's own account with them`,end:(0,A.jsx)(oh,{disabled:r.busy,onClick:()=>void r.move(async()=>{await lS(t,e,i),await n.reread()}),children:`Give it back to the box`})},i))]})]})}var ES=[{tab:`overview`,name:`Overview`},{tab:`members`,name:`Members`},{tab:`keys`,name:`Keys`},{tab:`limits`,name:`Limits`},{tab:`providers`,name:`Providers`}];function DS(){let e=j(),t=Sr().org??``,[n,r]=Yi(),i=ES.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`overview`,a=Ox((0,D.useCallback)(()=>Jx(e,t),[e,t])),{moveTo:o}=Yh(),[s,c]=(0,D.useState)(!1),[l,u]=(0,D.useState)(null),d=async e=>{c(!0),u(null);try{await o(e)}catch(e){u(kx(e)),c(!1)}};return(0,A.jsxs)(Dh,{width:1060,tight:!0,children:[(0,A.jsx)(Oh,{back:(0,A.jsx)(k,{to:`/box/orgs`,className:`box-back`,children:`← Organizations`}),title:a.value?.name??t,lede:a.value===void 0?void 0:(0,A.jsx)(`span`,{className:`box-fixed`,children:`${a.value.slug} · ${a.value.id}`}),actions:a.value!==void 0&&(0,A.jsx)(W,{kind:`primary`,size:`md`,disabled:s,onClick:()=>void d(a.value?.id??t),children:s?`Opening…`:`Open as operator`})}),(0,A.jsx)(zh,{label:`Organization`,tabs:ES,on:i,onPick:e=>r(e===`overview`?{}:{tab:e})}),(0,A.jsx)($m,{children:l??a.refused}),a.value!==void 0&&i===`overview`&&(0,A.jsx)(wS,{org:a.value}),i===`members`&&(0,A.jsx)(SS,{named:t,seats:a.value?.quotas.seats??null}),i===`keys`&&(0,A.jsx)(mS,{named:t}),a.value!==void 0&&i===`limits`&&(0,A.jsx)(vS,{org:a.value,onSaved:a.reread}),i===`providers`&&(0,A.jsx)(TS,{named:t})]})}var OS=`minmax(0,1.2fr) minmax(0,1fr) minmax(0,1fr) 60px`;function kS(){let e=j(),t=Ox((0,D.useCallback)(()=>qx(e),[e])),n=Ax(),[r,i]=(0,D.useState)(!1),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),l=async r=>{r.preventDefault(),await n.move(async()=>{await Yx(e,a.trim(),s.trim()),await t.reread()})&&(o(``),c(``),i(!1))};return(0,A.jsxs)(Dh,{width:1060,tight:!0,children:[(0,A.jsx)(Oh,{title:`Organizations`,lede:`Every tenant this box serves. Open one to see its people, its keys, its limits and the vendors it brought.`}),(0,A.jsx)($m,{children:t.refused??n.refused}),t.value!==void 0&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`On this box`,meta:`${t.value.length} ${t.value.length===1?`organization`:`organizations`}`,action:r?void 0:(0,A.jsx)(W,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>i(!0),children:`Add an organization`})}),r&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void l(e),children:[(0,A.jsx)(uh,{label:`Slug`,grow:!0,minWidth:180,children:(0,A.jsx)(G,{value:a,placeholder:`tienda-sur`,onChange:e=>o(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(uh,{label:`Name`,grow:!0,minWidth:180,children:(0,A.jsx)(G,{value:s,placeholder:`Tienda Sur (optional)`,onChange:e=>c(e.target.value)})}),(0,A.jsx)(W,{kind:`primary`,size:`form`,type:`submit`,disabled:n.busy||a.trim()===``,children:n.busy?`Adding…`:`Add`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`The slug is what people type and the gateway is its judge. Its first admin is invited from the org's Members tab.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(oh,{onClick:()=>i(!1),children:`Close`})})]})]}),t.value.length===0?(0,A.jsx)(Qm,{children:`No organization on this box yet. The first one is what a key is issued against.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:OS,labels:[`Organization`,`Slug`,`Id`,``]}),t.value.map(e=>(0,A.jsxs)(Mh,{columns:OS,to:`/box/orgs/${encodeURIComponent(e.slug)}`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e.name}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:e.slug}),(0,A.jsx)(`span`,{className:`ui-cell-faint box-fixed`,children:e.id}),(0,A.jsx)(`span`,{className:`ui-cell-link ui-cell-end`,children:`Open`})]},e.id))]})]})]})}var AS=[`production`,`sandbox`],jS=[`phone`,`whatsapp`],MS=`minmax(0,1.1fr) 110px minmax(0,1fr) 150px 80px`;function NS(){let e=j(),t=Ox((0,D.useCallback)(()=>qx(e),[e])),[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(AS[0]),o=Ox((0,D.useCallback)(()=>n===``?Promise.resolve(void 0):wx(e,n,i),[e,n,i])),s=Ax(),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(``),[m,h]=(0,D.useState)(jS[0]),[g,_]=(0,D.useState)(null);(0,D.useEffect)(()=>{n===``&&t.value!==void 0&&r(t.value.find(e=>e.slug!=="default")?.slug??t.value[0]?.slug??``)},[n,t.value]);let v=async t=>{t.preventDefault(),_(null),await s.move(async()=>{let t=await Tx(e,{org:n,number:u.trim(),agent:f.trim(),channel:m,env:i});_(t===null?`${u.trim()} now rings ${f.trim()}.`:`${u.trim()} now rings ${f.trim()}, taken from ${t}.`),await o.reread()})&&(d(``),p(``),l(!1))};return(0,A.jsxs)(Dh,{width:1060,tight:!0,children:[(0,A.jsx)(Oh,{title:`Routes`,lede:`Every door one org answers at, in one world. A row typed here outranks whatever an app declared.`}),(0,A.jsxs)(`div`,{className:`box-pick`,children:[(0,A.jsx)(ch,{size:`sm`,value:n,onChange:e=>r(e.target.value),"aria-label":`Organization`,children:(t.value??[]).map(e=>(0,A.jsx)(`option`,{value:e.slug,children:e.slug},e.id))}),(0,A.jsx)(ch,{size:`sm`,value:i,onChange:e=>a(e.target.value),"aria-label":`World`,children:AS.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})]}),(0,A.jsx)($m,{children:t.refused??o.refused??s.refused}),o.value!==void 0&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`${n} · ${i}`,meta:`${o.value.length} ${o.value.length===1?`door`:`doors`}`,action:c?void 0:(0,A.jsx)(W,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>l(!0),children:`Type a number`})}),c&&(0,A.jsxs)(`div`,{className:`box-inline`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void v(e),children:[(0,A.jsx)(uh,{label:`Number`,minWidth:170,children:(0,A.jsx)(G,{value:u,placeholder:`+34910000000`,onChange:e=>d(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(uh,{label:`Agent`,grow:!0,minWidth:170,children:(0,A.jsx)(G,{value:f,placeholder:`clinica-norte`,onChange:e=>p(e.target.value),required:!0})}),(0,A.jsx)(uh,{label:`Channel`,minWidth:120,children:(0,A.jsx)(ch,{value:m,onChange:e=>h(e.target.value),children:jS.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),(0,A.jsx)(W,{kind:`primary`,size:`form`,type:`submit`,disabled:s.busy,children:s.busy?`Typing…`:`Add`})]}),(0,A.jsxs)(`div`,{className:`box-inline-foot`,children:[`A row and nothing else: the carrier and the SFU trunk are the org's Numbers screen.`,(0,A.jsx)(`span`,{className:`box-inline-close`,children:(0,A.jsx)(oh,{onClick:()=>l(!1),children:`Close`})})]})]}),g!==null&&(0,A.jsx)(`div`,{className:`box-done box-done-row`,children:g}),o.value.length===0?(0,A.jsx)(Qm,{children:`No door in this world: nothing typed, and no app holding an agent here.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:MS,labels:[`Number`,`Channel`,`Agent`,`Said by`,``]}),o.value.map(t=>(0,A.jsxs)(Mh,{columns:MS,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:t.route.number?Eg(t.route.number):`—`}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:t.route.channel}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:t.route.agent}),(0,A.jsxs)(`span`,{className:`box-line`,children:[(0,A.jsx)(vh,{tone:t.source===`operator`?`indigo`:`gray`,children:t.source===`operator`?`typed`:t.source}),t.route.managed===!0&&(0,A.jsx)(vh,{tone:`violet`,children:`bought`})]}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:t.source===`operator`&&typeof t.route.number==`string`&&(0,A.jsx)(oh,{danger:!0,disabled:s.busy,onClick:()=>void s.move(async()=>{await Ex(e,n,t.route.number??``),await o.reread()}),children:`Forget`})})]},`${t.route.channel}-${t.route.number??t.route.agent}`))]})]})]})}var PS=`/v1/ops`;async function FS(e){try{return await e}catch(e){if(e instanceof ta&&(e.status===404||e.status===405))return null;throw e}}var IS=yp({google:yp({configured:L(),client_id:P().nullish(),redirect_uri:P().nullish()})});async function LS(e){return FS(oa(e,`${PS}/signin`).then(e=>IS.parse(e)))}async function RS(e,t){await sa(e,`${PS}/signin/google`,t)}async function zS(e){await la(e,`${PS}/signin/google`)}var BS=[`starttls`,`tls`,`none`],VS=yp({configured:L(),source:P().nullish(),host:P().nullish(),port:F().nullish(),security:P().nullish(),username:P().nullish(),from:P().nullish(),verified_at:P().nullish(),last_error:P().nullish()});async function HS(e){return FS(oa(e,`${PS}/mail`).then(e=>VS.parse(e)))}async function US(e,t){await sa(e,`${PS}/mail`,t)}async function WS(e){await la(e,`${PS}/mail`)}async function GS(e,t){let n=yp({sent:L(),error:P().nullish()}).parse(await ca(e,`${PS}/mail/test`,{to:t}));return{sent:n.sent,error:n.error??null}}var KS=yp({name:P().nullish(),logo_url:P().nullish(),accent:P().nullish()});async function qS(e){return FS(oa(e,`${PS}/brand`).then(e=>KS.parse(e)))}async function JS(e,t){await sa(e,`${PS}/brand`,t)}var YS=`Pinecall`,XS=`#5b3df5`,ZS=/^#[0-9a-fA-F]{6}$/;function QS(){let e=j(),t=Ox((0,D.useCallback)(()=>qS(e),[e])),n=Ax(),[r,i]=(0,D.useState)(YS),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(XS),[l,u]=(0,D.useState)(!1);if((0,D.useEffect)(()=>{t.value!==void 0&&t.value!==null&&(i(t.value.name??YS),o(t.value.logo_url??``),c(t.value.accent??XS))},[t.value]),t.value===void 0)return(0,A.jsx)($m,{children:t.refused});if(t.value===null)return(0,A.jsx)(iC,{});let d=async i=>{i.preventDefault(),u(!1),u(await n.move(async()=>{await JS(e,{name:r.trim(),logo_url:a.trim(),accent:s}),await t.reread()}))},f=ZS.test(s)?s:XS;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)($m,{children:n.refused}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`What the letters carry`,meta:`invitations and password resets, for every org on this box`}),(0,A.jsxs)(`form`,{className:`box-form`,onSubmit:e=>void d(e),children:[(0,A.jsxs)(`div`,{className:`box-form-grid`,children:[(0,A.jsx)(uh,{label:`Name`,children:(0,A.jsx)(G,{value:r,onChange:e=>i(e.target.value),required:!0})}),(0,A.jsx)(uh,{label:`Accent`,children:(0,A.jsxs)(`span`,{className:`box-accent`,children:[(0,A.jsx)(`input`,{type:`color`,className:`box-accent-well`,value:f,onChange:e=>c(e.target.value),"aria-label":`Accent`}),(0,A.jsx)(G,{value:s,onChange:e=>c(e.target.value)})]})}),(0,A.jsx)(uh,{label:`Logo URL`,children:(0,A.jsx)(G,{type:`url`,value:a,placeholder:`https://… (https only; empty shows the name)`,onChange:e=>o(e.target.value)})})]}),(0,A.jsxs)(`div`,{className:`box-line`,children:[(0,A.jsx)(W,{kind:`primary`,size:`md`,type:`submit`,disabled:n.busy,children:n.busy?`Saving…`:`Save`}),l&&(0,A.jsx)(`span`,{className:`box-done`,children:`Saved. The next letter carries it.`})]})]})]}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Preview`,meta:`the head of a letter`}),(0,A.jsx)(`div`,{className:`box-letter-ground`,children:(0,A.jsxs)(`div`,{className:`box-letter`,children:[a.trim().startsWith(`https://`)?(0,A.jsx)(`img`,{className:`box-letter-logo`,src:a.trim(),alt:r}):(0,A.jsx)(`span`,{className:`box-letter-name`,children:r}),(0,A.jsxs)(`div`,{className:`box-letter-title`,children:[`You're invited to Acme on `,r]}),(0,A.jsx)(`div`,{className:`box-letter-words`,children:`Ana invited you as a supervisor. Choose a password to take your first key.`}),(0,A.jsx)(`span`,{className:`box-letter-button`,style:{background:f},children:`Accept the invitation`})]})})]})]})}function $S(){let e=j(),t=Ox((0,D.useCallback)(()=>HS(e),[e])),n=Ax(),[r,i]=(0,D.useState)(!1),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null);if(t.value===void 0)return(0,A.jsx)($m,{children:t.refused});if(t.value===null)return(0,A.jsx)(iC,{});let l=t.value,u=async r=>{r.preventDefault(),c(null),await n.move(async()=>{c(await GS(e,a.trim())),await t.reread()})};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)($m,{children:n.refused}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`The box's mail`,meta:`invitations, password resets and a forgotten password`,children:(0,A.jsx)(`span`,{className:`box-head-moves`,children:(0,A.jsx)(vh,{tone:l.configured?`green`:`gray`,children:l.configured?l.source===`environment`?`on · from the environment`:`on`:`off`})})}),r||!l.configured?(0,A.jsx)(eC,{kept:l,busy:n.busy,onCancel:l.configured?()=>i(!1):void 0,onSave:async r=>{await n.move(async()=>{await US(e,r),await t.reread()})&&i(!1)}}):(0,A.jsxs)(`div`,{className:`box-kvs`,children:[(0,A.jsxs)(rh,{label:`Server`,keyWidth:120,children:[(0,A.jsx)(`span`,{className:`box-fixed`,children:`${l.host??`—`}:${l.port??``}`}),` · `,l.security??`starttls`]}),(0,A.jsx)(rh,{label:`Username`,keyWidth:120,children:(0,A.jsx)(`span`,{className:`box-fixed`,children:l.username??`none`})}),(0,A.jsx)(rh,{label:`From`,keyWidth:120,children:l.from??`—`}),(0,A.jsx)(rh,{label:`Last letter`,keyWidth:120,children:l.last_error?(0,A.jsx)(`span`,{className:`box-bad`,children:l.last_error}):l.verified_at?`went through · ${l.verified_at.slice(0,16).replace(`T`,` `)}`:`none sent yet`}),(0,A.jsxs)(`div`,{className:`box-line box-kvs-moves`,children:[(0,A.jsx)(W,{size:`sm`,onClick:()=>i(!0),children:l.source===`environment`?`Replace it here`:`Change`}),l.source!==`environment`&&(0,A.jsx)(oh,{danger:!0,disabled:n.busy,onClick:()=>void n.move(async()=>{await WS(e),await t.reread()}),children:`Forget it`})]})]})]}),l.configured&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Send a test letter`,meta:`the one door that waits for the mail server's answer`}),(0,A.jsxs)(`div`,{className:`ui-card-body`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void u(e),children:[(0,A.jsx)(uh,{label:`To`,grow:!0,minWidth:240,children:(0,A.jsx)(G,{type:`email`,value:a,placeholder:`you@company.com`,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(W,{size:`form`,type:`submit`,disabled:n.busy,children:n.busy?`Sending…`:`Send`})]}),s!==null&&(s.sent?(0,A.jsx)(`div`,{className:`box-done box-done-under`,children:`Taken by the mail server.`}):(0,A.jsx)(`div`,{className:`box-bad box-note`,children:s.error??`It was refused.`}))]})]})]})}function eC({kept:e,busy:t,onSave:n,onCancel:r}){let[i,a]=(0,D.useState)(e.host??``),[o,s]=(0,D.useState)(String(e.port??587)),[c,l]=(0,D.useState)(BS.find(t=>t===e.security)??`starttls`),[u,d]=(0,D.useState)(e.username??``),[f,p]=(0,D.useState)(``),[m,h]=(0,D.useState)(e.from??``);return(0,A.jsxs)(`form`,{className:`box-form`,onSubmit:e=>{e.preventDefault(),n({host:i.trim(),port:Number(o),security:c,username:u.trim()===``?null:u.trim(),...f===``?{}:{password:f},from:m.trim()})},children:[(0,A.jsxs)(`div`,{className:`box-form-grid`,children:[(0,A.jsx)(uh,{label:`Host`,children:(0,A.jsx)(G,{value:i,placeholder:`email-smtp.us-east-1.amazonaws.com`,onChange:e=>a(e.target.value),required:!0})}),(0,A.jsxs)(`div`,{className:`box-form-pair`,children:[(0,A.jsx)(uh,{label:`Port`,children:(0,A.jsx)(G,{inputMode:`numeric`,value:o,onChange:e=>s(e.target.value.replace(/[^0-9]/g,``)),required:!0})}),(0,A.jsx)(uh,{label:`Security`,children:(0,A.jsx)(ch,{value:c,onChange:e=>l(e.target.value),children:BS.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})})]}),(0,A.jsx)(uh,{label:`Username`,children:(0,A.jsx)(G,{autoComplete:`off`,value:u,onChange:e=>d(e.target.value)})}),(0,A.jsx)(uh,{label:`Password, sent once`,children:(0,A.jsx)(G,{type:`password`,autoComplete:`new-password`,value:f,placeholder:e.configured?`unchanged`:`never shown again`,onChange:e=>p(e.target.value)})}),(0,A.jsx)(uh,{label:`From`,children:(0,A.jsx)(G,{value:m,placeholder:`Pinecall <noreply@pinecall.io>`,onChange:e=>h(e.target.value),required:!0})})]}),(0,A.jsxs)(`div`,{className:`box-line`,children:[(0,A.jsx)(W,{kind:`primary`,size:`md`,type:`submit`,disabled:t,children:t?`Saving…`:`Save`}),r!==void 0&&(0,A.jsx)(oh,{onClick:r,children:`Cancel`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`Saving sends nothing: the test letter below is what proves it.`})]})]})}function tC(){let e=j(),t=Ox((0,D.useCallback)(()=>LS(e),[e])),n=Ax(),[r,i]=(0,D.useState)(!1),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(!1);if(t.value===void 0)return(0,A.jsx)($m,{children:t.refused});if(t.value===null)return(0,A.jsx)(iC,{});let d=t.value.google,f=d.redirect_uri??bm(jm()),p=r||!d.configured,m=async r=>{r.preventDefault(),await n.move(async()=>{await RS(e,{client_id:a.trim(),client_secret:s.trim()}),await t.reread()})&&(c(``),i(!1))};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)($m,{children:n.refused}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Continue with Google`,meta:`one client for the whole box — no org configures anything`,children:(0,A.jsx)(`span`,{className:`box-head-moves`,children:(0,A.jsx)(vh,{tone:d.configured?`green`:`gray`,children:d.configured?`on`:`off`})})}),p?(0,A.jsxs)(`form`,{className:`box-form`,onSubmit:e=>void m(e),children:[(0,A.jsxs)(`div`,{className:`box-form-grid`,children:[(0,A.jsx)(uh,{label:`Client ID`,children:(0,A.jsx)(G,{value:a,placeholder:`…apps.googleusercontent.com`,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(uh,{label:`Client secret, sent once`,children:(0,A.jsx)(G,{type:`password`,autoComplete:`off`,value:s,placeholder:`never shown again`,onChange:e=>c(e.target.value),required:!0})})]}),(0,A.jsxs)(`div`,{className:`box-line`,children:[(0,A.jsx)(W,{kind:`primary`,size:`md`,type:`submit`,disabled:n.busy,children:n.busy?`Saving…`:`Save`}),r&&(0,A.jsx)(oh,{onClick:()=>i(!1),children:`Cancel`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`Made at Google Cloud Console → APIs & Services → Credentials → OAuth client ID → Web application.`})]})]}):(0,A.jsxs)(`div`,{className:`box-kvs`,children:[(0,A.jsx)(rh,{label:`Client ID`,keyWidth:120,children:(0,A.jsx)(`span`,{className:`box-fixed`,children:d.client_id??`—`})}),(0,A.jsx)(rh,{label:`Secret`,keyWidth:120,children:`kept, and read back by no door`}),(0,A.jsxs)(`div`,{className:`box-line box-kvs-moves`,children:[(0,A.jsx)(W,{size:`sm`,onClick:()=>{o(d.client_id??``),i(!0)},children:`Change`}),(0,A.jsx)(oh,{danger:!0,disabled:n.busy,onClick:()=>void n.move(async()=>{await zS(e),await t.reread()}),children:`Turn it off`})]})]}),(0,A.jsxs)(`div`,{className:`box-redirect`,children:[(0,A.jsxs)(`div`,{className:`box-redirect-head`,children:[(0,A.jsx)(`span`,{className:`ui-note`,children:`Register this at Google as the authorized redirect URI`}),(0,A.jsx)(W,{size:`xs`,onClick:()=>void navigator.clipboard.writeText(f).then(()=>u(!0)),children:l?`Copied`:`Copy`})]}),(0,A.jsx)(`pre`,{className:`ui-code`,children:f})]})]})]})}var nC=[{tab:`signin`,name:`Sign-in`},{tab:`email`,name:`Email`},{tab:`brand`,name:`Brand`}];function rC(){let[e,t]=Yi(),n=nC.some(t=>t.tab===e.get(`tab`))?e.get(`tab`):`signin`;return(0,A.jsxs)(Dh,{width:900,children:[(0,A.jsx)(Oh,{title:`Box settings`,lede:`What this gateway is set to, for every organization on it.`}),(0,A.jsx)(zh,{label:`Box settings`,tabs:nC,on:n,onPick:e=>t(e===`signin`?{}:{tab:e})}),n===`signin`&&(0,A.jsx)(tC,{}),n===`email`&&(0,A.jsx)($S,{}),n===`brand`&&(0,A.jsx)(QS,{})]})}function iC(){return(0,A.jsx)(H,{children:(0,A.jsx)(Qm,{children:`This gateway does not have this door yet.`})})}var aC=100,oC=`minmax(0,1.2fr) 110px 110px 140px 140px`,sC=`130px minmax(0,1fr) minmax(0,1.4fr) 110px 80px 80px 90px`;function cC(){let e=j(),[t,n]=(0,D.useState)([]),[r,i]=(0,D.useState)({}),[a,o]=(0,D.useState)(0),[s,c]=(0,D.useState)(!1),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),p=async(t,r)=>{u(!0);try{let a=await Dx(e,t,aC);n(e=>r?a.rows:[...e,...a.rows]),i(e=>r?a.totals:uC(e,a.totals)),o(a.next??null),c(!0)}catch(e){f(kx(e))}finally{u(!1)}};(0,D.useEffect)(()=>{p(0,!0)},[e]);let m=e=>t.filter(t=>t.org===e).reduce((e,t)=>e+t.cost_eur,0);return(0,A.jsxs)(Dh,{tight:!0,children:[(0,A.jsx)(Oh,{title:`Box usage`,lede:`What every organization consumed, folded off the log by a cursor — there is no counter table to drift from it.`}),(0,A.jsx)($m,{children:d}),s&&t.length===0&&a===null&&(0,A.jsx)(H,{children:(0,A.jsx)(Qm,{children:`Nothing metered yet: no call of any org has been summarised.`})}),Object.keys(r).length>0&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`By organization`,meta:a===null?`the whole log`:`the pages read so far`}),(0,A.jsx)(jh,{columns:oC,labels:[`Organization`,`Minutes>`,`Messages>`,`Tokens>`,`Cost>`]}),Object.entries(r).map(([e,t])=>(0,A.jsxs)(Mh,{columns:oC,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:t.minutes.toFixed(1)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:t.messages}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:(t.input_tokens+t.output_tokens).toLocaleString(`en`)}),(0,A.jsxs)(`span`,{className:`ui-cell-ink ui-cell-right`,children:[`€`,m(e).toFixed(2)]})]},e))]}),t.length>0&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Metered rows`,meta:`${t.length} read, oldest first`}),(0,A.jsx)(jh,{columns:sC,labels:[`When`,`Organization`,`Agent · call`,`What`,`Min>`,`Msgs>`,`Cost>`]}),t.map(e=>(0,A.jsxs)(Mh,{columns:sC,children:[(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:lC(e.at)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.org}),(0,A.jsxs)(`span`,{className:`ui-cell-ink ui-clip`,title:e.call,children:[e.agent,` `,(0,A.jsxs)(`span`,{className:`ui-cell-faint box-fixed`,children:[e.call.slice(0,13),`…`]})]}),(0,A.jsx)(`span`,{className:`ui-cell-faint box-fixed`,children:e.type}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:e.minutes.toFixed(2)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-cell-right`,children:e.messages}),(0,A.jsxs)(`span`,{className:`ui-cell-ink ui-cell-right`,children:[`€`,e.cost_eur.toFixed(4)]})]},`${e.cursor}-${e.call}-${e.type}`)),a!==null&&(0,A.jsx)(Zm,{children:(0,A.jsx)(W,{size:`sm`,disabled:l,onClick:()=>void p(a,!1),children:l?`Reading…`:`Read on`})})]})]})}function lC(e){return new Date(e*1e3).toISOString().slice(0,16).replace(`T`,` `)}function uC(e,t){let n={...e};for(let[e,r]of Object.entries(t)){let t=n[e];n[e]=t===void 0?r:{...r,minutes:t.minutes+r.minutes,messages:t.messages+r.messages,input_tokens:t.input_tokens+r.input_tokens,output_tokens:t.output_tokens+r.output_tokens,characters:t.characters+r.characters}}return n}function dC({children:e}){let{operator:t}=wb();return t===null?null:t?e:(0,A.jsx)(Xr,{to:`/`,replace:!0})}var fC=3e3;function pC(e){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i=async()=>{try{let i=dy.parse(await oa(t,`/v1/agents/${e}/sessions`));n||(r(i.calls),a(null))}catch(e){n||a(String(e))}};i();let o=window.setInterval(()=>void i(),fC);return()=>{n=!0,window.clearInterval(o)}},[e,t]),{lines:n,error:i}}function mC(e){return e.status!==`ended`}var hC={neutral:`gray`,good:`green`,warn:`amber`,bad:`red`};function gC({nodes:e}){return(0,A.jsx)(A.Fragment,{children:e.map((e,t)=>(0,A.jsx)(_C,{node:e},t))})}function _C({node:e}){switch(e.tag){case`panel`:return(0,A.jsxs)(`div`,{className:`ib-panel`,children:[e.title!==null&&(0,A.jsx)(nh,{children:e.title}),(0,A.jsx)(gC,{nodes:e.children})]});case`rows`:return(0,A.jsx)(`div`,{className:`ib-panel-rows`,children:(0,A.jsx)(gC,{nodes:e.children})});case`row`:return(0,A.jsx)(rh,{label:e.label,children:e.value});case`stat`:return(0,A.jsxs)(`div`,{className:`ib-panel-stat`,children:[(0,A.jsx)(`span`,{className:`ib-panel-stat-value`,children:e.value}),(0,A.jsx)(`span`,{className:`ib-panel-stat-label`,children:e.label})]});case`table`:return(0,A.jsx)(vC,{columns:e.columns,rows:e.rows});case`badge`:return(0,A.jsx)(`div`,{className:`ib-panel-badge`,children:(0,A.jsx)(vh,{tone:hC[e.tone],small:!0,children:e.text})});case`text`:return(0,A.jsx)(`p`,{className:`ib-panel-text`,children:e.text})}}function vC({columns:e,rows:t}){if(t.length===0)return(0,A.jsx)(`p`,{className:`ib-panel-text`,children:`—`});let n=`repeat(${String(Math.max(e.length,t[0]?.length??1))}, minmax(0, 1fr))`;return(0,A.jsxs)(`div`,{className:`ib-panel-table`,children:[e.length>0&&(0,A.jsx)(jh,{columns:n,labels:e,padding:`5px 2px`}),t.map((e,t)=>(0,A.jsx)(Mh,{columns:n,padding:`6px 2px`,children:e.map((e,t)=>(0,A.jsx)(`span`,{className:`ui-clip`,children:e},t))},t))]})}function yC(e){let t={conversations:e.length,seconds:0,first:null,last:null,channels:[],held:0,judged:0,flags:[],live:!1};for(let n of e){n.started_at!==null&&n.ended_at!==null&&(t.seconds+=Math.max(0,n.ended_at-n.started_at)),n.started_at!==null&&(t.first=t.first===null?n.started_at:Math.min(t.first,n.started_at),t.last=t.last===null?n.started_at:Math.max(t.last,n.started_at)),n.channel!==null&&!t.channels.includes(n.channel)&&t.channels.push(n.channel),n.score!=null&&(t.held+=n.score.held,t.judged+=n.score.judged);for(let e of n.flags??[])t.flags.includes(e)||t.flags.push(e);n.status!==`ended`&&(t.live=!0)}return t}var bC={escalated:`a person took part`,low_score:`a judge broke`,promise:`a promise was made`};function xC(e){return bC[e]}var SC={"chat.roster":`chat`,"chat.start":`chat`,"chat.say":`chat`,"chat.end":`chat`,"view.render":`view`,"knowledge.roster":`knowledge`,"knowledge.push":`knowledge`,"knowledge.eval":`knowledge`,"memory.roster":`memory`,"memory.eval":`memory`,"memory.extraction":`memory`,"simulate.start":`evals`,"goldens.roster":`evals`,"goldens.run":`evals`,"promote.roster":`evals`,"promote.write":`evals`,"drift.read":`evals`,"reproductions.roster":`evals`,"reproductions.read":`evals`};function CC(e,t){return`/v1/agents/${encodeURIComponent(e)}/dev/${SC[t]}/${t}`}async function wC(e,t,n,r={}){return ca(e,CC(t,n),r)}var TC=em(()=>xp([z({tag:Mp(`panel`),title:P().nullable(),children:R(TC)}),z({tag:Mp(`rows`),children:R(TC)}),z({tag:Mp(`row`),label:P(),value:P()}),z({tag:Mp(`stat`),label:P(),value:P()}),z({tag:Mp(`table`),columns:R(P()),rows:R(R(P()))}),z({tag:Mp(`badge`),tone:V([`neutral`,`good`,`warn`,`bad`]),text:P()}),z({tag:Mp(`text`),text:P()})])),EC=yp({name:P(),nodes:R(TC)}),DC=yp({view:P().nullish()});async function OC(e,t){return DC.parse(await oa(e,`/v1/agents/${encodeURIComponent(t)}/config`)).view??null}async function kC(e,t,n,r){try{return EC.parse(await wC(e,t,`view.render`,{contact:n,call:r}))}catch(e){if(e instanceof ta&&(e.status===404||e.status===405))return null;throw e}}function AC({agent:e,thread:t,name:n}){let r=yC(t.lines);return(0,A.jsxs)(`aside`,{className:`ib-aside`,"aria-label":`About ${n}`,children:[(0,A.jsx)(MC,{agent:e,contact:t.contact,call:t.latest.call}),(0,A.jsx)(nh,{children:`Contact`}),(0,A.jsxs)(`div`,{className:`ib-aside-rows`,children:[(0,A.jsx)(rh,{label:`Reached by`,children:r.channels.join(` · `)||`—`}),(0,A.jsx)(rh,{label:`Handle`,children:t.handle}),(0,A.jsx)(rh,{label:`First seen`,children:r.first===null?`—`:yg(r.first)}),(0,A.jsx)(rh,{label:`Last`,children:r.last===null?`—`:bg(r.last)})]}),(0,A.jsx)(nh,{ruled:!0,children:`Standing`}),(0,A.jsxs)(`div`,{className:`ib-aside-facts`,children:[(0,A.jsx)(jC,{value:String(r.conversations),label:r.conversations===1?`conversation`:`conversations`}),(0,A.jsx)(jC,{value:pg({started_at:0,ended_at:r.seconds}),label:`on the line`}),r.judged>0&&(0,A.jsx)(jC,{value:`${String(r.held)}/${String(r.judged)}`,label:`judges held`})]}),r.flags.length>0&&(0,A.jsx)(`div`,{className:`ib-aside-flags`,children:r.flags.map(e=>(0,A.jsx)(vh,{tone:e===`low_score`?`red`:`amber`,small:!0,children:xC(e)},e))}),(0,A.jsx)(nh,{ruled:!0,children:`Conversations`}),(0,A.jsx)(`div`,{className:`ib-aside-list`,children:t.lines.map(t=>(0,A.jsx)(th,{name:t.started_at===null?t.call:yg(t.started_at),sub:`${t.channel??`—`} · ${t.status===`ended`?pg(t):`on the line now`}`,end:t.outcome!==null&&t.outcome!==``?(0,A.jsx)(`span`,{className:`ib-aside-outcome`,children:t.outcome}):void 0,to:`/a/${e}/sessions/${t.call}`},t.call))})]})}function jC({value:e,label:t}){return(0,A.jsxs)(`div`,{className:`ib-panel-stat`,children:[(0,A.jsx)(`span`,{className:`ib-panel-stat-value`,children:e}),(0,A.jsx)(`span`,{className:`ib-panel-stat-label`,children:t})]})}function MC({agent:e,contact:t,call:n}){let r=j(),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{let t=!1;return OC(r,e).then(e=>{t||a(e)},()=>void 0),()=>{t=!0}},[r,e]),(0,D.useEffect)(()=>{if(i===null)return;let a=!1;return d(!0),l(null),kC(r,e,t,n).then(e=>{a||(s(e),d(!1))},e=>{a||(l(e instanceof ta?e.message:String(e)),d(!1))}),()=>{a=!0}},[r,e,t,n,i]),i===null?null:(0,A.jsxs)(`div`,{className:`ib-aside-own`,children:[u&&o===null&&c===null&&(0,A.jsxs)(Qm,{children:[`Drawing `,i,`…`]}),(0,A.jsx)($m,{children:c}),o!==null&&o.nodes.length===0&&(0,A.jsxs)(Qm,{children:[i,` has nothing for this conversation.`]}),o!==null&&(0,A.jsx)(gC,{nodes:o.nodes})]})}var NC=/^\+[1-9]\d{4,14}$/;function PC(){let e=j(),[t,n]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let t=!1;return Qb(e).then(e=>{t||n(e!==null&&e.ready?e:null)},()=>void 0),()=>{t=!0}},[e]),t}function FC({outbound:e,value:t,onChange:n}){return e.from_numbers.length<2?null:(0,A.jsx)(uh,{label:`From`,children:(0,A.jsxs)(ch,{size:`sm`,value:t,onChange:e=>n(e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`the agent's own number`}),e.from_numbers.map(e=>(0,A.jsx)(`option`,{value:e,children:Eg(e)},e))]})})}function IC({agent:e,to:t,outbound:n,onClose:r,onRefused:i}){let a=j(),o=vr(),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(!1),d=(0,D.useRef)(null);(0,D.useEffect)(()=>{let e=e=>{e.key===`Escape`&&r()},t=e=>{let t=d.current?.parentElement;t!=null&&!t.contains(e.target)&&r()};return document.addEventListener(`keydown`,e),document.addEventListener(`mousedown`,t),()=>{document.removeEventListener(`keydown`,e),document.removeEventListener(`mousedown`,t)}},[r]);let f=async()=>{u(!0);try{let n=await tx(a,e,t,s);o(`/live/${n}`)}catch(e){i(e instanceof ta?e.message:String(e)),r()}finally{u(!1)}};return(0,A.jsxs)(`div`,{className:`dial-pop`,role:`dialog`,"aria-label":`call back`,ref:d,children:[(0,A.jsxs)(`div`,{className:`dial-ask`,children:[`Call `,Eg(t),` as `,e,`?`]}),(0,A.jsx)(FC,{outbound:n,value:s,onChange:c}),(0,A.jsxs)(`div`,{className:`dial-moves`,children:[(0,A.jsx)(W,{kind:`primary`,size:`md`,disabled:l,onClick:()=>void f(),children:l?`Calling…`:`Call`}),(0,A.jsx)(W,{size:`md`,disabled:l,onClick:r,children:`Cancel`})]})]})}function LC({agent:e,outbound:t,onClose:n}){let r=j(),i=vr(),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),p=a.replace(/[\s()-]/g,``),m=async t=>{if(t.preventDefault(),!NC.test(p)){f(`A number is written whole, with its country: +14176743169.`);return}u(!0),f(null);try{let t=await tx(r,e,p,s);n(),i(`/live/${t}`)}catch(e){f(e instanceof ta?e.message:String(e))}finally{u(!1)}};return(0,A.jsxs)(`form`,{className:`dial-form`,onSubmit:e=>void m(e),children:[(0,A.jsx)(uh,{label:`Number`,children:(0,A.jsx)(G,{size:`sm`,value:a,placeholder:`+1 417 674 3169`,autoFocus:!0,autoComplete:`off`,onChange:e=>o(e.target.value)})}),(0,A.jsx)(FC,{outbound:t,value:s,onChange:c}),(0,A.jsx)(`p`,{className:`dial-note`,children:t.guards.dial_anywhere?`${e} places the call and speaks first.`:`${e} places the call and speaks first. Only a number that has already called or written to you is dialled.`}),d!==null&&(0,A.jsx)(`p`,{className:`dial-refused`,children:d}),(0,A.jsx)(W,{kind:`primary`,size:`md`,type:`submit`,disabled:l||p===``,children:l?`Calling…`:`Call`})]})}var RC=yp({threads:R(yp({contact:P(),name:P().nullish(),unread:F().nullish()}))});async function zC(e,t){try{let n=RC.parse(await oa(e,`/v1/agents/${encodeURIComponent(t)}/threads`));return new Map(n.threads.map(e=>[e.contact,e]))}catch(e){if(e instanceof ta&&(e.status===404||e.status===405))return null;throw e}}async function BC(e,t,n){await ca(e,`/v1/agents/${encodeURIComponent(t)}/threads/${encodeURIComponent(n)}/read`,{})}async function VC(e,t,n,r){await ca(e,`/v1/agents/${encodeURIComponent(t)}/threads/${encodeURIComponent(n)}/messages`,{text:r})}async function HC(e,t,n){await ca(e,`/v1/calls/${encodeURIComponent(t)}/verbs`,C_.parse({verb:`say`,text:n}))}function UC(e){return e.direction===`outbound`?e.to:e.from}function WC(e){let t=new Map;for(let n of e){let e=n.caller?.id??n.caller?.phone??UC(n)??n.call,r=t.get(e);if(r===void 0){t.set(e,{contact:e,name:n.caller?.name??null,handle:GC(n),lines:[n],latest:n});continue}r.lines.push(n),r.name??=n.caller?.name??null,(n.started_at??0)>(r.latest.started_at??0)&&(r.latest=n)}let n=[...t.values()];for(let e of n)e.lines.sort((e,t)=>(t.started_at??0)-(e.started_at??0));return n.sort((e,t)=>(t.latest.started_at??0)-(e.latest.started_at??0))}function GC(e){let t=UC(e);return t===null?e.channel===`web`?`web visitor`:`—`:t.startsWith(`+`)?Eg(t):e.channel===`web`?`web visitor`:t}function KC(e){return e.name!==null&&e.name!==``?e.name:e.contact.startsWith(`+`)?Eg(e.contact):e.contact}function qC(e){if(e.name===null||e.name===``)return e.handle===`web visitor`?`W`:e.contact.startsWith(`+`)?e.contact.slice(-2):void 0}function JC(e,t){if(e.channel===`phone`)return!0;let n=Qy();for(let e of t)n=tb(n,e);return n.room!==null}function YC(e,t,n){let r=[],i=t[0]?.ts??e.started_at??0;n&&r.push({kind:`call`,text:XC(e),at:i,call:e.call});for(let n of t){let t=n.data.text;typeof t==`string`&&t!==``&&(n.type===`turn.user`&&r.push({kind:`in`,text:t,at:n.ts,call:e.call}),(n.type===`turn.agent`||n.type===`supervisor.said`)&&r.push({kind:`out`,text:t,at:n.ts,call:e.call}))}return r}function XC(e){let t=e.direction===`outbound`?`outbound`:`inbound`;return e.status===`ended`?e.end_reason===`no_answer`||e.end_reason===`busy`||e.end_reason===`dial_failed`?`Voice call · ${e.end_reason.replace(`_`,` `)}`:`Voice call · answered · ${pg(e)}`:`Voice call · ${t} · on the line now`}function ZC(e){let t=e.latest;return t.status===`ended`?t.outcome!==null&&t.outcome!==``?t.outcome:`${t.channel??`a`} call · ${pg(t)}`:`On a call now`}var QC=500;async function $C(e,t){let n=[],r=0;for(;;){let i=sy.parse(await oa(e,`/v1/calls/${t}/events`,{after:r,limit:QC}));if(n.push(...i.entries),i.next===null||i.entries.length<QC)return n;r=i.next}}var ew=12;function tw(e){let t=j(),n=(0,D.useRef)(new Map),[,r]=(0,D.useState)(0),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(null),c=e?.lines.slice(0,ew)??[],l=c.map(e=>`${e.call}@${e.last_seq}`).join(` `);return(0,D.useEffect)(()=>{let e=!1,i=c.filter(e=>n.current.get(e.call)?.seq!==e.last_seq);if(i.length!==0)return a(!0),(async()=>{try{await Promise.all(i.map(async e=>{let r=await $C(t,e.call),i=JC(e,r);n.current.set(e.call,{seq:e.last_seq,voice:i,messages:YC(e,r,i)})})),e||s(null)}catch(t){e||s(na(t))}finally{e||(a(!1),r(e=>e+1))}})(),()=>{e=!0}},[l,t]),{messages:c.flatMap(e=>n.current.get(e.call)?.messages??[]).sort((e,t)=>e.at-t.at),voice:(e===void 0?void 0:n.current.get(e.latest.call))?.voice??null,loading:i,error:o}}function nw(){let e=Sr(),t=e.agent??``,n=e.call,r=vr(),i=j(),a=pC(t),o=(0,D.useMemo)(()=>WC(a.lines),[a.lines]),[s,c]=(0,D.useState)(``),l=Rh({name:`agent.conversations`,initial:292,min:200,max:520,side:`left`}),u=Rh({name:`agent.aside`,initial:316,min:240,max:560,side:`right`}),[d,f]=(0,D.useState)(!1),p=PC(),m=iw(t,a.lines.length),h=o.find(e=>n!==void 0&&e.lines.some(e=>e.call===n))??o[0],g=s.trim().toLowerCase(),_=o.filter(e=>g===``||`${rw(e,m)} ${e.handle} ${ZC(e)}`.toLowerCase().includes(g));return(0,D.useEffect)(()=>{h!==void 0&&m!==null&&(m.get(h.contact)?.unread??0)!==0&&BC(i,t,h.contact).catch(()=>void 0)},[h?.contact,m,i,t]),(0,A.jsxs)(`div`,{className:`ib`,style:l.style,children:[l.handle,(0,A.jsxs)(`div`,{className:`ib-list`,children:[(0,A.jsxs)(`div`,{className:`ib-list-head`,children:[(0,A.jsx)(`input`,{className:`ib-search`,placeholder:`Search a caller or number`,value:s,onChange:e=>c(e.target.value)}),p!==null&&(0,A.jsx)(`button`,{type:`button`,className:`ib-new`,title:`Call a number`,"aria-expanded":d,onClick:()=>f(!d),children:`+`}),d&&p!==null&&(0,A.jsx)(`div`,{className:`ib-dial`,children:(0,A.jsxs)(`div`,{className:`dial-panel`,children:[(0,A.jsxs)(`div`,{className:`dial-panel-head`,children:[(0,A.jsx)(`span`,{className:`dial-panel-title`,children:`Call a number`}),(0,A.jsx)(`button`,{type:`button`,className:`dial-panel-close`,onClick:()=>f(!1),"aria-label":`close`,children:`×`})]}),(0,A.jsx)(LC,{agent:t,outbound:p,onClose:()=>f(!1)})]})})]}),(0,A.jsxs)(`div`,{className:`ib-threads`,children:[a.error!==null&&(0,A.jsx)(`p`,{className:`ib-empty ib-refused`,children:a.error}),a.error===null&&o.length===0&&(0,A.jsxs)(`p`,{className:`ib-empty`,children:[`No conversations yet. The first call to reach `,t,` opens a thread here as it rings.`]}),o.length>0&&_.length===0&&(0,A.jsxs)(`p`,{className:`ib-empty`,children:[`Nobody here matches “`,s,`”.`]}),_.map(e=>(0,A.jsx)(aw,{thread:e,name:rw(e,m),unread:m?.get(e.contact)?.unread??0,on:e===h,onOpen:()=>void r(`/a/${t}/calls/${e.latest.call}`)},e.contact))]})]}),h===void 0?(0,A.jsx)(`div`,{className:`ib-thread`,children:(0,A.jsx)(`p`,{className:`ib-nothing`,children:a.error===null?`Pick a conversation on the left.`:``})}):(0,A.jsxs)(`div`,{className:`ib-open`,style:u.style,children:[u.handle,(0,A.jsx)(sw,{agent:t,thread:h,name:rw(h,m),door:m!==null,outbound:p},h.contact),(0,A.jsx)(AC,{agent:t,thread:h,name:rw(h,m)},`${h.contact}-aside`)]})]})}function rw(e,t){return t?.get(e.contact)?.name??KC(e)}function iw(e,t){let n=j(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{if(a)return;let t=!1;return zC(n,e).then(e=>{t||(e===null&&o(!0),i(e))},()=>void 0),()=>{t=!0}},[n,e,t,a]),r}function aw({thread:e,name:t,unread:n,on:r,onOpen:i}){return(0,A.jsxs)(`button`,{type:`button`,className:r?`ib-row ib-row-on`:`ib-row`,onClick:i,children:[(0,A.jsx)(Th,{name:t,letters:qC(e),size:36,round:!0}),(0,A.jsxs)(`span`,{className:`ib-row-main`,children:[(0,A.jsxs)(`span`,{className:`ib-row-top`,children:[(0,A.jsx)(`span`,{className:`ib-row-name`,children:t}),(0,A.jsx)(`span`,{className:`ib-row-time`,children:ow(e.latest.started_at)})]}),(0,A.jsxs)(`span`,{className:`ib-row-bottom`,children:[(0,A.jsx)(`span`,{className:e.latest.status===`ended`?`ib-row-last`:`ib-row-last ib-row-last-live`,children:ZC(e)}),n>0&&(0,A.jsx)(`span`,{className:`ib-unread`,children:n})]})]})]})}function ow(e){if(e===null)return``;let t=Sg(),n=xg(e);return n===t.today?_g(e).slice(0,5):n===t.yesterday?`Yesterday`:yg(e)}function sw({agent:e,thread:t,name:n,door:r,outbound:i}){let a=vr(),o=j(),{messages:s,voice:c,loading:l,error:u}=tw(t),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(null),[_,v]=(0,D.useState)(!1),y=(0,D.useCallback)(()=>v(!1),[]),b=i!==null&&t.contact.startsWith(`+`),x=t.latest,S=x.status!==`ended`,C=S&&c===!1?`call`:!S&&r&&x.channel===`whatsapp`?`thread`:null,w=C===null?S&&c===!0?`A live voice call — Listen in on Live to speak into it`:S?`Reading the call…`:`The conversation is closed — nothing can be written into it from here`:`Write as ${e} — the agent keeps the thread from here`,T=async()=>{if(C!==null&&d.trim()!==``){m(!0),g(null);try{C===`call`?await HC(o,x.call,d.trim()):await VC(o,e,t.contact,d.trim()),f(``)}catch(e){g(e instanceof ta?e.message:String(e))}finally{m(!1)}}};return(0,A.jsxs)(`div`,{className:`ib-thread`,children:[(0,A.jsxs)(`div`,{className:`ib-head`,children:[(0,A.jsx)(Th,{name:n,letters:qC(t),size:38,round:!0}),(0,A.jsxs)(`div`,{className:`ib-head-words`,children:[(0,A.jsx)(`div`,{className:`ib-head-name`,children:n}),(0,A.jsxs)(`div`,{className:`ib-head-sub`,children:[t.handle!==n&&`${t.handle} · `,x.channel??`—`,` · handled by `,e]})]}),(0,A.jsxs)(`div`,{className:`ib-head-actions`,children:[S&&(0,A.jsx)(`button`,{type:`button`,className:`ui-button ui-button-md`,onClick:()=>void a(`/live/${x.call}`),children:`Watch live`}),(0,A.jsx)(`button`,{type:`button`,className:`ui-button ui-button-md`,onClick:()=>void a(`/a/${e}/sessions/${x.call}`),children:`Session`}),b&&i!==null&&(0,A.jsxs)(`span`,{className:`dial-anchor`,children:[(0,A.jsx)(`button`,{type:`button`,className:`ui-button ui-button-primary ui-button-md`,"aria-expanded":_,onClick:()=>v(!_),children:`Call back`}),_&&(0,A.jsx)(IC,{agent:e,to:t.contact,outbound:i,onClose:y,onRefused:g})]})]})]}),(0,A.jsxs)(`div`,{className:`ib-messages`,children:[u!==null&&(0,A.jsx)(`p`,{className:`ib-refused-line`,children:u}),s.length===0&&u===null&&(0,A.jsx)(`p`,{className:`ib-quiet`,children:l?`Reading the conversation…`:`Nothing was said in this conversation.`}),(0,A.jsx)(cw,{messages:s})]}),h!==null&&(0,A.jsx)(`p`,{className:`ib-refused-line ib-refused-foot`,children:h}),(0,A.jsxs)(`form`,{className:`ib-composer`,onSubmit:e=>{e.preventDefault(),T()},children:[(0,A.jsx)(`input`,{className:`ib-write`,value:d,placeholder:w,disabled:C===null||p,onChange:e=>f(e.target.value)}),(0,A.jsx)(`button`,{type:`submit`,className:`ib-send`,disabled:C===null||p||d.trim()===``,children:`Send`})]})]})}function cw({messages:e}){let t=Sg(),n=``;return(0,A.jsx)(A.Fragment,{children:e.map((e,r)=>{let i=xg(e.at),a=i===n?null:i===t.today?`Today`:i===t.yesterday?`Yesterday`:yg(e.at);return n=i,(0,A.jsxs)(`div`,{className:`ib-bubble-wrap`,children:[a!==null&&(0,A.jsx)(`div`,{className:`ib-day`,children:a}),e.kind===`call`?(0,A.jsx)(`div`,{className:`ib-line ib-line-call`,children:(0,A.jsx)(`span`,{className:`ib-call`,children:e.text})}):(0,A.jsx)(`div`,{className:e.kind===`out`?`ib-line ib-line-out`:`ib-line`,children:(0,A.jsxs)(`span`,{className:e.kind===`out`?`ib-bubble ib-bubble-out`:`ib-bubble`,children:[e.text,(0,A.jsx)(`span`,{className:`ib-time`,children:_g(e.at).slice(0,5)})]})})]},`${e.call}-${String(r)}`)})})}function lw(e){let t=new Map;for(let n of e)!t.has(n)&&oy(n)&&t.set(n,yf(ty[n],{io:`input`}));return t}function uw(e,t){return e==null?`null`:typeof e==`boolean`?e?`true`:`false`:typeof e==`string`?JSON.stringify(e):typeof e==`number`?mw(e,t):Array.isArray(e)?`[${e.map(e=>uw(e,t?.items)).join(`,`)}]`:fw(e,t)}function dw(e,t){return typeof e==`string`?e:uw(e,t)}function fw(e,t){let n=pw(e,t)?.properties;return`{${Object.entries(e).map(([e,t])=>`${JSON.stringify(e)}:${uw(t,n?.[e])}`).join(`,`)}}`}function pw(e,t){return t?.oneOf===void 0?t:t.oneOf.find(t=>Object.entries(t.properties??{}).every(([t,n])=>n.const===void 0||n.const===e[t]))}function mw(e,t){if(t?.type!==`number`||!Number.isFinite(e))return String(e);let n=Math.abs(e);return e!==0&&(n<1e-4||n>=0x2386f26fc10000)?hw(e):Number.isInteger(e)?`${e}.0`:String(e)}function hw(e){let[t=``,n=``]=e.toExponential().split(`e`);return`${t}e${n.startsWith(`-`)?`-`:`+`}${n.replace(/^[+-]/,``).padStart(2,`0`)}`}var gw=[`transcription_delay`,`end_of_turn_delay`],_w=[`llm_node_ttft`,`tts_node_ttfb`,`e2e_latency`],vw=[...gw,..._w];function yw(e){return kw(e).map(([e,t])=>({field:e,value:Sw(t),unit:null}))}function bw(e,t){return Cw(e,``,t)}function xw(){let e=yf(W_,{io:`input`}),t=new Map;for(let[n,r]of Object.entries(e.properties??{}))r.items!==void 0&&t.set(n,r.items);return t}function Sw(e){return e<0?`—`:e<1?`${Math.round(e*1e3)} ms`:`${e.toFixed(2)} s`}function Cw(e,t,n){let r=[];for(let[i,a]of Object.entries(e)){let e=t+i,o=n?.properties?.[i];a!=null&&(typeof a==`object`&&!Array.isArray(a)?r.push(...Cw(a,`${e}.`,o)):r.push({field:e,value:dw(a,o),unit:ww(i)}))}return r}function ww(e){return Xy[e]??null}function Tw(e,t){let n=xw(),r=[];for(let[i,a]of Object.entries(e))for(let e of a)Ow(e,t)&&r.push({kind:i,readings:bw(e,n.get(i))});return r}var Ew=[`turn.user`,`turn.agent`];function Dw(e){let t=Aw(e);return vw.filter(e=>(t.get(e)??[]).length>0).map(e=>{let n=t.get(e)??[];return{name:e,seconds:jw(n),max:Math.max(...n),turns:n.length}})}function Ow(e,t){return`speech_id`in e&&e.speech_id===t}function kw(e){let t=e.role===`user`?gw:_w,n=e.metrics,r=[];for(let e of t){let t=n[e];typeof t==`number`&&r.push([e,t])}return r}function Aw(e){let t=new Map(vw.map(e=>[e,[]]));for(let n of e){if(!Ew.includes(n.type))continue;let e=n.data.metrics;for(let n of vw){let r=e?.[n];typeof r==`number`&&t.get(n)?.push(r)}}return t}function jw(e){let t=[...e].sort((e,t)=>e-t),n=Math.floor(t.length/2),r=t[n]??0;return t.length%2==1?r:((t[n-1]??0)+r)/2}function Mw(e,t={}){let n=j(),[r,i]=(0,D.useState)(Qy),[a,o]=(0,D.useState)(`connecting`),[s,c]=(0,D.useState)(null),l=(0,D.useRef)(t);return(0,D.useEffect)(()=>{l.current=t}),(0,D.useEffect)(()=>{let t={current:Qy()},r=!1,a=null,s=()=>i({...t.current}),u=()=>{r=!0,a?.()};return(async()=>{let i=0;try{i=await Nw(n,e,t,l)}catch(e){c(String(e)),o(`ended`);return}if(!r){if(s(),t.current.status===`ended`){o(`ended`);return}a=gb(ua(n,`/v1/calls/${e}/events`,{after:i}),n,{onEntry(e){t.current=tb(t.current,e),l.current.onEntry?.(e),Pw(e,t.current,l.current),e.type===`call.score`&&(s(),o(`ended`),u())},onPaint:s,onConnection:o,onRefused:c}),r&&a()}})(),u},[e,n]),{state:r,connection:a,error:s}}async function Nw(e,t,n,r){let i;try{i=await $C(e,t)}catch(e){if(e instanceof ta&&e.status===404)return 0;throw e}for(let e of i)n.current=tb(n.current,e),r.current.onEntry?.(e),Pw(e,n.current,r.current);return i.at(-1)?.seq??0}function Pw(e,t,n){if(e.type!==`custom`)return;let r=t.custom.at(-1);r!==void 0&&n.onCustom?.(r)}function Fw(e){let t=(0,D.useRef)([]),n=Mw(e,{onEntry(e){let n=t.current.at(-1);n!==void 0&&e.seq<=n.seq||t.current.push(e)}}),r=(0,D.useMemo)(()=>[...t.current],[n.state.seq]);return{state:n.state,entries:r,connection:n.connection,error:n.error}}function Iw({agent:e,call:t}){let{lines:n}=wb(),r=n.find(t=>t.agent===e)?.call??null,i=t??r;return(0,A.jsx)(`aside`,{className:`inspector`,"aria-label":`Inspector`,children:i===null?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Lw,{connection:null}),(0,A.jsx)(`p`,{className:`inspector-quiet`,children:`Nothing to read yet: the first call this agent takes is read here as it happens.`})]}):(0,A.jsx)(zw,{call:i,yours:t!==null},i)})}function Lw({connection:e}){return(0,A.jsxs)(`div`,{className:`inspector-head`,children:[(0,A.jsx)(`span`,{className:`inspector-title`,children:`Inspector`}),(0,A.jsx)(`span`,{className:`inspector-standing`,children:Rw(e)})]})}function Rw(e){switch(e){case`live`:return(0,A.jsx)(vh,{tone:`green`,children:`reading the log`});case`connecting`:return(0,A.jsx)(vh,{tone:`muted`,children:`opening the log`});case`reconnecting`:return(0,A.jsx)(vh,{tone:`amber`,children:`reconnecting`});case`ended`:return(0,A.jsx)(vh,{tone:`muted`,children:`call ended`});default:return(0,A.jsx)(vh,{tone:`muted`,children:`no call yet`})}}function zw({call:e,yours:t}){let[n,r]=(0,D.useState)(`call`),i=Fw(e),{state:a}=i,o=new Set,s=Dw(i.entries.filter(e=>!o.has(e.seq)&&(o.add(e.seq),!0))),c=e=>{let t=s.find(t=>t.name===e);return t===void 0?`—`:Sw(t.seconds)},l=Vw(a),u=[[`Turns`,String(a.turns.length)],[`ttft`,c(`llm_node_ttft`)],[`e2e`,c(`e2e_latency`)],[`Cost`,hg(a.cost?.eur)],[`Tokens in`,Hw(l.in)],[`Tokens out`,Hw(l.out)]],d=Object.keys(a.app_state).sort(),f=[{tab:`call`,name:`Call`},{tab:`turns`,name:`Turns`,mark:(0,A.jsx)(`span`,{className:`inspector-count`,children:a.turns.length})},{tab:`tools`,name:`Tools`,mark:(0,A.jsx)(`span`,{className:`inspector-count`,children:a.tools.length})},{tab:`state`,name:`State`}];return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Lw,{connection:i.connection}),(0,A.jsx)(`div`,{className:`inspector-tabs`,children:(0,A.jsx)(zh,{label:`Inspector`,tabs:f,on:n,onPick:r})}),n===`call`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(nh,{children:t?`This session`:`Last session`}),(0,A.jsx)(`div`,{className:`inspector-figures`,children:u.map(([e,t])=>(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`inspector-figure-label`,children:e}),(0,A.jsx)(`div`,{className:`inspector-figure`,children:t})]},e))}),!t&&(0,A.jsx)(`p`,{className:`inspector-call`,children:e})]}),n===`turns`&&(0,A.jsxs)(`div`,{className:`inspector-turns`,children:[a.turns.length===0&&(0,A.jsx)(`p`,{className:`inspector-none`,children:`No turn yet.`}),a.turns.map((e,t)=>(0,A.jsxs)(`div`,{className:`inspector-turn`,children:[(0,A.jsx)(`span`,{className:e.role===`agent`?`inspector-who inspector-who-agent`:`inspector-who`,children:e.role===`agent`?`agent`:`caller`}),(0,A.jsxs)(`span`,{className:`inspector-turn-body`,children:[(0,A.jsx)(`span`,{className:`inspector-turn-text`,children:e.text}),(0,A.jsx)(`span`,{className:`inspector-turn-meta`,children:Bw(e)})]})]},`${e.speech_id}-${t}`))]}),n===`tools`&&(0,A.jsxs)(`div`,{className:`inspector-tools`,children:[a.tools.length===0&&(0,A.jsx)(`p`,{className:`inspector-none`,children:`No tool has run.`}),a.tools.map(e=>(0,A.jsxs)(`div`,{className:`inspector-tool`,children:[(0,A.jsx)(`div`,{className:`inspector-tool-name`,children:e.name}),(0,A.jsx)(`div`,{className:`inspector-tool-args`,children:Uw(e.arguments)}),(0,A.jsx)(`div`,{className:e.status===`failed`?`inspector-tool-result inspector-tool-failed`:e.status===`running`?`inspector-tool-result inspector-tool-running`:`inspector-tool-result`,children:e.status===`failed`?e.error??`failed`:e.status===`running`?`running…`:`ok${e.summary?` · ${e.summary}`:``}`})]},e.call_id))]}),n===`state`&&(0,A.jsxs)(`div`,{className:`inspector-state`,children:[d.length===0&&(0,A.jsx)(`p`,{className:`inspector-none`,children:`The app has declared no state yet.`}),d.map(e=>(0,A.jsxs)(`div`,{className:`inspector-field`,children:[(0,A.jsx)(`span`,{className:`inspector-field-key`,children:e}),(0,A.jsx)(`span`,{className:`inspector-field-value`,children:Ww(a.app_state[e])})]},e))]}),i.error!==null&&(0,A.jsx)(`p`,{className:`inspector-refused`,children:i.error})]})}function Bw(e){if(e.role===`agent`){let t=[];return typeof e.metrics.llm_node_ttft==`number`&&t.push(`ttft ${Sw(e.metrics.llm_node_ttft)}`),typeof e.metrics.e2e_latency==`number`&&t.push(`e2e ${Sw(e.metrics.e2e_latency)}`),e.interrupted&&t.push(`interrupted`),t.join(` · `)}let t=[];return typeof e.metrics.transcription_delay==`number`&&t.push(`stt ${Sw(e.metrics.transcription_delay)}`),t.push(e.speech_id),t.join(` · `)}function Vw(e){let t=0,n=0;for(let r of e.usage)r.type===`llm_usage`&&(t+=(r.input_tokens??0)+(r.input_cached_tokens??0),n+=r.output_tokens??0);return{in:t,out:n}}function Hw(e){return e.toLocaleString(`en-US`).replace(/,/g,` `)}function Uw(e){let t=Object.entries(e).map(([e,t])=>`${e}=${Ww(t)}`);return t.length===0?`no arguments`:t.join(` · `)}function Ww(e){return typeof e==`string`?e:JSON.stringify(e)}var Gw=`supervisor.`;function Kw(e){if(!e.type.startsWith(Gw))return null;let t=ay(e);switch(t.type){case`supervisor.whispered`:return{said:`supervisor whispered: ${t.data.text}`,by:qw(t.data.by)};case`supervisor.said`:return{said:`supervisor made the agent say: ${t.data.text}`,by:qw(t.data.by)};case`supervisor.took_over`:return{said:`supervisor took the line`,by:qw(t.data.by)};case`supervisor.released`:return{said:`supervisor handed the line back`,by:qw(t.data.by)};case`supervisor.transferred`:return{said:`supervisor transferred the call to ${t.data.to}`,by:qw(t.data.by)};case`supervisor.ended`:return{said:`supervisor ended the call${Jw(t.data.reason)}`,by:qw(t.data.by)};default:return null}}function qw(e){return e.name??e.id}function Jw(e){return e==null?``:`: ${e}`}function Yw(e,t){let n=[],r=[],i=()=>{r.length>0&&(n.push({kind:`quiet`,seq:r[0]?.seq??0,entries:r}),r=[])};for(let a of e){let e=Xw(a,t);if(e===null){r.push(a);continue}i(),n.push(e)}return i(),n}function Xw(e,t){let n=e.seq,r=Kw(e);if(r!==null)return{kind:`supervisor`,seq:n,mark:r};let i=ay(e);switch(i.type){case`turn.user`:case`turn.agent`:{let e=Zw(t,i.type===`turn.user`?`user`:`agent`,i.data.speech_id);return e===void 0?null:{kind:`turn`,seq:n,turn:e}}case`tool.call`:{let e=Qw(t.tools,e=>e.call_id===i.data.call_id);return e===void 0?null:{kind:`tool`,seq:n,run:e}}case`state.changed`:return{kind:`state`,seq:n,changed:i.data.changed,cause:i.data.cause??null};case`confirm.request`:{let e=Qw(t.confirms,e=>e.call_id===i.data.call_id);return e===void 0?null:{kind:`confirm`,seq:n,confirm:e}}case`event.received`:return{kind:`event`,seq:n,name:i.data.name,source:i.data.source,data:i.data.data};case`memory.ops`:return{kind:`memory`,seq:n,ops:i.data};case`docs.sources`:return{kind:`sources`,seq:n,sources:i.data};default:return null}}function Zw(e,t,n){return Qw(e.turns,e=>e.role===t&&e.speech_id===n)}function Qw(e,t){for(let n=e.length-1;n>=0;--n){let r=e[n];if(t(r))return r}}function $w(e){let t=new Map,n=new Set;for(let r of e)if(r.type===`agent.transcript`){let e=r.data;if(e.final)continue;t.set(e.speech_id,(t.get(e.speech_id)??``)+e.text)}else r.type===`turn.agent`&&n.add(r.data.speech_id);return{streaming:t,settled:n}}var eT=new Map,tT=1,nT=.18;function rT(e,t,n){let[r,i]=(0,D.useState)(()=>n?t.length:eT.get(e)??0),a=(0,D.useRef)(t.length);return a.current=t.length,(0,D.useEffect)(()=>{if(n){eT.set(e,t.length),i(t.length);return}let r=0,o=()=>{i(t=>{let n=a.current-t;if(n<=0)return t;let r=Math.min(a.current,t+Math.max(tT,Math.ceil(n*nT)));return eT.set(e,r),r}),r=requestAnimationFrame(o)};return r=requestAnimationFrame(o),()=>cancelAnimationFrame(r)},[e,n,t.length]),t.slice(0,Math.min(r,t.length))}var iT=80;function aT({watched:e,pending:t,onConfirmed:n}){let r=sT(e.entries),i=Yw(r,e.state),{streaming:a,settled:o}=$w(r),s=(0,D.useRef)(null),c=(0,D.useRef)(!0),[l]=(0,D.useState)(()=>performance.now()),[u,d]=(0,D.useState)(!1);(0,D.useEffect)(()=>{let e=window.setTimeout(()=>d(!0),600);return()=>window.clearTimeout(e)},[l]);let f=i.filter(e=>e.kind===`turn`&&e.turn.role===`user`).length;(0,D.useEffect)(()=>{let e=[...i].reverse().find(e=>e.kind===`turn`&&e.turn.role===`user`);e?.kind===`turn`&&n(e.turn.text)},[f]);let p=[...a.entries()].filter(([e])=>!o.has(e)),m=e.state.agent_state===`thinking`&&p.length===0;return(0,D.useLayoutEffect)(()=>{let e=s.current;e!==null&&c.current&&(e.scrollTop=e.scrollHeight)}),(0,A.jsxs)(`div`,{className:`chat-lines`,ref:s,onScroll:e=>{let t=e.currentTarget;c.current=t.scrollHeight-t.scrollTop-t.clientHeight<iT},children:[i.map(e=>{if(e.kind===`turn`){let t=e.turn.speech_id??`seq-${String(e.seq)}`;return e.turn.role===`agent`?(0,A.jsx)(oT,{speech:t,text:e.turn.text,instant:!u,done:!0},`turn-${String(e.seq)}`):(0,A.jsx)(`div`,{className:`chat-line chat-line-user`,children:(0,A.jsx)(`span`,{className:`chat-bubble chat-bubble-you`,children:e.turn.text})},`turn-${String(e.seq)}`)}return e.kind===`tool`?(0,A.jsx)(`div`,{className:`chat-line chat-line-tool`,children:(0,A.jsxs)(`span`,{className:`chat-tool chat-tool-${e.run.status}`,children:[e.run.name,` · `,e.run.error??e.run.summary??(e.run.status===`running`?`running…`:`done`)]})},`tool-${String(e.seq)}`):null}),p.map(([e,t])=>(0,A.jsx)(oT,{speech:e,text:t,instant:!1,done:!1},`writing-${e}`)),t.map(e=>(0,A.jsx)(`div`,{className:`chat-line chat-line-user chat-line-pending`,children:(0,A.jsx)(`span`,{className:`chat-bubble chat-bubble-you`,children:e.text})},`pending-${String(e.id)}`)),m&&(0,A.jsx)(`div`,{className:`chat-line chat-line-agent`,children:(0,A.jsxs)(`span`,{className:`chat-bubble chat-typing`,"aria-label":`the agent is writing`,children:[(0,A.jsx)(`i`,{}),(0,A.jsx)(`i`,{}),(0,A.jsx)(`i`,{})]})}),e.error!==null&&(0,A.jsx)(`p`,{className:`chat-error`,children:e.error})]})}function oT({speech:e,text:t,instant:n,done:r}){let i=rT(e,t,n),a=i.length>=t.length;return(0,A.jsx)(`div`,{className:`chat-line chat-line-agent`,children:(0,A.jsxs)(`span`,{className:`chat-bubble`,children:[i,!(r&&a)&&(0,A.jsx)(`span`,{className:`chat-caret`,"aria-hidden":!0})]})})}function sT(e){let t=new Set;return e.filter(e=>!t.has(e.seq)&&(t.add(e.seq),!0))}var cT=z({agent:P().nullable(),states:R(P())}),lT=z({call:P()});async function uT(e,t){return cT.parse(await wC(e,t,`chat.roster`))}async function dT(e,t,n,r){let i={agent:t,...n===``?{}:{as:n},...r===``?{}:{golden:r}};return lT.parse(await wC(e,t,`chat.start`,i)).call}async function fT(e,t,n,r){lT.parse(await wC(e,t,`chat.say`,{call:n,text:r}))}async function pT(e,t,n){lT.parse(await wC(e,t,`chat.end`,{call:n}))}function mT(){let e=Sr(),t=e.agent??``,n=e.call;return(0,A.jsxs)(`div`,{className:`chat-grid`,children:[(0,A.jsx)(`div`,{className:`chat-column`,children:n===void 0?(0,A.jsx)(gT,{agent:t}):(0,A.jsx)(_T,{agent:t,call:n})}),(0,A.jsx)(Iw,{agent:t,call:n??null})]})}function hT({agent:e,children:t}){return(0,A.jsxs)(`div`,{className:`chat-head`,children:[(0,A.jsxs)(`div`,{className:`chat-head-words`,children:[(0,A.jsxs)(`div`,{className:`chat-title`,children:[`Chat with `,e]}),(0,A.jsx)(`div`,{className:`chat-sub`,children:`The same agent, typed instead of spoken — every turn still lands in the log.`})]}),t]})}function gT({agent:e}){let t=j(),n=vr(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(null),[d,f]=(0,D.useState)(!1);(0,D.useEffect)(()=>{let n=!1;return uT(t,e).then(e=>{n||i(e)},e=>{n||u(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[t,e]);let p=async r=>{r.preventDefault(),f(!0),u(null);try{n(`/a/${e}/dev-chat/${await dT(t,e,a.trim(),s)}`)}catch(e){u(e instanceof ta?e.message:String(e))}finally{f(!1)}};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(hT,{agent:e}),(0,A.jsx)(`div`,{className:`chat-lines`,children:(0,A.jsxs)(`div`,{className:`chat-start ui-card`,children:[(0,A.jsx)(`div`,{className:`ui-card-head`,children:(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Start a conversation`})}),(0,A.jsxs)(`div`,{className:`ui-card-body`,children:[r===null&&l===null&&(0,A.jsxs)(`p`,{className:`chat-note`,children:[`Asking the terminal that holds `,e,`…`]}),r!==null&&r.agent!==e&&(0,A.jsx)(`p`,{className:`chat-note`,children:r.agent===null?"No agent class in the directory this agent's `pinecall start` runs in, so there is nothing to chat with. Run `pinecall start` where its agent.tsx is.":`The process holding the agent runs in ${r.agent}'s directory: to chat with ${e}, run \`pinecall start\` there.`}),r!==null&&r.agent===e&&(0,A.jsxs)(`form`,{className:`chat-start-form`,onSubmit:e=>void p(e),children:[(0,A.jsx)(`p`,{className:`chat-note`,children:`The class of this directory, in writing. Its tools run in the terminal that serves this page, and a conversation can open part-way through, in the state one of the goldens declares.`}),(0,A.jsx)(uh,{label:`As`,children:(0,A.jsx)(G,{value:a,placeholder:`a phone number, a customer id — or nobody`,onChange:e=>o(e.target.value)})}),r.states.length>0&&(0,A.jsx)(uh,{label:`From`,children:(0,A.jsxs)(ch,{value:s,onChange:e=>c(e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`the call's own opening`}),r.states.map(e=>(0,A.jsxs)(`option`,{value:e,children:[`the state of `,e]},e))]})}),(0,A.jsx)(`div`,{children:(0,A.jsx)(W,{kind:`primary`,size:`form`,type:`submit`,disabled:d,children:d?`Opening…`:`Start the chat`})})]}),(0,A.jsx)($m,{children:l})]})]})})]})}function _T({agent:e,call:t}){let n=j(),r=vr(),[i,a]=(0,D.useState)([]),[o,s]=(0,D.useState)(null),c=(0,D.useRef)(0),l=Fw(t),u=l.state.status===`ended`||l.connection===`ended`,d=async()=>{try{await pT(n,e,t)}catch(e){s(e instanceof ta?e.message:String(e));return}r(`/a/${e}/sessions/${t}`)};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(hT,{agent:e,children:(0,A.jsxs)(`div`,{className:`chat-head-actions`,children:[(0,A.jsx)(k,{className:`chat-whole`,to:`/a/${e}/sessions/${t}`,children:`Session`}),!u&&(0,A.jsx)(W,{size:`md`,onClick:()=>void d(),title:`hanging up seals the log and runs the judges`,children:`Hang up`})]})}),(0,A.jsx)(aT,{watched:l,pending:i,onConfirmed:e=>a(t=>{let n=t.findIndex(t=>t.text===e);return n===-1?t:[...t.slice(0,n),...t.slice(n+1)]})}),o!==null&&(0,A.jsx)(`div`,{className:`chat-refused`,children:(0,A.jsx)($m,{children:o})}),u?(0,A.jsx)(`div`,{className:`chat-over`,children:`This chat has ended — it is on the session, whole.`}):(0,A.jsx)(vT,{agent:e,call:t,onRefused:s,onSent:e=>{c.current+=1;let t={id:c.current,text:e};return a(e=>[...e,t]),()=>a(e=>e.filter(e=>e.id!==t.id))}})]})}function vT({agent:e,call:t,onSent:n,onRefused:r}){let i=j(),[a,o]=(0,D.useState)(``),s=async s=>{s.preventDefault();let c=a.trim();if(c===``)return;o(``),r(null);let l=n(c);try{await fT(i,e,t,c)}catch(e){l(),o(c),r(e instanceof ta?e.message:String(e))}};return(0,A.jsxs)(`form`,{className:`chat-composer`,onSubmit:e=>void s(e),children:[(0,A.jsx)(`input`,{className:`chat-say`,value:a,autoFocus:!0,placeholder:`Ask the agent something`,onChange:e=>o(e.target.value)}),(0,A.jsx)(`button`,{type:`submit`,className:`chat-send`,disabled:a.trim()===``,children:`Send`})]})}var yT=z({golden:P(),model:P(),call:P()}),bT=z({metric:P(),score:F(),passed:L(),reason:P(),criteria:P(),judge_calls:I()}),xT=z({model:P(),golden:P(),scores:R(bT),summary:kp(P(),mp()).nullable()}),ST=z({models:R(P()),goldens:R(P()),metrics:R(P()),judge_calls:I(),runs:R(xT),failures:R(z({model:P(),golden:P(),metric:P()}))}),CT=z({runs:R(z({id:P(),agent:P(),started_at:F(),finished_at:F().nullable(),status:V([`running`,`done`,`failed`]),calls:R(yT),matrix:ST.nullable(),error:P().nullable()}))}),wT=200;async function TT(e){return CT.parse(await oa(e,`/v1/evals/runs`,{limit:wT})).runs}async function ET(e,t){return CT.parse(await oa(e,`/v1/evals/runs`,{agent:t,limit:wT})).runs}var DT=z({held:I(),settled:I(),percent:F()}),OT=z({judge:P(),before:DT.nullable(),now:DT.nullable(),delta:F().nullable()}),kT=z({call:P(),judge:P(),seqs:R(I()),reason:P()}),AT=z({agent:P(),window:F(),baseline:F(),threshold:F(),drift:z({judges:R(OT),notJudged:z({now:I(),before:I()}),broke:R(kT),worst:F().nullable()})});async function jT(e,t,n,r){return AT.parse(await wC(e,t,`drift.read`,{agent:t,window:n,baseline:r}))}var MT=z({check:P(),status:P(),detail:P()}),NT=z({call:P(),agent:P(),passed:L(),verdicts:R(MT)});async function PT(e,t){return NT.parse(await ca(e,`/v1/evals/replay/${encodeURIComponent(t)}`,{}))}var FT=z({path:P(),candidate:z({name:P(),input:R(P())}),notes:R(P())});async function IT(e,t,n){return FT.parse(await wC(e,t,`promote.write`,{call:n}))}var LT=z({run:P(),folder:P(),goldens:R(P())}),RT=z({run:P(),agent:P(),golden:P(),model:P(),call:P(),declared:mp(),verdicts:R(z({metric:P(),passed:L(),criteria:P(),reason:P()})),asked:mp()});async function zT(e,t,n){return LT.parse(await wC(e,t,`reproductions.roster`,{run:n}))}async function BT(e,t,n,r){return RT.parse(await wC(e,t,`reproductions.read`,{run:n,golden:r}))}var VT=`minmax(0,1.2fr) minmax(0,1.3fr) 90px minmax(0,1fr) 80px`,HT=`minmax(0,1fr) 150px 70px minmax(0,2fr) 90px`;function UT(){let e=j(),{agents:t,lines:n}=wb(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null);(0,D.useEffect)(()=>{let t=!1;return TT(e).then(e=>{t||i(e)},e=>{t||(i([]),o(e instanceof ta?e.message:String(e)))}),()=>{t=!0}},[e]);let s=n.filter(e=>e.score!=null),c=s.filter(e=>e.score?.passed===!1),l=[...new Set([...t.map(e=>e.slug),...(r??[]).map(e=>e.agent),...s.map(e=>e.agent)])].sort().map(e=>WT(e,r??[],s)),u=s.length-c.length,d=l.filter(e=>e.suite!==null),f=d.filter(e=>e.suite!==null&&e.suite.held===e.suite.cells).length;return(0,A.jsxs)(Dh,{width:1060,tight:!0,children:[(0,A.jsx)(Oh,{title:`Evals`,lede:`How every agent is doing: the suites run on purpose, and the real calls judged at hang-up.`}),(0,A.jsx)($m,{children:a}),(0,A.jsxs)(kh,{min:170,children:[(0,A.jsx)(Ah,{size:`small`,label:`Calls judged`,value:s.length,of:`of the last ${n.length}`}),(0,A.jsx)(Ah,{size:`small`,label:`Held`,value:s.length===0?`—`:Tg(u/s.length),accent:!0}),(0,A.jsx)(Ah,{size:`small`,label:`Did not hold`,value:c.length}),(0,A.jsx)(Ah,{size:`small`,label:`Suites green`,value:d.length===0?`—`:`${f} of ${d.length}`})]}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`By agent`,meta:`a row opens that agent's Evals: its goldens, its runs, its drift`}),l.length===0?(0,A.jsx)(Qm,{children:`No agent is held here yet.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:VT,labels:[`Agent`,`Last suite`,`Judged`,`Held on real calls`,``]}),l.map(e=>(0,A.jsxs)(Mh,{columns:VT,to:`/a/${e.slug}/evals`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.slug}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.suite===null?(0,A.jsx)(`span`,{className:`oev-none`,children:`no suite run in this world`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(vh,{tone:e.suite.held===e.suite.cells?`green`:`red`,children:[e.suite.held,`/`,e.suite.cells]}),` `,(0,A.jsx)(`span`,{className:`oev-when`,children:bg(e.suite.at)})]})}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:e.judged}),(0,A.jsx)(`span`,{className:`oev-held`,children:e.judged===0?(0,A.jsx)(`span`,{className:`oev-none`,children:`nothing judged yet`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(Eh,{share:e.held/e.judged}),(0,A.jsx)(`span`,{className:`oev-share`,children:Tg(e.held/e.judged)})]})}),(0,A.jsx)(`span`,{className:`ui-cell-end oev-open`,children:`Open →`})]},e.slug))]})]}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Calls that did not hold`,meta:`a judge answered broken — the reason is the judge's own`}),c.length===0?(0,A.jsx)(Qm,{children:s.length===0?`No call has been judged yet. Judging is turned on from Home.`:`Every judged call held.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:HT,labels:[`Caller`,`Agent`,`Score`,`Why`,`When>`]}),c.slice(0,40).map(e=>(0,A.jsxs)(Mh,{columns:HT,to:`/sessions/${e.call}`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:Dg(e)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.agent}),(0,A.jsx)(`span`,{className:`ui-cell`,children:(0,A.jsxs)(vh,{tone:`red`,children:[e.score?.held,`/`,e.score?.judged]})}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.score?.reason??`—`}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-cell-end`,children:bg(e.started_at)})]},e.call))]})]})]})}function WT(e,t,n){let r=t.find(t=>t.agent===e&&t.status===`done`&&t.matrix!==null),i=r?.matrix??null,a=n.filter(t=>t.agent===e);return{slug:e,suite:r===void 0||i===null?null:{at:r.started_at,cells:i.runs.length,held:i.runs.filter(e=>e.scores.every(e=>e.passed)).length,failing:[...new Set(i.failures.map(e=>e.golden))]},judged:a.length,held:a.filter(e=>e.score?.passed===!0).length}}var GT=z({agent:P().nullable(),golden:P().nullable(),questions:I(),cases:R(P())});async function KT(e,t){return Dy.parse(await oa(e,`/v1/contacts/${encodeURIComponent(t)}/memory`))}async function qT(e,t){return Oy.parse(await la(e,`/v1/contacts/${encodeURIComponent(t)}/memory`))}async function JT(e,t){return GT.parse(await wC(e,t,`memory.roster`,{agent:t}))}async function YT(e,t){return Ay.parse(await wC(e,t,`memory.eval`,{agent:t}))}async function XT(e,t){return Py.parse(await wC(e,t,`memory.extraction`,{agent:t}))}var ZT=z({facts:R(z({id:P(),contact:P(),text:P(),category:P().nullish(),written_at:F()})),next:xp([P(),F()]).nullish()});async function QT(e,t){try{return ZT.parse(await oa(e,`/v1/agents/${encodeURIComponent(t)}/memory`)).facts}catch(e){if(e instanceof ta&&e.status===404)return null;throw e}}async function $T(e,t){await la(e,`/v1/memory/facts/${encodeURIComponent(t)}`)}var eE=z({facts:R(z({id:P(),agent:P(),contact:P(),text:P(),category:P().nullish(),written_at:F()})),next:P().nullish()});async function tE(e,t,n){let r={};t!==``&&(r.q=t),n!==null&&(r.after=n);try{return eE.parse(await oa(e,`/v1/memory`,r))}catch(e){if(e instanceof ta&&e.status===404)return null;throw e}}var nE=`150px 140px minmax(0,1fr) 100px 64px`;function rE(e){return e.startsWith(`+`)?Eg(e):e}function iE(e){return e instanceof Error?e.message:String(e)}function aE(){let e=j(),[t,n]=(0,D.useState)(``),[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(void 0),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null);(0,D.useEffect)(()=>{let e=window.setTimeout(()=>i(t.trim()),300);return()=>window.clearTimeout(e)},[t]),(0,D.useEffect)(()=>{let t=!1;return u(null),tE(e,r,null).then(e=>{t||(o(e===null?null:e.facts),c(e?.next??null))},e=>{t||u(iE(e))}),()=>{t=!0}},[e,r]);let d=async()=>{if(s!==null)try{let t=await tE(e,r,s);if(t===null)return;o(e=>[...e??[],...t.facts]),c(t.next??null)}catch(e){u(iE(e))}},f=async t=>{if(window.confirm(`Drop "${t.text}"? The rest of what memory keeps about ${rE(t.contact)} stays.`)){u(null);try{await $T(e,t.id),o(e=>(e??[]).filter(e=>e.id!==t.id))}catch(e){u(iE(e))}}};return(0,A.jsxs)(Dh,{width:1060,tight:!0,children:[(0,A.jsx)(Oh,{title:`Memory`,ledeWidth:640,lede:`What every agent carries between calls with the same caller — newest first, each fact with the agent whose call taught it, droppable one row at a time.`}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Remembered`,meta:a?`${a.length}${s===null?``:`+`} facts`:void 0,children:(0,A.jsx)(`div`,{className:`mem-look`,children:(0,A.jsx)(G,{size:`sm`,value:t,placeholder:`Search a caller, a word, a category`,onChange:e=>n(e.target.value)})})}),a===void 0?(0,A.jsx)(Qm,{children:`Asking the gateway what the agents remember…`}):a===null?(0,A.jsx)(Qm,{children:`This gateway keeps no memory: it runs without the database memory lives in.`}):a.length===0?(0,A.jsx)(Qm,{children:r===``?"No agent remembers anything about any caller yet. An agent that declares `memory` writes what it learns when a call hangs up.":`Nothing remembered matches.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:nE,labels:[`Caller`,`Agent`,`Remembered`,`Written`,`Action>`]}),a.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:nE},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,title:e.contact,children:rE(e.contact)}),(0,A.jsx)(`span`,{className:`ui-clip`,children:(0,A.jsx)(k,{to:`/a/${encodeURIComponent(e.agent)}/memory`,children:e.agent})}),(0,A.jsxs)(`span`,{className:`mem-fact`,children:[e.text,e.category?(0,A.jsxs)(`span`,{className:`mem-superseded`,children:[` · `,e.category]}):null]}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:yg(e.written_at)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(oh,{danger:!0,onClick:()=>void f(e),children:`Drop`})})]},e.id)),s!==null&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:(0,A.jsx)(W,{size:`sm`,onClick:()=>void d(),children:`Load more`})})]})]}),(0,A.jsx)($m,{children:l})]})}var oE=(0,D.createContext)(null);function sE({children:e}){let{pathname:t,search:n}=gr(),r=`${t}${n}`,i=(0,D.useRef)({now:r,before:null});return i.current.now!==r&&(i.current={now:r,before:i.current.now}),(0,A.jsx)(oE.Provider,{value:i.current.before,children:e})}function cE(){return(0,D.useContext)(oE)}function lE(e){let t=cE(),{pathname:n,search:r}=gr(),i=t!==null&&t.startsWith(`/`)&&!t.startsWith(`//`)&&t!==`${n}${r}`?t:e;return{to:i,name:Hm(i)?.name??`Back`}}async function uE(e){let[t,n]=await Promise.all([Ey.parse(await oa(e,`/v1/knowledge`)),qy.parse(await oa(e,`/v1/knowledge/attached`))]),r=new Map(n.bases.map(e=>[e.base,e.agents]));return t.bases.map(e=>({...e,agents:r.get(e.base)??[]}))}function dE(e,t){return`/v1/knowledge/${encodeURIComponent(e)}/files/${t.split(`/`).map(encodeURIComponent).join(`/`)}`}async function fE(e,t){return Wy.parse(await oa(e,`/v1/knowledge/${encodeURIComponent(t)}`))}async function pE(e,t,n){return Gy.parse(await oa(e,dE(t,n)))}async function mE(e,t,n,r){return Ky.parse(await sa(e,dE(t,n),{text:r}))}async function hE(e,t,n){await la(e,dE(t,n))}var gE=`minmax(0,1fr) 110px 90px 150px 70px`,_E=`new`;function vE(e){return e instanceof Error?e.message:String(e)}function yE(){let e=j(),t=Sr().base??``,[n,r]=Yi(),i=n.get(`file`),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(null),[_,v]=(0,D.useState)(null),y=(0,D.useCallback)(async()=>{o(await fE(e,t))},[e,t]);(0,D.useEffect)(()=>{let e=!1;return y().catch(t=>{e||v(vE(t))}),()=>{e=!0}},[y]),(0,D.useEffect)(()=>{let n=!1;if(g(null),i!==null){if(i===_E){c(``),u(``),f(``);return}return pE(e,t,i).then(e=>{n||(c(e.path),u(e.text),f(e.text))},e=>{n||v(vE(e))}),()=>{n=!0}}},[e,t,i]);let b=e=>r(e===null?{}:{file:e}),x=async()=>{let n=s.trim();if(n===``){v(`name the file first: a path like faq/horarios.md`);return}m(!0),v(null);try{let r=await mE(e,t,n,l);f(l),g(`${r.path} kept · ${r.chunks} chunk${r.chunks===1?``:`s`} · ${Math.round(r.took_ms)} ms`),await y(),i!==n&&b(n)}catch(e){v(vE(e))}finally{m(!1)}},S=async n=>{if(window.confirm(`Take ${n} out of ${t}? The agent stops searching it on the next call.`)){v(null);try{await hE(e,t,n),i===n&&b(null),await y()}catch(e){v(vE(e))}}},C=async n=>{let r=Array.from(n.target.files??[]);if(n.target.value=``,r.length!==0){m(!0),v(null);try{for(let n of r)await mE(e,t,n.name,await n.text());await y(),b(r[r.length-1].name),g(`${r.length} file${r.length===1?``:`s`} added`)}catch(e){v(vE(e))}finally{m(!1)}}},w=l!==d||i===_E&&s.trim()!==``,T=lE(`/docs`);return(0,A.jsxs)(Dh,{width:1060,children:[(0,A.jsx)(Oh,{title:t,back:(0,A.jsxs)(k,{to:T.to,children:[`← `,T.name]}),ledeWidth:640,lede:`The documents the agent searches, one file each. Open one to read or change it, add one from your disk or write it here, take one out. Every change is searchable on the next call.`,actions:(0,A.jsxs)(`div`,{className:`od-actions`,children:[(0,A.jsxs)(`label`,{className:p?`ui-button ui-button-form od-upload od-busy`:`ui-button ui-button-form od-upload`,children:[`Add files…`,(0,A.jsx)(`input`,{type:`file`,accept:`.md,.markdown,.txt,text/markdown,text/plain`,multiple:!0,disabled:p,"aria-label":`Add files to this base`,onChange:e=>void C(e)})]}),(0,A.jsx)(W,{kind:`primary`,size:`form`,disabled:p,onClick:()=>b(_E),children:`Write one`})]})}),(0,A.jsx)($m,{children:_}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Files`,meta:a===null?void 0:`${a.files.length} file${a.files.length===1?``:`s`}`}),a===null?(0,A.jsx)(Qm,{children:_===null?`Asking the gateway…`:`The files could not be read.`}):a.kept?a.files.length===0?(0,A.jsx)(Qm,{children:`No file in this base. Add one above.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:gE,labels:[`File`,`Characters`,`Chunks`,`Arrived`,``]}),a.files.map(e=>(0,A.jsxs)(Mh,{columns:gE,onClick:()=>b(e.path),children:[(0,A.jsx)(`span`,{className:i===e.path?`ui-cell-strong ui-clip od-open`:`ui-cell-strong ui-clip`,children:e.path}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.chars.toLocaleString(`en-US`)}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.chunks}),(0,A.jsx)(`span`,{className:`ui-cell`,children:vg(e.pushed_at)}),(0,A.jsx)(`span`,{className:`ui-cell od-row-end`,children:(0,A.jsx)(oh,{danger:!0,onClick:()=>void S(e.path),children:`Take out`})})]},e.path))]}):(0,A.jsx)(Qm,{children:"This base was pushed before its files were kept, so there is nothing to open here yet. Push it again from its project (`pinecall docs push`), or add a file: from then on the files are kept."})]}),i!==null&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:i===_E?`A new file`:i,meta:i===_E?void 0:`${l.length.toLocaleString(`en-US`)} characters`,children:(0,A.jsx)(oh,{onClick:()=>b(null),children:`Close`})}),(0,A.jsxs)(`div`,{className:`od-editor`,children:[i===_E&&(0,A.jsx)(`input`,{className:`ui-input od-path`,value:s,placeholder:`its path in the base: faq/horarios.md`,spellCheck:!1,"aria-label":`Its path in the base`,onChange:e=>c(e.target.value)}),(0,A.jsx)(`textarea`,{className:`ui-textarea od-text`,value:l,spellCheck:!1,"aria-label":i===_E?`The new file`:i,placeholder:`# Horarios
63
+
64
+ De lunes a viernes, de 9:00 a 20:00.`,onChange:e=>u(e.target.value)}),(0,A.jsxs)(`div`,{className:`od-editor-foot`,children:[(0,A.jsx)(W,{kind:`primary`,size:`form`,disabled:p||!w,onClick:()=>void x(),children:p?`Keeping…`:i===_E?`Add to the base`:`Save`}),(0,A.jsx)(`span`,{className:`od-said`,children:h??(w?`Not kept yet.`:`Markdown. Headings are what a search finds a passage by.`)})]})]})]})]})}var bE=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function xE({taken:e,onCancel:t}){let n=j(),r=vr(),[i,a]=(0,D.useState)(``),[o,s]=(0,D.useState)(`upload`),[c,l]=(0,D.useState)([]),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(``),[m,h]=(0,D.useState)(!1),[g,_]=(0,D.useState)(null),[v,y]=(0,D.useState)([]),b=bE.test(i),x=e.includes(i),S=o===`upload`?c.length>0:u.trim()!==``&&f.trim()!==``,C=b&&!x&&S&&!m,w=o===`upload`?c.length:1,T=e=>l(Array.from(e.target.files??[])),ee=async()=>{h(!0),_(null),y([]);let e=[];try{if(o===`upload`)for(let t of c)await mE(n,i,t.name,await t.text()),e.push(t.name);else await mE(n,i,u.trim(),f),e.push(u.trim());r(`/docs/${encodeURIComponent(i)}`)}catch(t){_(t instanceof Error?t.message:String(t)),y(e),h(!1)}};return(0,A.jsxs)(`div`,{className:`ui-card nb`,children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`New base`}),(0,A.jsx)(`span`,{className:`ui-card-meta`,children:`a set of documents an agent searches`})]}),(0,A.jsxs)(`div`,{className:`nb-body`,children:[(0,A.jsxs)(`label`,{className:`nb-field`,children:[(0,A.jsx)(`span`,{className:`nb-label`,children:`Name`}),(0,A.jsx)(`span`,{className:`nb-hint`,children:`How agents attach it, in their Settings ▸ Bases. Lower-case words joined by hyphens.`}),(0,A.jsx)(G,{value:i,spellCheck:!1,placeholder:`cleaning-services`,onChange:e=>a(e.target.value.toLowerCase().replace(/\s+/g,`-`))}),i!==``&&!b&&(0,A.jsx)(`span`,{className:`nb-bad`,children:`Only a–z, 0–9 and single hyphens between words.`}),x&&(0,A.jsxs)(`span`,{className:`nb-bad`,children:[`There is a base called `,i,` already: open it to add files.`]})]}),(0,A.jsxs)(`div`,{className:`nb-field`,children:[(0,A.jsx)(`span`,{className:`nb-label`,children:`First documents`}),(0,A.jsx)(`span`,{className:`nb-hint`,children:`A base starts with at least one. Markdown works best: its headings are what a search finds a passage by.`}),(0,A.jsx)(dh,{options:[{value:`upload`,label:`Upload files`},{value:`write`,label:`Write one`}],value:o,onChange:s}),o===`upload`?(0,A.jsxs)(`label`,{className:`nb-drop`,children:[(0,A.jsx)(`input`,{type:`file`,accept:`.md,.markdown,.txt,text/markdown,text/plain`,multiple:!0,"aria-label":`The base’s first files`,onChange:T}),c.length===0?(0,A.jsx)(`span`,{children:`Choose .md or .txt files — several at once`}):(0,A.jsxs)(`span`,{children:[c.length,` file`,c.length===1?``:`s`,`: `,c.map(e=>e.name).join(`, `)]})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(G,{value:u,spellCheck:!1,placeholder:`its path in the base: services/move-out.md`,"aria-label":`Its path in the base`,onChange:e=>d(e.target.value)}),(0,A.jsx)(lh,{rows:8,value:f,spellCheck:!1,"aria-label":`The document`,placeholder:`# Move-out cleaning
65
+
66
+ What is included, how long it takes, how to prepare.`,onChange:e=>p(e.target.value)})]})]})]}),(0,A.jsxs)(`div`,{className:`nb-foot`,children:[(0,A.jsx)(W,{kind:`primary`,size:`form`,disabled:!C,onClick:()=>void ee(),children:m?`Creating…`:`Create base`}),(0,A.jsx)(W,{size:`form`,onClick:t,children:`Cancel`})]}),g!==null&&(0,A.jsxs)(`p`,{className:`nb-landed`,children:[(0,A.jsx)(`span`,{className:`nb-bad`,children:g}),v.length===0?(0,A.jsxs)(`span`,{children:[`Nothing landed: there is no base called `,i,`. Nothing was made under that name, so create it again once the refusal above is answered.`]}):(0,A.jsxs)(`span`,{children:[v.length,` of `,w,` landed, so the base `,(0,A.jsx)(`b`,{children:i}),` exists already with `,v.join(`, `),`. Create again to send the rest — a file that is in is written over, not doubled — or `,(0,A.jsxs)(k,{to:`/docs/${encodeURIComponent(i)}`,children:[`open `,i]}),` and add them there.`]})]})]})}var SE=`minmax(0,1fr) 90px 140px 150px minmax(0,1fr)`;function CE(e){return e instanceof Error?e.message:String(e)}function wE(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{let t=!1;return uE(e).then(e=>{t||n(e)},e=>{t||i(CE(e))}),()=>{t=!0}},[e]),(0,A.jsxs)(Dh,{width:1060,tight:!0,children:[(0,A.jsx)(Oh,{title:`Docs`,ledeWidth:640,lede:"Every base of documents in this world, and which agents search it. Create one here, or push a whole folder from a project with `pinecall docs push`; open a base to read, add, edit or take out its files, and attach it to an agent in its Settings.",actions:!a&&(0,A.jsx)(W,{kind:`primary`,size:`form`,onClick:()=>o(!0),children:`New base`})}),a&&(0,A.jsx)(xE,{taken:(t??[]).map(e=>e.base),onCancel:()=>o(!1)}),(0,A.jsx)($m,{children:r}),(0,A.jsx)(H,{children:t===null?(0,A.jsx)(Qm,{children:r===null?`Asking the gateway…`:`The bases could not be read.`}):t.length===0?(0,A.jsx)(Qm,{children:"No base yet. Create one with New base, or push a folder from a project with `pinecall docs push`."}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:SE,labels:[`Base`,`Chunks`,`Embedder`,`Pushed`,`Read by`]}),t.map(e=>(0,A.jsxs)(Mh,{columns:SE,to:`/docs/${encodeURIComponent(e.base)}`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.base}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:e.chunks}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.model}),(0,A.jsx)(`span`,{className:`ui-cell`,children:vg(e.pushed_at)}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.agents.length===0?`nobody`:e.agents.map((e,t)=>(0,A.jsxs)(`span`,{children:[t>0&&`, `,(0,A.jsx)(k,{to:`/a/${encodeURIComponent(e)}/settings`,children:e})]},e))})]},e.base))]})})]})}async function TE(e,t,n){if(n<=0)return null;let r=sy.parse(await oa(e,`/v1/calls/${encodeURIComponent(t)}/events`,{after:n-1,types:ny,limit:1})).entries.find(e=>e.type===ny);return r===void 0?null:gv.parse(r.data)}var EE=20;function DE(e){let t=j(),n=(0,D.useRef)(new Map),[r,i]=(0,D.useState)(n.current),a=e.filter(e=>!mC(e)).slice(0,EE),o=a.map(e=>`${e.call}@${e.last_seq}`).join(` `);return(0,D.useEffect)(()=>{let e=!1,r=a.filter(e=>!n.current.has(e.call));return(async()=>{let a=await Promise.all(r.map(e=>OE(t,e)));if(!(e||a.length===0)){for(let e of a)n.current.set(e.line.call,e);i(new Map(n.current))}})(),()=>{e=!0}},[o,t]),a.map(e=>r.get(e.call)??kE(e))}async function OE(e,t){try{return{line:t,read:!0,score:await TE(e,t.call,t.last_seq),refused:null}}catch(e){return{line:t,read:!0,score:null,refused:String(e)}}}function kE(e){return{line:e,read:!1,score:null,refused:null}}function AE(e){let{lines:t,error:n}=pC(e);return{rows:DE(t),error:n}}function jE({call:e}){let t=j(),n=Sr().agent??``,[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null),d=async r=>{i(r),u(null);try{r===`check`?o(await PT(t,e)):c(await IT(t,n,e))}catch(e){u(e instanceof ta?e.message:String(e))}finally{i(``)}};return(0,A.jsxs)(`div`,{className:`ev-acts`,children:[(0,A.jsxs)(`div`,{className:`ev-acts-buttons`,children:[(0,A.jsx)(W,{size:`md`,disabled:r!==``,onClick:()=>void d(`check`),children:r===`check`?`Checking…`:`Re-check by code`}),(0,A.jsx)(W,{size:`md`,disabled:r!==``,onClick:()=>void d(`promote`),children:r===`promote`?`Writing…`:`Promote to a golden`})]}),a!==null&&(0,A.jsx)(`div`,{className:`ui-tags`,children:a.verdicts.map(e=>(0,A.jsx)(`span`,{title:e.detail,children:(0,A.jsxs)(vh,{tone:e.status===`passed`?`green`:e.status===`failed`?`red`:`muted`,children:[e.check,` `,e.status]})},e.check))}),s!==null&&(0,A.jsxs)(`div`,{className:`ui-note`,children:[`Written to `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:s.path}),` · `,s.candidate.input.length,` caller turn(s)`,s.notes.map(e=>(0,A.jsx)(`div`,{children:e},e))]}),(0,A.jsx)($m,{children:l})]})}var ME=`minmax(0,1.2fr) 120px 104px minmax(0,1.7fr) 70px 84px`;function NE({agent:e,rows:t}){let[n,r]=(0,D.useState)(null);return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:ME,labels:[`Call`,`Started`,`Verdict`,`Judges`,`Calls>`,`Cost>`]}),t.map(t=>(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:t.line.call===n?`ui-table-row ui-table-row-link ev-row-open`:`ui-table-row ui-table-row-link`,style:{gridTemplateColumns:ME},onClick:()=>r(t.line.call===n?null:t.line.call),children:[(0,A.jsx)(`span`,{className:`ui-cell-link ui-clip`,children:t.line.call}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:vg(t.line.started_at)}),(0,A.jsx)(`span`,{children:(0,A.jsx)(PE,{row:t})}),(0,A.jsx)(`span`,{className:`ui-tags`,children:t.score?.judges.map(e=>(0,A.jsx)(`span`,{className:e.verdict===`held`?`ev-judge`:`ev-judge ev-judge-bad`,children:e.name},e.name))}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:t.score?.judge_calls??`—`}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:hg(t.score?.judge_cost_eur)})]}),t.line.call===n&&(0,A.jsx)(FE,{agent:e,row:t})]},t.line.call))]})}function PE({row:e}){return e.read?e.refused===null?e.score?.passed==null?(0,A.jsx)(vh,{tone:`muted`,children:`not judged`}):e.score.passed?(0,A.jsx)(vh,{tone:`green`,children:`passed`}):(0,A.jsx)(vh,{tone:`red`,children:`did not pass`}):(0,A.jsx)(`span`,{title:e.refused,children:(0,A.jsx)(vh,{tone:`red`,children:`unreadable`})}):(0,A.jsx)(vh,{tone:`muted`,children:`reading…`})}function FE({agent:e,row:t}){let n=t.score;return(0,A.jsxs)(`div`,{className:`ev-evidence`,children:[(0,A.jsx)(`div`,{className:`ev-evidence-head`,children:(0,A.jsx)(k,{className:`ui-cell-link`,to:`/a/${e}/sessions/${t.line.call}`,children:`Open the session`})}),(0,A.jsx)(jE,{call:t.line.call}),n===null&&(0,A.jsx)(`div`,{className:`ui-note`,children:`This call's log carries no verdict.`}),n?.not_judged!=null&&(0,A.jsx)(`div`,{className:`ev-warn`,children:n.not_judged}),n!==null&&(0,A.jsx)(IE,{score:n}),n?.judges.filter(e=>e.verdict!==`held`).map(n=>(0,A.jsx)(LE,{agent:e,call:t.line.call,judgment:n},n.name)),n!==null&&n.judges.length>0&&n.judges.every(e=>e.verdict===`held`)&&(0,A.jsxs)(`div`,{className:`ui-note`,children:[`Every judge on the panel held: `,n.judges.map(e=>e.name).join(`, `),`.`]})]})}function IE({score:e}){let t=new Set(e.judges.map(e=>e.name)),n=(e.panel??[]).filter(e=>!t.has(e));return n.length===0?null:(0,A.jsxs)(`div`,{className:`ev-warn`,children:[n.join(`, `),` was run over this call and answered nothing; the panel was `,e.panel?.join(`, `),`.`]})}function LE({agent:e,call:t,judgment:n}){let r=n.evidence.seqs;return(0,A.jsxs)(`div`,{className:`ev-said`,children:[(0,A.jsxs)(nh,{children:[n.name,` · `,n.verdict]}),(0,A.jsxs)(`div`,{className:`ev-said-body`,children:[(0,A.jsx)(`div`,{className:`ev-reason`,children:n.reason}),(0,A.jsx)(`div`,{className:`ui-cell-faint`,children:n.criteria}),n.evidence.said!=null&&(0,A.jsxs)(`div`,{className:`ev-quote`,children:[`“`,n.evidence.said,`”`]}),r.length>0&&(0,A.jsx)(`div`,{className:`ui-tags`,children:r.map(n=>(0,A.jsxs)(k,{className:`ui-tag`,to:`/a/${e}/sessions/${t}#seq-${n}`,children:[`seq `,n]},n))})]})]})}var RE=86400,zE=7,BE=30,VE=`minmax(0,1fr) 150px 150px 90px`;function HE({agent:e}){let t=j(),[n,r]=(0,D.useState)(zE),[i,a]=(0,D.useState)(BE),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(!0),[u,d]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let r=!1;return l(!0),jT(t,e,n*RE,i*RE).then(e=>{r||(s(e),l(!1))},e=>{r||(d(e instanceof ta?e.message:String(e)),l(!1))}),()=>{r=!0}},[t,e,n,i]),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Drift`,meta:c?`reading…`:`held-rate per judge, over two windows`,children:(0,A.jsxs)(`span`,{className:`ev-drift-windows`,children:[(0,A.jsxs)(`label`,{className:`ev-drift-field`,children:[(0,A.jsx)(`span`,{children:`now, days`}),(0,A.jsx)(G,{size:`sm`,type:`number`,min:1,max:365,value:n,onChange:e=>r(Number(e.target.value))})]}),(0,A.jsxs)(`label`,{className:`ev-drift-field`,children:[(0,A.jsx)(`span`,{children:`against the last`}),(0,A.jsx)(G,{size:`sm`,type:`number`,min:1,max:365,value:i,onChange:e=>a(Number(e.target.value))})]})]})}),(0,A.jsx)($m,{children:u}),o!==null&&o.drift.judges.length===0&&(0,A.jsx)(Qm,{children:`No finished call of this agent carries a verdict in either window.`}),o!==null&&o.drift.judges.length>0&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:VE,labels:[`Judge`,`Before>`,`Now>`,`Points>`]}),o.drift.judges.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:VE},children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e.judge}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:UE(e,`before`)}),(0,A.jsx)(`span`,{className:`ev-num`,children:UE(e,`now`)}),(0,A.jsx)(`span`,{className:WE(e,o.threshold)?`ev-num ev-num-bad`:`ev-num ev-num-faint`,children:e.delta===null?`—`:`${e.delta>0?`+`:``}${e.delta.toFixed(0)}`})]},e.judge)),(0,A.jsxs)(`div`,{className:`ui-card-foot`,children:[o.drift.notJudged.now,` call`,o.drift.notJudged.now===1?``:`s`,` in this window carried no verdict at all (`,o.drift.notJudged.before,` before it). A judge may fall `,o.threshold.toFixed(0)," points before `pinecall runs drift` fails the night."]}),o.drift.broke.map(t=>(0,A.jsxs)(`div`,{className:`ev-broke`,children:[(0,A.jsx)(k,{className:`ui-cell-link ui-clip`,to:`/a/${e}/sessions/${t.call}`,children:t.call}),(0,A.jsx)(`span`,{className:`ev-judge ev-judge-bad`,children:t.judge}),(0,A.jsx)(`span`,{className:`ev-reason`,children:t.reason})]},`${t.call}-${t.judge}`))]})]})}function UE(e,t){let n=e[t];return n===null?`—`:`${n.percent.toFixed(0)}% · ${n.held}/${n.settled}`}function WE(e,t){return e.delta!==null&&e.delta<-Math.abs(t)}var GE=` · `;function KE(e,t,n){return[t,e,n].join(GE)}function qE(e){if(e===null)return{held:0,judgments:0};let t=e.runs.flatMap(e=>e.scores);return{held:t.filter(e=>e.passed).length,judgments:t.length}}function JE(e,t){if(t?.matrix==null||e.matrix===null)return null;let n=YE(t.matrix),r=YE(e.matrix),i=[...r.keys()].filter(e=>n.has(e));return{broke:i.filter(e=>n.get(e)===!0&&r.get(e)===!1),recovered:i.filter(e=>n.get(e)===!1&&r.get(e)===!0)}}function YE(e){let t=new Map;for(let n of e.runs)for(let e of n.scores)t.set(KE(n.model,n.golden,e.metric),e.passed);return t}function XE({run:e}){let t=j(),n=Sr().agent??``,[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null);if((0,D.useEffect)(()=>{let r=!1;return c(null),u(null),zT(t,n,e).then(e=>{r||(i(e.goldens),o(e.folder))},()=>{r||i([])}),()=>{r=!0}},[t,n,e]),r===null||r.length===0)return null;let d=async r=>{u(null);try{c(await BT(t,n,e,r))}catch(e){u(e instanceof ta?e.message:String(e))}};return(0,A.jsxs)(`div`,{className:`ev-repro`,children:[(0,A.jsx)(nh,{ruled:!0,children:`Reproductions`}),(0,A.jsxs)(`div`,{className:`ev-repro-body`,children:[(0,A.jsxs)(`div`,{className:`ui-note`,children:[r.length,` in `,(0,A.jsxs)(`span`,{className:`ui-fixed`,children:[a,`/`]}),` — the golden as written, every verdict on it, and the requests the model answered.`]}),(0,A.jsx)(`div`,{className:`ui-chips`,children:r.map(e=>(0,A.jsx)(`button`,{type:`button`,className:s?.golden===e?`ui-chip ui-chip-on`:`ui-chip`,onClick:()=>void d(e),children:e},e))}),(0,A.jsx)($m,{children:l}),s!==null&&(0,A.jsxs)(`div`,{className:`ev-repro-open`,children:[(0,A.jsxs)(`div`,{className:`ev-repro-title`,children:[s.golden,` · `,s.model,` `,(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:s.call})]}),s.verdicts.filter(e=>!e.passed).map(e=>(0,A.jsxs)(`div`,{className:`ev-repro-verdict`,children:[(0,A.jsx)(vh,{tone:`red`,small:!0,children:e.metric}),(0,A.jsx)(`span`,{className:`ev-reason`,children:e.reason})]},e.metric)),(0,A.jsx)(`pre`,{className:`ui-code ev-asked`,children:JSON.stringify(s.asked,null,2)})]})]})]})}var ZE=`minmax(0,1.1fr) 120px 84px 70px 80px minmax(0,1.6fr)`,QE={done:`green`,running:`amber`,failed:`red`};function $E({runs:e,selected:t,onSelect:n}){return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:ZE,labels:[`Run`,`Started`,`Status`,`Held>`,`Judge calls>`,`Since the run before`]}),e.map((r,i)=>{let a=qE(r.matrix),o=r.id===t;return(0,A.jsxs)(`div`,{className:o?`ui-table-row ui-table-row-link ev-row-open`:`ui-table-row ui-table-row-link`,style:{gridTemplateColumns:ZE},onClick:()=>n(r.id),children:[(0,A.jsx)(`span`,{className:`ui-cell-link ui-clip`,children:r.id}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:vg(r.started_at)}),(0,A.jsx)(`span`,{children:(0,A.jsx)(vh,{tone:QE[r.status],children:r.status})}),(0,A.jsx)(`span`,{className:a.judgments>0&&a.held<a.judgments?`ev-num ev-num-bad`:`ev-num`,children:a.judgments===0?`—`:`${a.held}/${a.judgments}`}),(0,A.jsx)(`span`,{className:`ev-num ev-num-faint`,children:r.matrix?.judge_calls??`—`}),(0,A.jsx)(eD,{delta:JE(r,e[i+1])})]},r.id)})]})}function eD({delta:e}){return e===null?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`first of its kind`}):e.broke.length===0&&e.recovered.length===0?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`±0`}):(0,A.jsxs)(`span`,{className:`ui-tags`,children:[e.broke.map(e=>(0,A.jsxs)(vh,{tone:`red`,small:!0,children:[`broke · `,e]},`broke-${e}`)),e.recovered.map(e=>(0,A.jsxs)(vh,{tone:`green`,small:!0,children:[`held again · `,e]},`held-${e}`))]})}var tD=`minmax(0,1.1fr) minmax(0,.8fr) 110px 120px 84px minmax(0,1.6fr)`,nD={done:`green`,running:`amber`,failed:`red`};function rD({run:e,before:t}){return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:e.id,meta:`${e.agent} · ${e.matrix?.judge_calls??0} judge calls`,children:(0,A.jsx)(`span`,{className:`ev-head-end`,children:(0,A.jsx)(vh,{tone:nD[e.status],children:e.status})})}),(0,A.jsxs)(`div`,{className:`ev-facts`,children:[(0,A.jsx)(rh,{label:`Started`,children:vg(e.started_at)}),(0,A.jsx)(rh,{label:`Finished`,children:vg(e.finished_at)}),e.error!==null&&(0,A.jsx)(rh,{label:`Error`,children:e.error}),(0,A.jsx)(rh,{label:`Since before`,children:(0,A.jsx)(eD,{delta:JE(e,t)})})]}),e.matrix===null?(0,A.jsx)(Qm,{children:`No matrix yet — the run is still opening its calls, or it failed before a judge answered.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:tD,labels:[`Golden`,`Model`,`Metric`,`Score`,`Held`,`The judge's own sentence`]}),e.matrix.runs.flatMap(t=>t.scores.map(n=>(0,A.jsx)(iD,{run:e,cell:t,score:n},`${t.golden}/${t.model}/${n.metric}`))),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`A hard policy writes the seqs into its reason on purpose, so the sentence is the way into the log.`})]}),(0,A.jsx)(XE,{run:e.id})]})}function iD({run:e,cell:t,score:n}){let r=e.calls.find(e=>e.golden===t.golden&&e.model===t.model);return(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:tD},children:[(0,A.jsxs)(`span`,{className:`ev-golden`,children:[(0,A.jsx)(`span`,{className:`ev-golden-says ui-clip`,children:t.golden}),r!==void 0&&(0,A.jsx)(k,{className:`ev-golden-call ui-clip`,to:`/a/${e.agent}/sessions/${r.call}`,children:r.call})]}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-clip`,children:t.model}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:n.metric}),(0,A.jsxs)(`span`,{className:`ev-score`,children:[(0,A.jsx)(`span`,{className:`ev-score-value`,children:n.score.toFixed(2)}),(0,A.jsx)(Eh,{share:n.score,color:n.passed?`var(--green-dot)`:`var(--red)`,height:5})]}),(0,A.jsx)(`span`,{children:n.passed?(0,A.jsx)(vh,{tone:`green`,children:`held`}):(0,A.jsx)(vh,{tone:`red`,children:`did not hold`})}),(0,A.jsx)(`span`,{className:`ev-reason`,title:n.criteria,children:n.reason})]})}var aD=z({name:P(),input:R(P()),expect:kp(P(),mp())}),oD=z({agent:P().nullable(),goldens:R(aD)}),sD=z({run:P()});async function cD(e,t){return oD.parse(await wC(e,t,`goldens.roster`))}async function lD(e,t){return sD.parse(await wC(e,t.agent,`goldens.run`,t)).run}var uD=15,dD=0;function fD({agent:e,roster:t,onOpened:n}){let r=j(),[i,a]=(0,D.useState)(()=>new Set(t.goldens.map(e=>e.name))),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(!1),[f,p]=(0,D.useState)(uD),[m,h]=(0,D.useState)(dD),[g,_]=(0,D.useState)(!1),[v,y]=(0,D.useState)(null),b=(e,t)=>{let n=new Set(i);t?n.add(e):n.delete(e),a(n)},x=i.size===t.goldens.length,S=async a=>{a.preventDefault(),_(!0),y(null);try{let a=o.split(`,`).map(e=>e.trim()).filter(e=>e!==``);n(await lD(r,{agent:e,goldens:t.goldens.map(e=>e.name).filter(e=>i.has(e)),...a.length===0?{}:{models:a},voice:c,...c&&u?{background_noise:f,packet_loss:m/100}:{}}))}catch(e){y(e instanceof ta?e.message:String(e))}finally{_(!1)}};return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Run a suite`,meta:`through the class in the directory pinecall start runs in, scored by this gateway`}),(0,A.jsxs)(`form`,{onSubmit:e=>void S(e),children:[(0,A.jsxs)(`div`,{className:`ev-suite-controls`,children:[(0,A.jsxs)(`div`,{className:`ev-suite-models`,children:[(0,A.jsx)(sh,{children:`Models`}),(0,A.jsx)(G,{size:`sm`,value:o,placeholder:`the one the settings name · vendor/model, comma separated`,onChange:e=>s(e.target.value)})]}),(0,A.jsx)(hh,{checked:c,onChange:l,children:`Voice — ring 2, a real line`}),c&&(0,A.jsx)(hh,{checked:u,onChange:d,children:`Noisy line`}),c&&u&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`ev-suite-number`,children:[(0,A.jsx)(sh,{children:`Noise, dB under`}),(0,A.jsx)(G,{size:`sm`,type:`number`,min:0,max:60,value:f,onChange:e=>p(Number(e.target.value))})]}),(0,A.jsxs)(`div`,{className:`ev-suite-number`,children:[(0,A.jsx)(sh,{children:`Packets lost, %`}),(0,A.jsx)(G,{size:`sm`,type:`number`,min:0,max:100,value:m,onChange:e=>h(Number(e.target.value))})]})]}),(0,A.jsx)(W,{kind:`primary`,size:`md`,type:`submit`,className:`ev-suite-go`,disabled:g||i.size===0,children:g?`Opening…`:`Run ${x?`the suite`:`${i.size} golden${i.size===1?``:`s`}`}`})]}),(0,A.jsx)(`div`,{className:`ev-suite-all`,children:(0,A.jsxs)(hh,{checked:x,onChange:e=>a(new Set(e?t.goldens.map(e=>e.name):[])),children:[i.size,` of `,t.goldens.length]})}),t.goldens.map(e=>(0,A.jsxs)(`div`,{className:`ev-suite-golden`,children:[(0,A.jsx)(hh,{checked:i.has(e.name),onChange:t=>b(e.name,t),children:(0,A.jsx)(`span`,{className:`ev-suite-name`,children:e.name})}),(0,A.jsx)(`span`,{className:`ev-suite-says ui-clip`,children:e.input[0]??``}),(0,A.jsx)(`span`,{className:`ev-suite-expects ui-clip`,children:pD(e)})]},e.name))]}),(0,A.jsx)($m,{children:v})]})}function pD(e){let t=Object.entries(e.expect).map(([e,t])=>`${e}: ${mD(t)}`);return t.length===0?`consent only`:t.join(` · `)}function mD(e){return Array.isArray(e)?e.map(String).join(`, `):String(e)}var hD=3e3;function gD(e){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(!0),[o,s]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1,i=async()=>{try{let i=await ET(t,e);n||(r(i),s(null))}catch(e){n||s(String(e))}finally{n||a(!1)}};i();let o=window.setInterval(()=>void i(),hD);return()=>{n=!0,window.clearInterval(o)}},[e,t]),{runs:n,reading:i,error:o}}var _D=`minmax(0,1fr) 110px 90px`;function vD(e){let t=Object.keys(e.expect);return t.includes(`tools`)||t.includes(`not_tools`)?`tool call`:t.includes(`says`)||t.includes(`not`)?`exact phrase`:t.includes(`grounded`)||t.includes(`register`)?`judge`:t.includes(`replies`)?`a reply`:t.length===0?`consent`:t[0]??`—`}function yD(e){let t=new Map;for(let n of e?.matrix?.runs??[]){let e=n.scores.every(e=>e.passed);t.set(n.golden,(t.get(n.golden)??!0)&&e)}return t}function bD(){let e=Sr().agent??``,t=j(),[n,r]=Yi(),i=gD(e),a=AE(e),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(!1),[f,p]=(0,D.useState)(null),m=Am===`local`;(0,D.useEffect)(()=>{let n=!1;return cD(t,e).then(e=>{n||s(e)},e=>{n||l(e instanceof Error?e.message:String(e))}),()=>{n=!0}},[t,e]);let h=n.get(`view`),g=h===`calls`||h===`drift`?h:h===`runs`&&m||m?`runs`:`calls`,_=n.get(`run`),v=i.runs.find(e=>e.id===_)??null,y=i.runs.find(e=>e.matrix!==null),b=yD(y),x=o!==null&&o.agent===e?o.goldens:[],S=x.length>0?x.map(e=>e.name):[...b.keys()],C=[...b.values()].filter(Boolean).length,w=b.size-C,T=e=>{let t=new URLSearchParams(n);for(let[n,r]of Object.entries(e))r===null?t.delete(n):t.set(n,r);r(t)},ee=async()=>{d(!0),p(null);try{let n=await lD(t,{agent:e,goldens:x.map(e=>e.name),voice:!1});T({view:null,run:n})}catch(e){p(e instanceof Error?e.message:String(e))}finally{d(!1)}},te=[...m?[{value:`runs`,label:`Runs`}]:[],{value:`calls`,label:`Scored calls`},{value:`drift`,label:`Drift`}];return(0,A.jsxs)(Dh,{width:1060,tight:!0,children:[(0,A.jsx)(Oh,{title:`Evals`,ledeWidth:620,lede:`Golden sessions replayed against the agent as it is now. A golden is fixed and the agent is the variable: never soften a golden so a change can pass.`}),(0,A.jsxs)(kh,{min:150,children:[(0,A.jsx)(Ah,{size:`small`,label:`Goldens`,value:S.length===0?`—`:S.length}),(0,A.jsx)(Ah,{size:`small`,label:`Passing`,value:y===void 0?`—`:C,tone:y===void 0?void 0:`green`}),(0,A.jsx)(Ah,{size:`small`,label:`Failing`,value:y===void 0?`—`:w,tone:y===void 0||w===0?void 0:`red`}),(0,A.jsxs)(`div`,{className:`ui-stat ui-stat-small`,children:[(0,A.jsx)(`div`,{className:`ui-stat-label`,children:`Last run`}),(0,A.jsx)(`div`,{className:`ev-last`,children:i.runs[0]===void 0?`never`:vg(i.runs[0].started_at)})]})]}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Golden questions`,children:m&&x.length>0&&(0,A.jsx)(W,{kind:`primary`,size:`sm`,className:`ev-run-all`,disabled:u,onClick:()=>void ee(),children:u?`Opening…`:`Run all`})}),S.length===0&&(0,A.jsx)(Qm,{children:o!==null&&o.agent!==e?o.agent===null?"No agent class in the directory the agent's `pinecall start` runs in, so no goldens to read.":`The process holding the agent runs in ${o.agent}'s directory; its goldens are that agent's.`:c!==null&&i.runs.length===0?`The goldens are files beside the class, read by the process holding the agent — and no run has been stored yet to list them from.`:`No goldens for this agent yet: write one in its goldens folder — test/goldens, or test/goldens/<name> in a project of several.`}),(0,A.jsx)(`div`,{className:`ev-goldens`,children:S.map(e=>{let t=x.find(t=>t.name===e),n=b.get(e);return(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:_D},children:[(0,A.jsx)(`span`,{className:`ev-golden-says ui-clip`,title:e,children:t?.input[0]??e}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:t===void 0?`—`:vD(t)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:n===void 0?(0,A.jsx)(vh,{tone:`muted`,children:`not run`}):n?(0,A.jsx)(vh,{tone:`green`,children:`pass`}):(0,A.jsx)(vh,{tone:`red`,children:`fail`})})]},e)})})]}),(0,A.jsx)($m,{children:f}),(0,A.jsx)(`div`,{className:`ev-views`,children:(0,A.jsx)(dh,{options:te,value:g,onChange:e=>T({view:e===(m?`runs`:`calls`)?null:e,run:null})})}),g===`runs`&&(0,A.jsxs)(A.Fragment,{children:[o!==null&&o.agent===e&&x.length>0&&(0,A.jsx)(fD,{agent:e,roster:o,onOpened:e=>T({run:e})}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Runs`,meta:`${i.runs.length} · the same rows pinecall runs list prints`}),(0,A.jsx)($m,{children:i.error}),i.runs.length>0?(0,A.jsx)($E,{runs:i.runs,selected:_,onSelect:e=>T({run:e})}):(0,A.jsx)(Qm,{children:i.reading?`Reading…`:`No run has been stored yet. A run appears here the moment one opens — from this page, a laptop or CI.`})]}),v!==null&&(0,A.jsx)(rD,{run:v,before:i.runs[i.runs.indexOf(v)+1]})]}),g===`drift`&&(0,A.jsx)(HE,{agent:e}),g===`calls`&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Scored calls`,meta:`the verdict is the call.score entry the log seals on`}),(0,A.jsx)($m,{children:a.error}),a.rows.length>0?(0,A.jsx)(NE,{agent:e,rows:a.rows}):(0,A.jsx)(Qm,{children:`No call of this agent has finished yet. The judges seal a call's log with its verdict when the caller hangs up; the first one lands here.`})]})]})}var xD=z({state_fields:kp(P(),V([`public`,`tenant`,`pii`])).default({})});function SD(e){let t=j(),[n,r]=(0,D.useState)({});return(0,D.useEffect)(()=>{let n=!1;if(e!==``)return(async()=>{try{let i=xD.parse(await oa(t,`/v1/agents/${e}/config`));n||r(i.state_fields)}catch{n||r({})}})(),()=>{n=!0}},[e,t]),n}function CD(e){let t=e?.recording;return typeof t==`string`&&t!==``?t:null}function wD({call:e,path:t}){let[n,r]=(0,D.useState)(!1),i=(0,D.useCallback)(()=>r(!0),[]);return t===null||n?null:(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Listen to this call`}),(0,A.jsx)(`div`,{className:`ui-card-body`,children:(0,A.jsx)(TD,{call:e,onNothing:i})})]})}function TD({call:e,onNothing:t}){let n=j(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let r=null,a=!1;return(async()=>{try{let o=await fetch(ua(n,`/v1/calls/${e}/recording`),{headers:ra(n)});if(o.status===404&&t!==void 0){a||t();return}if(!o.ok)throw Error(await ED(o));r=URL.createObjectURL(await o.blob()),a?URL.revokeObjectURL(r):i(r)}catch(e){a||o(e instanceof Error?e.message:String(e))}})(),()=>{a=!0,r!==null&&URL.revokeObjectURL(r)}},[e,n,t]),a===null?r===null?(0,A.jsx)(`p`,{className:`session-sentence`,children:`Reading the recording…`}):(0,A.jsx)(`audio`,{className:`session-player`,controls:!0,preload:`none`,src:r}):(0,A.jsx)(`p`,{className:`session-sentence`,children:a})}async function ED(e){try{let t=(await e.json()).detail;if(typeof t==`string`)return t}catch{}return`the recording answered ${e.status}`}function DD(e,t){return t.forEach(function(t){t&&typeof t!=`string`&&!Array.isArray(t)&&Object.keys(t).forEach(function(n){if(n!=="default"&&!(n in e)){var r=Object.getOwnPropertyDescriptor(t,n);Object.defineProperty(e,n,r.get?r:{enumerable:!0,get:function(){return t[n]}})}})}),Object.freeze(e)}var OD=Object.defineProperty,kD=(e,t,n)=>t in e?OD(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n,AD=(e,t,n)=>kD(e,typeof t==`symbol`?t:t+``,n),jD=class{constructor(){AD(this,`_locking`),AD(this,`_locks`),this._locking=Promise.resolve(),this._locks=0}isLocked(){return this._locks>0}lock(){this._locks+=1;let e,t=new Promise(t=>e=()=>{--this._locks,t()}),n=this._locking.then(()=>e);return this._locking=this._locking.then(()=>t),n}};function MD(e,t){if(!e)throw Error(t)}var ND=34028234663852886e22,PD=-34028234663852886e22,FD=4294967295,ID=2147483647,LD=-2147483648;function RD(e){if(typeof e!=`number`)throw Error(`invalid int 32: `+typeof e);if(!Number.isInteger(e)||e>ID||e<LD)throw Error(`invalid int 32: `+e)}function zD(e){if(typeof e!=`number`)throw Error(`invalid uint 32: `+typeof e);if(!Number.isInteger(e)||e>FD||e<0)throw Error(`invalid uint 32: `+e)}function BD(e){if(typeof e!=`number`)throw Error(`invalid float 32: `+typeof e);if(Number.isFinite(e)&&(e>ND||e<PD))throw Error(`invalid float 32: `+e)}var VD=Symbol(`@bufbuild/protobuf/enum-type`);function HD(e){let t=e[VD];return MD(t,`missing enum type on enum object`),t}function UD(e,t,n,r){e[VD]=WD(t,n.map(t=>({no:t.no,name:t.name,localName:e[t.no]})))}function WD(e,t,n){let r=Object.create(null),i=Object.create(null),a=[];for(let e of t){let t=KD(e);a.push(t),r[e.name]=t,i[e.no]=t}return{typeName:e,values:a,findName(e){return r[e]},findNumber(e){return i[e]}}}function GD(e,t,n){let r={};for(let e of t){let t=KD(e);r[t.localName]=t.no,r[t.no]=t.localName}return UD(r,e,t),r}function KD(e){return`localName`in e?e:Object.assign(Object.assign({},e),{localName:e.name})}var qD=class{equals(e){return this.getType().runtime.util.equals(this.getType(),this,e)}clone(){return this.getType().runtime.util.clone(this)}fromBinary(e,t){let n=this.getType().runtime.bin,r=n.makeReadOptions(t);return n.readMessage(this,r.readerFactory(e),e.byteLength,r),this}fromJson(e,t){let n=this.getType(),r=n.runtime.json,i=r.makeReadOptions(t);return r.readMessage(n,e,i,this),this}fromJsonString(e,t){let n;try{n=JSON.parse(e)}catch(e){throw Error(`cannot decode ${this.getType().typeName} from JSON: ${e instanceof Error?e.message:String(e)}`)}return this.fromJson(n,t)}toBinary(e){let t=this.getType().runtime.bin,n=t.makeWriteOptions(e),r=n.writerFactory();return t.writeMessage(this,r,n),r.finish()}toJson(e){let t=this.getType().runtime.json,n=t.makeWriteOptions(e);return t.writeMessage(this,n)}toJsonString(e){let t=this.toJson(e);return JSON.stringify(t,null,e?.prettySpaces??0)}toJSON(){return this.toJson({emitDefaultValues:!0})}getType(){return Object.getPrototypeOf(this).constructor}};function JD(e,t,n,r){let i=r?.localName??t.substring(t.lastIndexOf(`.`)+1),a={[i]:function(t){e.util.initFields(this),e.util.initPartial(t,this)}}[i];return Object.setPrototypeOf(a.prototype,new qD),Object.assign(a,{runtime:e,typeName:t,fields:e.util.newFieldList(n),fromBinary(e,t){return new a().fromBinary(e,t)},fromJson(e,t){return new a().fromJson(e,t)},fromJsonString(e,t){return new a().fromJsonString(e,t)},equals(t,n){return e.util.equals(a,t,n)}}),a}function YD(){let e=0,t=0;for(let n=0;n<28;n+=7){let r=this.buf[this.pos++];if(e|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}let n=this.buf[this.pos++];if(e|=(n&15)<<28,t=(n&112)>>4,!(n&128))return this.assertBounds(),[e,t];for(let n=3;n<=31;n+=7){let r=this.buf[this.pos++];if(t|=(r&127)<<n,!(r&128))return this.assertBounds(),[e,t]}throw Error(`invalid varint`)}function XD(e,t,n){for(let r=0;r<28;r+=7){let i=e>>>r,a=!(!(i>>>7)&&t==0),o=(a?i|128:i)&255;if(n.push(o),!a)return}let r=e>>>28&15|(t&7)<<4,i=!!(t>>3);if(n.push((i?r|128:r)&255),i){for(let e=3;e<31;e+=7){let r=t>>>e,i=!!(r>>>7),a=(i?r|128:r)&255;if(n.push(a),!i)return}n.push(t>>>31&1)}}var ZD=4294967296;function QD(e){let t=e[0]===`-`;t&&(e=e.slice(1));let n=1e6,r=0,i=0;function a(t,a){let o=Number(e.slice(t,a));i*=n,r=r*n+o,r>=ZD&&(i+=r/ZD|0,r%=ZD)}return a(-24,-18),a(-18,-12),a(-12,-6),a(-6),t?rO(r,i):nO(r,i)}function $D(e,t){let n=nO(e,t),r=n.hi&2147483648;r&&(n=rO(n.lo,n.hi));let i=eO(n.lo,n.hi);return r?`-`+i:i}function eO(e,t){var n=tO(e,t);if(e=n.lo,t=n.hi,t<=2097151)return String(ZD*t+e);let r=e&16777215,i=(e>>>24|t<<8)&16777215,a=t>>16&65535,o=r+i*6777216+a*6710656,s=i+a*8147497,c=a*2,l=1e7;return o>=l&&(s+=Math.floor(o/l),o%=l),s>=l&&(c+=Math.floor(s/l),s%=l),c.toString()+iO(s)+iO(o)}function tO(e,t){return{lo:e>>>0,hi:t>>>0}}function nO(e,t){return{lo:e|0,hi:t|0}}function rO(e,t){return t=~t,e?e=~e+1:t+=1,nO(e,t)}var iO=e=>{let t=String(e);return`0000000`.slice(t.length)+t};function aO(e,t){if(e>=0){for(;e>127;)t.push(e&127|128),e>>>=7;t.push(e)}else{for(let n=0;n<9;n++)t.push(e&127|128),e>>=7;t.push(1)}}function oO(){let e=this.buf[this.pos++],t=e&127;if(!(e&128)||(e=this.buf[this.pos++],t|=(e&127)<<7,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<14,!(e&128))||(e=this.buf[this.pos++],t|=(e&127)<<21,!(e&128)))return this.assertBounds(),t;e=this.buf[this.pos++],t|=(e&15)<<28;for(let t=5;e&128&&t<10;t++)e=this.buf[this.pos++];if(e&128)throw Error(`invalid varint`);return this.assertBounds(),t>>>0}function sO(){let e=new DataView(new ArrayBuffer(8));if(typeof BigInt==`function`&&typeof e.getBigInt64==`function`&&typeof e.getBigUint64==`function`&&typeof e.setBigInt64==`function`&&typeof e.setBigUint64==`function`&&(typeof process!=`object`||{}.BUF_BIGINT_DISABLE!==`1`)){let t=BigInt(`-9223372036854775808`),n=BigInt(`9223372036854775807`),r=BigInt(`0`),i=BigInt(`18446744073709551615`);return{zero:BigInt(0),supported:!0,parse(e){let r=typeof e==`bigint`?e:BigInt(e);if(r>n||r<t)throw Error(`int64 invalid: ${e}`);return r},uParse(e){let t=typeof e==`bigint`?e:BigInt(e);if(t>i||t<r)throw Error(`uint64 invalid: ${e}`);return t},enc(t){return e.setBigInt64(0,this.parse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},uEnc(t){return e.setBigInt64(0,this.uParse(t),!0),{lo:e.getInt32(0,!0),hi:e.getInt32(4,!0)}},dec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigInt64(0,!0)},uDec(t,n){return e.setInt32(0,t,!0),e.setInt32(4,n,!0),e.getBigUint64(0,!0)}}}let t=e=>MD(/^-?[0-9]+$/.test(e),`int64 invalid: ${e}`),n=e=>MD(/^[0-9]+$/.test(e),`uint64 invalid: ${e}`);return{zero:`0`,supported:!1,parse(e){return typeof e!=`string`&&(e=e.toString()),t(e),e},uParse(e){return typeof e!=`string`&&(e=e.toString()),n(e),e},enc(e){return typeof e!=`string`&&(e=e.toString()),t(e),QD(e)},uEnc(e){return typeof e!=`string`&&(e=e.toString()),n(e),QD(e)},dec(e,t){return $D(e,t)},uDec(e,t){return eO(e,t)}}}var cO=sO(),K;(function(e){e[e.DOUBLE=1]=`DOUBLE`,e[e.FLOAT=2]=`FLOAT`,e[e.INT64=3]=`INT64`,e[e.UINT64=4]=`UINT64`,e[e.INT32=5]=`INT32`,e[e.FIXED64=6]=`FIXED64`,e[e.FIXED32=7]=`FIXED32`,e[e.BOOL=8]=`BOOL`,e[e.STRING=9]=`STRING`,e[e.BYTES=12]=`BYTES`,e[e.UINT32=13]=`UINT32`,e[e.SFIXED32=15]=`SFIXED32`,e[e.SFIXED64=16]=`SFIXED64`,e[e.SINT32=17]=`SINT32`,e[e.SINT64=18]=`SINT64`})(K||={});var lO;(function(e){e[e.BIGINT=0]=`BIGINT`,e[e.STRING=1]=`STRING`})(lO||={});function uO(e,t,n){if(t===n)return!0;if(e==K.BYTES){if(!(t instanceof Uint8Array)||!(n instanceof Uint8Array)||t.length!==n.length)return!1;for(let e=0;e<t.length;e++)if(t[e]!==n[e])return!1;return!0}switch(e){case K.UINT64:case K.FIXED64:case K.INT64:case K.SFIXED64:case K.SINT64:return t==n}return!1}function dO(e,t){switch(e){case K.BOOL:return!1;case K.UINT64:case K.FIXED64:case K.INT64:case K.SFIXED64:case K.SINT64:return t==0?cO.zero:`0`;case K.DOUBLE:case K.FLOAT:return 0;case K.BYTES:return new Uint8Array;case K.STRING:return``;default:return 0}}function fO(e,t){switch(e){case K.BOOL:return t===!1;case K.STRING:return t===``;case K.BYTES:return t instanceof Uint8Array&&!t.byteLength;default:return t==0}}function pO(e,t){this.v=e,this.k=t}function mO(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function hO(e){if(Array.isArray(e))return e}function gO(e,t,n){return(t=DO(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function _O(e){if(typeof Symbol<`u`&&e[Symbol.iterator]!=null||e[`@@iterator`]!=null)return Array.from(e)}function vO(e,t){var n=e==null?null:typeof Symbol<`u`&&e[Symbol.iterator]||e[`@@iterator`];if(n!=null){var r,i,a,o,s=[],c=!0,l=!1;try{if(a=(n=n.call(e)).next,t===0){if(Object(n)!==n)return;c=!1}else for(;!(c=(r=a.call(n)).done)&&(s.push(r.value),s.length!==t);c=!0);}catch(e){l=!0,i=e}finally{try{if(!c&&n.return!=null&&(o=n.return(),Object(o)!==o))return}finally{if(l)throw i}}return s}}function yO(){throw TypeError(`Invalid attempt to destructure non-iterable instance.
67
+ In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function bO(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function xO(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?bO(Object(n),!0).forEach(function(t){gO(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):bO(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function SO(e,t){if(e==null)return{};var n,r,i=CO(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(i[n]=e[n])}return i}function CO(e,t){if(e==null)return{};var n={};for(var r in e)if({}.hasOwnProperty.call(e,r)){if(t.indexOf(r)!==-1)continue;n[r]=e[r]}return n}function wO(e,t){return hO(e)||vO(e,t)||OO(e,t)||yO()}function TO(e){return hO(e)||_O(e)||OO(e)||yO()}function EO(e,t){if(typeof e!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(typeof r!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function DO(e){var t=EO(e,`string`);return typeof t==`symbol`?t:t+``}function OO(e,t){if(e){if(typeof e==`string`)return mO(e,t);var n={}.toString.call(e).slice(8,-1);return n===`Object`&&e.constructor&&(n=e.constructor.name),n===`Map`||n===`Set`?Array.from(e):n===`Arguments`||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?mO(e,t):void 0}}function kO(e){return function(){return new AO(e.apply(this,arguments))}}function AO(e){var t,n;function r(t,n){try{var a=e[t](n),o=a.value,s=o instanceof pO;Promise.resolve(s?o.v:o).then(function(n){if(s){var c=t===`return`&&o.k?t:`next`;if(!o.k||n.done)return r(c,n);n=e[c](n).value}i(!!a.done,n)},function(e){r(`throw`,e)})}catch(e){i(2,e)}}function i(e,i){e===2?t.reject(i):t.resolve({value:i,done:e}),(t=t.next)?r(t.key,t.arg):n=null}this._invoke=function(e,i){return new Promise(function(a,o){var s={key:e,arg:i,resolve:a,reject:o,next:null};n?n=n.next=s:(t=n=s,r(e,i))})},typeof e.return!=`function`&&(this.return=void 0)}AO.prototype[typeof Symbol==`function`&&Symbol.asyncIterator||`@@asyncIterator`]=function(){return this},AO.prototype.next=function(e){return this._invoke(`next`,e)},AO.prototype.throw=function(e){return this._invoke(`throw`,e)},AO.prototype.return=function(e){return this._invoke(`return`,e)};var jO;(function(e){e[e.Varint=0]=`Varint`,e[e.Bit64=1]=`Bit64`,e[e.LengthDelimited=2]=`LengthDelimited`,e[e.StartGroup=3]=`StartGroup`,e[e.EndGroup=4]=`EndGroup`,e[e.Bit32=5]=`Bit32`})(jO||={});var MO=class{constructor(e){this.stack=[],this.textEncoder=e??new TextEncoder,this.chunks=[],this.buf=[]}finish(){this.chunks.push(new Uint8Array(this.buf));let e=0;for(let t=0;t<this.chunks.length;t++)e+=this.chunks[t].length;let t=new Uint8Array(e),n=0;for(let e=0;e<this.chunks.length;e++)t.set(this.chunks[e],n),n+=this.chunks[e].length;return this.chunks=[],t}fork(){return this.stack.push({chunks:this.chunks,buf:this.buf}),this.chunks=[],this.buf=[],this}join(){let e=this.finish(),t=this.stack.pop();if(!t)throw Error(`invalid state, fork stack empty`);return this.chunks=t.chunks,this.buf=t.buf,this.uint32(e.byteLength),this.raw(e)}tag(e,t){return this.uint32((e<<3|t)>>>0)}raw(e){return this.buf.length&&(this.chunks.push(new Uint8Array(this.buf)),this.buf=[]),this.chunks.push(e),this}uint32(e){for(zD(e);e>127;)this.buf.push(e&127|128),e>>>=7;return this.buf.push(e),this}int32(e){return RD(e),aO(e,this.buf),this}bool(e){return this.buf.push(+!!e),this}bytes(e){return this.uint32(e.byteLength),this.raw(e)}string(e){let t=this.textEncoder.encode(e);return this.uint32(t.byteLength),this.raw(t)}float(e){BD(e);let t=new Uint8Array(4);return new DataView(t.buffer).setFloat32(0,e,!0),this.raw(t)}double(e){let t=new Uint8Array(8);return new DataView(t.buffer).setFloat64(0,e,!0),this.raw(t)}fixed32(e){zD(e);let t=new Uint8Array(4);return new DataView(t.buffer).setUint32(0,e,!0),this.raw(t)}sfixed32(e){RD(e);let t=new Uint8Array(4);return new DataView(t.buffer).setInt32(0,e,!0),this.raw(t)}sint32(e){return RD(e),e=(e<<1^e>>31)>>>0,aO(e,this.buf),this}sfixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=cO.enc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}fixed64(e){let t=new Uint8Array(8),n=new DataView(t.buffer),r=cO.uEnc(e);return n.setInt32(0,r.lo,!0),n.setInt32(4,r.hi,!0),this.raw(t)}int64(e){let t=cO.enc(e);return XD(t.lo,t.hi,this.buf),this}sint64(e){let t=cO.enc(e),n=t.hi>>31;return XD(t.lo<<1^n,(t.hi<<1|t.lo>>>31)^n,this.buf),this}uint64(e){let t=cO.uEnc(e);return XD(t.lo,t.hi,this.buf),this}},NO=class{constructor(e,t){this.varint64=YD,this.uint32=oO,this.buf=e,this.len=e.length,this.pos=0,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),this.textDecoder=t??new TextDecoder}tag(){let e=this.uint32(),t=e>>>3,n=e&7;if(t<=0||n<0||n>5)throw Error(`illegal tag: field no `+t+` wire type `+n);return[t,n]}skip(e,t){let n=this.pos;switch(e){case jO.Varint:for(;this.buf[this.pos++]&128;);break;case jO.Bit64:this.pos+=4;case jO.Bit32:this.pos+=4;break;case jO.LengthDelimited:let n=this.uint32();this.pos+=n;break;case jO.StartGroup:for(;;){let e=wO(this.tag(),2),n=e[0],r=e[1];if(r===jO.EndGroup){if(t!==void 0&&n!==t)throw Error(`invalid end group tag`);break}this.skip(r,n)}break;default:throw Error(`cant skip wire type `+e)}return this.assertBounds(),this.buf.subarray(n,this.pos)}assertBounds(){if(this.pos>this.len)throw RangeError(`premature EOF`)}int32(){return this.uint32()|0}sint32(){let e=this.uint32();return e>>>1^-(e&1)}int64(){return cO.dec(...this.varint64())}uint64(){return cO.uDec(...this.varint64())}sint64(){let e=wO(this.varint64(),2),t=e[0],n=e[1],r=-(t&1);return t=(t>>>1|(n&1)<<31)^r,n=n>>>1^r,cO.dec(t,n)}bool(){let e=wO(this.varint64(),2),t=e[0],n=e[1];return t!==0||n!==0}fixed32(){return this.view.getUint32((this.pos+=4)-4,!0)}sfixed32(){return this.view.getInt32((this.pos+=4)-4,!0)}fixed64(){return cO.uDec(this.sfixed32(),this.sfixed32())}sfixed64(){return cO.dec(this.sfixed32(),this.sfixed32())}float(){return this.view.getFloat32((this.pos+=4)-4,!0)}double(){return this.view.getFloat64((this.pos+=8)-8,!0)}bytes(){let e=this.uint32(),t=this.pos;return this.pos+=e,this.assertBounds(),this.buf.subarray(t,t+e)}string(){return this.textDecoder.decode(this.bytes())}};function PO(e,t,n,r){let i;return{typeName:t,extendee:n,get field(){if(!i){let n=typeof r==`function`?r():r;n.name=t.split(`.`).pop(),n.jsonName=`[${t}]`,i=e.util.newFieldList([n]).list()[0]}return i},runtime:e}}function FO(e){let t=e.field.localName,n=Object.create(null);return n[t]=IO(e),[n,()=>n[t]]}function IO(e){let t=e.field;if(t.repeated)return[];if(t.default!==void 0)return t.default;switch(t.kind){case`enum`:return t.T.values[0].no;case`scalar`:return dO(t.T,t.L);case`message`:let e=t.T,n=new e;return e.fieldWrapper?e.fieldWrapper.unwrapField(n):n;case`map`:throw`map fields are not allowed to be extensions`}}function LO(e,t){if(!t.repeated&&(t.kind==`enum`||t.kind==`scalar`)){for(let n=e.length-1;n>=0;--n)if(e[n].no==t.no)return[e[n]];return[]}return e.filter(e=>e.no===t.no)}var RO=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/`.split(``),zO=[];for(let e=0;e<RO.length;e++)zO[RO[e].charCodeAt(0)]=e;zO[45]=RO.indexOf(`+`),zO[95]=RO.indexOf(`/`);var BO={dec(e){let t=e.length*3/4;e[e.length-2]==`=`?t-=2:e[e.length-1]==`=`&&--t;let n=new Uint8Array(t),r=0,i=0,a,o=0;for(let t=0;t<e.length;t++){if(a=zO[e.charCodeAt(t)],a===void 0)switch(e[t]){case`=`:i=0;case`
68
+ `:case`\r`:case` `:case` `:continue;default:throw Error(`invalid base64 string.`)}switch(i){case 0:o=a,i=1;break;case 1:n[r++]=o<<2|(a&48)>>4,o=a,i=2;break;case 2:n[r++]=(o&15)<<4|(a&60)>>2,o=a,i=3;break;case 3:n[r++]=(o&3)<<6|a,i=0}}if(i==1)throw Error(`invalid base64 string.`);return n.subarray(0,r)},enc(e){let t=``,n=0,r,i=0;for(let a=0;a<e.length;a++)switch(r=e[a],n){case 0:t+=RO[r>>2],i=(r&3)<<4,n=1;break;case 1:t+=RO[i|r>>4],i=(r&15)<<2,n=2;break;case 2:t+=RO[i|r>>6],t+=RO[r&63],n=0}return n&&(t+=RO[i],t+=`=`,n==1&&(t+=`=`)),t}};function VO(e,t,n){WO(t,e);let r=t.runtime.bin.makeReadOptions(n),i=LO(e.getType().runtime.bin.listUnknownFields(e),t.field),a=wO(FO(t),2),o=a[0],s=a[1];for(let e of i)t.runtime.bin.readField(o,r.readerFactory(e.data),t.field,e.wireType,r);return s()}function HO(e,t,n,r){WO(t,e);let i=t.runtime.bin.makeReadOptions(r),a=t.runtime.bin.makeWriteOptions(r);if(UO(e,t)){let n=e.getType().runtime.bin.listUnknownFields(e).filter(e=>e.no!=t.field.no);e.getType().runtime.bin.discardUnknownFields(e);for(let t of n)e.getType().runtime.bin.onUnknownField(e,t.no,t.wireType,t.data)}let o=a.writerFactory(),s=t.field;!s.opt&&!s.repeated&&(s.kind==`enum`||s.kind==`scalar`)&&(s=Object.assign(Object.assign({},t.field),{opt:!0})),t.runtime.bin.writeField(s,n,o,a);let c=i.readerFactory(o.finish());for(;c.pos<c.len;){let t=wO(c.tag(),2),n=t[0],r=t[1],i=c.skip(r,n);e.getType().runtime.bin.onUnknownField(e,n,r,i)}}function UO(e,t){let n=e.getType();return t.extendee.typeName===n.typeName&&!!n.runtime.bin.listUnknownFields(e).find(e=>e.no==t.field.no)}function WO(e,t){MD(e.extendee.typeName==t.getType().typeName,`extension ${e.typeName} can only be applied to message ${e.extendee.typeName}`)}function GO(e,t){let n=e.localName;if(e.repeated)return t[n].length>0;if(e.oneof)return t[e.oneof.localName].case===n;switch(e.kind){case`enum`:case`scalar`:return e.opt||e.req?t[n]!==void 0:e.kind==`enum`?t[n]!==e.T.values[0].no:!fO(e.T,t[n]);case`message`:return t[n]!==void 0;case`map`:return Object.keys(t[n]).length>0}}function KO(e,t){let n=e.localName,r=!e.opt&&!e.req;if(e.repeated)t[n]=[];else if(e.oneof)t[e.oneof.localName]={case:void 0};else switch(e.kind){case`map`:t[n]={};break;case`enum`:t[n]=r?e.T.values[0].no:void 0;break;case`scalar`:t[n]=r?dO(e.T,e.L):void 0;break;case`message`:t[n]=void 0}}function qO(e,t){if(typeof e!=`object`||!e||!Object.getOwnPropertyNames(qD.prototype).every(t=>t in e&&typeof e[t]==`function`))return!1;let n=e.getType();return n===null||typeof n!=`function`||!(`typeName`in n)||typeof n.typeName!=`string`?!1:t===void 0||n.typeName==t.typeName}function JO(e,t){return qO(t)||!e.fieldWrapper?t:e.fieldWrapper.wrapField(t)}K.DOUBLE,K.FLOAT,K.INT64,K.UINT64,K.INT32,K.UINT32,K.BOOL,K.STRING,K.BYTES;var YO={ignoreUnknownFields:!1},XO={emitDefaultValues:!1,enumAsInteger:!1,useProtoFieldName:!1,prettySpaces:0};function ZO(e){return e?Object.assign(Object.assign({},YO),e):YO}function QO(e){return e?Object.assign(Object.assign({},XO),e):XO}var $O=Symbol(),ek=Symbol();function tk(){return{makeReadOptions:ZO,makeWriteOptions:QO,readMessage(e,t,n,r){if(t==null||Array.isArray(t)||typeof t!=`object`)throw Error(`cannot decode message ${e.typeName} from JSON: ${nk(t)}`);r??=new e;let i=new Map,a=n.typeRegistry;for(let s of Object.entries(t)){var o=wO(s,2);let t=o[0],c=o[1],l=e.fields.findJsonName(t);if(l){if(l.oneof){if(c===null&&l.kind==`scalar`)continue;let n=i.get(l.oneof);if(n!==void 0)throw Error(`cannot decode message ${e.typeName} from JSON: multiple keys for oneof "${l.oneof.name}" present: "${n}", "${t}"`);i.set(l.oneof,t)}rk(r,c,l,n,e)}else{let i=!1;if(a?.findExtension&&t.startsWith(`[`)&&t.endsWith(`]`)){let o=a.findExtension(t.substring(1,t.length-1));if(o&&o.extendee.typeName==e.typeName){i=!0;let e=wO(FO(o),2),t=e[0],a=e[1];rk(t,c,o.field,n,o),HO(r,o,a(),n)}}if(!i&&!n.ignoreUnknownFields)throw Error(`cannot decode message ${e.typeName} from JSON: key "${t}" is unknown`)}}return r},writeMessage(e,t){let n=e.getType(),r={},i;try{for(i of n.fields.byNumber()){if(!GO(i,e)){if(i.req)throw`required field not set`;if(!t.emitDefaultValues||!sk(i))continue}let n=i.oneof?e[i.oneof.localName].value:e[i.localName],a=ck(i,n,t);a!==void 0&&(r[t.useProtoFieldName?i.name:i.jsonName]=a)}let a=t.typeRegistry;if(a?.findExtensionFor)for(let i of n.runtime.bin.listUnknownFields(e)){let o=a.findExtensionFor(n.typeName,i.no);if(o&&UO(e,o)){let n=VO(e,o,t),i=ck(o.field,n,t);i!==void 0&&(r[o.field.jsonName]=i)}}}catch(e){let t=i?`cannot encode field ${n.typeName}.${i.name} to JSON`:`cannot encode message ${n.typeName} to JSON`,r=e instanceof Error?e.message:String(e);throw Error(t+(r.length>0?`: ${r}`:``))}return r},readScalar(e,t,n){return ak(e,t,n??lO.BIGINT,!0)},writeScalar(e,t,n){if(t!==void 0&&(n||fO(e,t)))return uk(e,t)},debug:nk}}function nk(e){if(e===null)return`null`;switch(typeof e){case`object`:return Array.isArray(e)?`array`:`object`;case`string`:return e.length>100?`string`:`"${e.split(`"`).join(`\\"`)}"`;default:return String(e)}}function rk(e,t,n,r,i){let a=n.localName;if(n.repeated){if(MD(n.kind!=`map`),t===null)return;if(!Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${nk(t)}`);let o=e[a];for(let e of t){if(e===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${nk(e)}`);switch(n.kind){case`message`:o.push(n.T.fromJson(e,r));break;case`enum`:let t=ok(n.T,e,r.ignoreUnknownFields,!0);t!==ek&&o.push(t);break;case`scalar`:try{o.push(ak(n.T,e,n.L,!0))}catch(t){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${nk(e)}`;throw t instanceof Error&&t.message.length>0&&(r+=`: ${t.message}`),Error(r)}}}}else if(n.kind==`map`){if(t===null)return;if(typeof t!=`object`||Array.isArray(t))throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: ${nk(t)}`);let s=e[a];for(let e of Object.entries(t)){var o=wO(e,2);let a=o[0],c=o[1];if(c===null)throw Error(`cannot decode field ${i.typeName}.${n.name} from JSON: map value null`);let l;try{l=ik(n.K,a)}catch(e){let r=`cannot decode map key for field ${i.typeName}.${n.name} from JSON: ${nk(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}switch(n.V.kind){case`message`:s[l]=n.V.T.fromJson(c,r);break;case`enum`:let e=ok(n.V.T,c,r.ignoreUnknownFields,!0);e!==ek&&(s[l]=e);break;case`scalar`:try{s[l]=ak(n.V.T,c,lO.BIGINT,!0)}catch(e){let r=`cannot decode map value for field ${i.typeName}.${n.name} from JSON: ${nk(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}}}}else switch(n.oneof&&(e=e[n.oneof.localName]={case:a},a=`value`),n.kind){case`message`:let o=n.T;if(t===null&&o.typeName!=`google.protobuf.Value`)return;let s=e[a];qO(s)?s.fromJson(t,r):(e[a]=s=o.fromJson(t,r),o.fieldWrapper&&!n.oneof&&(e[a]=o.fieldWrapper.unwrapField(s)));break;case`enum`:let c=ok(n.T,t,r.ignoreUnknownFields,!1);switch(c){case $O:KO(n,e);break;case ek:break;default:e[a]=c}break;case`scalar`:try{let r=ak(n.T,t,n.L,!1);switch(r){case $O:KO(n,e);break;default:e[a]=r}}catch(e){let r=`cannot decode field ${i.typeName}.${n.name} from JSON: ${nk(t)}`;throw e instanceof Error&&e.message.length>0&&(r+=`: ${e.message}`),Error(r)}}}function ik(e,t){if(e===K.BOOL)switch(t){case`true`:t=!0;break;case`false`:t=!1}return ak(e,t,lO.BIGINT,!0).toString()}function ak(e,t,n,r){if(t===null)return r?dO(e,n):$O;switch(e){case K.DOUBLE:case K.FLOAT:if(t===`NaN`)return NaN;if(t===`Infinity`)return 1/0;if(t===`-Infinity`)return-1/0;if(t===``||typeof t==`string`&&t.trim().length!==t.length||typeof t!=`string`&&typeof t!=`number`)break;let r=Number(t);if(Number.isNaN(r)||!Number.isFinite(r))break;return e==K.FLOAT&&BD(r),r;case K.INT32:case K.FIXED32:case K.SFIXED32:case K.SINT32:case K.UINT32:let i;if(typeof t==`number`?i=t:typeof t==`string`&&t.length>0&&t.trim().length===t.length&&(i=Number(t)),i===void 0)break;return e==K.UINT32||e==K.FIXED32?zD(i):RD(i),i;case K.INT64:case K.SFIXED64:case K.SINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let a=cO.parse(t);return n?a.toString():a;case K.FIXED64:case K.UINT64:if(typeof t!=`number`&&typeof t!=`string`)break;let o=cO.uParse(t);return n?o.toString():o;case K.BOOL:if(typeof t!=`boolean`)break;return t;case K.STRING:if(typeof t!=`string`)break;return t;case K.BYTES:if(t===``)return new Uint8Array;if(typeof t!=`string`)break;return BO.dec(t)}throw Error()}function ok(e,t,n,r){if(t===null)return e.typeName==`google.protobuf.NullValue`?0:r?e.values[0].no:$O;switch(typeof t){case`number`:if(Number.isInteger(t))return t;break;case`string`:let r=e.findName(t);if(r!==void 0)return r.no;if(n)return ek}throw Error(`cannot decode enum ${e.typeName} from JSON: ${nk(t)}`)}function sk(e){return e.repeated||e.kind==`map`?!0:!(e.oneof||e.kind==`message`||e.opt||e.req)}function ck(e,t,n){if(e.kind==`map`){MD(typeof t==`object`&&!!t);let o={},s=Object.entries(t);switch(e.V.kind){case`scalar`:for(let t of s){var r=wO(t,2);let n=r[0],i=r[1];o[n.toString()]=uk(e.V.T,i)}break;case`message`:for(let e of s){var i=wO(e,2);let t=i[0],r=i[1];o[t.toString()]=r.toJson(n)}break;case`enum`:let t=e.V.T;for(let e of s){var a=wO(e,2);let r=a[0],i=a[1];o[r.toString()]=lk(t,i,n.enumAsInteger)}}return n.emitDefaultValues||s.length>0?o:void 0}if(e.repeated){MD(Array.isArray(t));let r=[];switch(e.kind){case`scalar`:for(let n=0;n<t.length;n++)r.push(uk(e.T,t[n]));break;case`enum`:for(let i=0;i<t.length;i++)r.push(lk(e.T,t[i],n.enumAsInteger));break;case`message`:for(let e=0;e<t.length;e++)r.push(t[e].toJson(n))}return n.emitDefaultValues||r.length>0?r:void 0}switch(e.kind){case`scalar`:return uk(e.T,t);case`enum`:return lk(e.T,t,n.enumAsInteger);case`message`:return JO(e.T,t).toJson(n)}}function lk(e,t,n){return MD(typeof t==`number`),e.typeName==`google.protobuf.NullValue`?null:n?t:e.findNumber(t)?.name??t}function uk(e,t){switch(e){case K.INT32:case K.SFIXED32:case K.SINT32:case K.FIXED32:case K.UINT32:return MD(typeof t==`number`),t;case K.FLOAT:case K.DOUBLE:return MD(typeof t==`number`),Number.isNaN(t)?`NaN`:t===1/0?`Infinity`:t===-1/0?`-Infinity`:t;case K.STRING:return MD(typeof t==`string`),t;case K.BOOL:return MD(typeof t==`boolean`),t;case K.UINT64:case K.FIXED64:case K.INT64:case K.SFIXED64:case K.SINT64:return MD(typeof t==`bigint`||typeof t==`string`||typeof t==`number`),t.toString();case K.BYTES:return MD(t instanceof Uint8Array),BO.enc(t)}}var dk=Symbol(`@bufbuild/protobuf/unknown-fields`),fk={readUnknownFields:!0,readerFactory:e=>new NO(e)},pk={writeUnknownFields:!0,writerFactory:()=>new MO};function mk(e){return e?Object.assign(Object.assign({},fk),e):fk}function hk(e){return e?Object.assign(Object.assign({},pk),e):pk}function gk(){return{makeReadOptions:mk,makeWriteOptions:hk,listUnknownFields(e){return e[dk]??[]},discardUnknownFields(e){delete e[dk]},writeUnknownFields(e,t){let n=e[dk];if(n)for(let e of n)t.tag(e.no,e.wireType).raw(e.data)},onUnknownField(e,t,n,r){let i=e;Array.isArray(i[dk])||(i[dk]=[]),i[dk].push({no:t,wireType:n,data:r})},readMessage(e,t,n,r,i){let a=e.getType(),o=i?t.len:t.pos+n,s,c;for(;t.pos<o;){var l=wO(t.tag(),2);if(s=l[0],c=l[1],i===!0&&c==jO.EndGroup)break;let n=a.fields.find(s);if(!n){let n=t.skip(c,s);r.readUnknownFields&&this.onUnknownField(e,s,c,n);continue}_k(e,t,n,c,r)}if(i&&(c!=jO.EndGroup||s!==n))throw Error(`invalid end group tag`)},readField:_k,writeMessage(e,t,n){let r=e.getType();for(let i of r.fields.byNumber()){if(!GO(i,e)){if(i.req)throw Error(`cannot encode field ${r.typeName}.${i.name} to binary: required field not set`);continue}Sk(i,i.oneof?e[i.oneof.localName].value:e[i.localName],t,n)}return n.writeUnknownFields&&this.writeUnknownFields(e,t),t},writeField(e,t,n,r){t!==void 0&&Sk(e,t,n,r)}}}function _k(e,t,n,r,i){let a=n.repeated,o=n.localName;switch(n.oneof&&(e=e[n.oneof.localName],e.case!=o&&delete e.value,e.case=o,o=`value`),n.kind){case`scalar`:case`enum`:let s=n.kind==`enum`?K.INT32:n.T,c=xk;if(n.kind==`scalar`&&n.L>0&&(c=bk),a){let n=e[o];if(r==jO.LengthDelimited&&s!=K.STRING&&s!=K.BYTES){let e=t.uint32()+t.pos;for(;t.pos<e;)n.push(c(t,s))}else n.push(c(t,s))}else e[o]=c(t,s);break;case`message`:let l=n.T;a?e[o].push(vk(t,new l,i,n)):qO(e[o])?vk(t,e[o],i,n):(e[o]=vk(t,new l,i,n),l.fieldWrapper&&!n.oneof&&!n.repeated&&(e[o]=l.fieldWrapper.unwrapField(e[o])));break;case`map`:let u=wO(yk(n,t,i),2),d=u[0],f=u[1];e[o][d]=f}}function vk(e,t,n,r){let i=t.getType().runtime.bin,a=r?.delimited;return i.readMessage(t,e,a?r.no:e.uint32(),n,a),t}function yk(e,t,n){let r=t.uint32(),i=t.pos+r,a,o;for(;t.pos<i;)switch(wO(t.tag(),1)[0]){case 1:a=xk(t,e.K);break;case 2:switch(e.V.kind){case`scalar`:o=xk(t,e.V.T);break;case`enum`:o=t.int32();break;case`message`:o=vk(t,new e.V.T,n,void 0)}}if(a===void 0&&(a=dO(e.K,lO.BIGINT)),typeof a!=`string`&&typeof a!=`number`&&(a=a.toString()),o===void 0)switch(e.V.kind){case`scalar`:o=dO(e.V.T,lO.BIGINT);break;case`enum`:o=e.V.T.values[0].no;break;case`message`:o=new e.V.T}return[a,o]}function bk(e,t){let n=xk(e,t);return typeof n==`bigint`?n.toString():n}function xk(e,t){switch(t){case K.STRING:return e.string();case K.BOOL:return e.bool();case K.DOUBLE:return e.double();case K.FLOAT:return e.float();case K.INT32:return e.int32();case K.INT64:return e.int64();case K.UINT64:return e.uint64();case K.FIXED64:return e.fixed64();case K.BYTES:return e.bytes();case K.FIXED32:return e.fixed32();case K.SFIXED32:return e.sfixed32();case K.SFIXED64:return e.sfixed64();case K.SINT64:return e.sint64();case K.UINT32:return e.uint32();case K.SINT32:return e.sint32()}}function Sk(e,t,n,r){MD(t!==void 0);let i=e.repeated;switch(e.kind){case`scalar`:case`enum`:let o=e.kind==`enum`?K.INT32:e.T;if(i){if(MD(Array.isArray(t)),e.packed)Ek(n,o,e.no,t);else for(let r of t)Tk(n,o,e.no,r)}else Tk(n,o,e.no,t);break;case`message`:if(i){MD(Array.isArray(t));for(let i of t)wk(n,r,e,i)}else wk(n,r,e,t);break;case`map`:MD(typeof t==`object`&&!!t);for(let i of Object.entries(t)){var a=wO(i,2);let t=a[0],o=a[1];Ck(n,r,e,t,o)}}}function Ck(e,t,n,r,i){e.tag(n.no,jO.LengthDelimited),e.fork();let a=r;switch(n.K){case K.INT32:case K.FIXED32:case K.UINT32:case K.SFIXED32:case K.SINT32:a=Number.parseInt(r);break;case K.BOOL:MD(r==`true`||r==`false`),a=r==`true`}switch(Tk(e,n.K,1,a),n.V.kind){case`scalar`:Tk(e,n.V.T,2,i);break;case`enum`:Tk(e,K.INT32,2,i);break;case`message`:MD(i!==void 0),e.tag(2,jO.LengthDelimited).bytes(i.toBinary(t))}e.join()}function wk(e,t,n,r){let i=JO(n.T,r);n.delimited?e.tag(n.no,jO.StartGroup).raw(i.toBinary(t)).tag(n.no,jO.EndGroup):e.tag(n.no,jO.LengthDelimited).bytes(i.toBinary(t))}function Tk(e,t,n,r){MD(r!==void 0);let i=wO(Dk(t),2),a=i[0],o=i[1];e.tag(n,a)[o](r)}function Ek(e,t,n,r){if(!r.length)return;e.tag(n,jO.LengthDelimited).fork();let i=wO(Dk(t),2)[1];for(let t=0;t<r.length;t++)e[i](r[t]);e.join()}function Dk(e){let t=jO.Varint;switch(e){case K.BYTES:case K.STRING:t=jO.LengthDelimited;break;case K.DOUBLE:case K.FIXED64:case K.SFIXED64:t=jO.Bit64;break;case K.FIXED32:case K.SFIXED32:case K.FLOAT:t=jO.Bit32}let n=K[e].toLowerCase();return[t,n]}function Ok(){return{setEnumType:UD,initPartial(e,t){if(e===void 0)return;let n=t.getType();for(let i of n.fields.byMember()){let n=i.localName,a=t,o=e;if(o[n]!=null)switch(i.kind){case`oneof`:let e=o[n].case;if(e===void 0)continue;let t=i.findField(e),s=o[n].value;t&&t.kind==`message`&&!qO(s,t.T)?s=new t.T(s):t&&t.kind===`scalar`&&t.T===K.BYTES&&(s=Ak(s)),a[n]={case:e,value:s};break;case`scalar`:case`enum`:let c=o[n];i.T===K.BYTES&&(c=i.repeated?c.map(Ak):Ak(c)),a[n]=c;break;case`map`:switch(i.V.kind){case`scalar`:case`enum`:if(i.V.T===K.BYTES)for(let e of Object.entries(o[n])){var r=wO(e,2);let t=r[0],i=r[1];a[n][t]=Ak(i)}else Object.assign(a[n],o[n]);break;case`message`:let e=i.V.T;for(let t of Object.keys(o[n])){let r=o[n][t];e.fieldWrapper||(r=new e(r)),a[n][t]=r}}break;case`message`:let l=i.T;if(i.repeated)a[n]=o[n].map(e=>qO(e,l)?e:new l(e));else{let e=o[n];a[n]=l.fieldWrapper?l.typeName===`google.protobuf.BytesValue`?Ak(e):e:qO(e,l)?e:new l(e)}}}},equals(e,t,n){return t===n?!0:!t||!n?!1:e.fields.byMember().every(e=>{let r=t[e.localName],i=n[e.localName];if(e.repeated){if(r.length!==i.length)return!1;switch(e.kind){case`message`:return r.every((t,n)=>e.T.equals(t,i[n]));case`scalar`:return r.every((t,n)=>uO(e.T,t,i[n]));case`enum`:return r.every((e,t)=>uO(K.INT32,e,i[t]))}throw Error(`repeated cannot contain ${e.kind}`)}switch(e.kind){case`message`:let t=r,n=i;return e.T.fieldWrapper&&(t!==void 0&&!qO(t)&&(t=e.T.fieldWrapper.wrapField(t)),n!==void 0&&!qO(n)&&(n=e.T.fieldWrapper.wrapField(n))),e.T.equals(t,n);case`enum`:return uO(K.INT32,r,i);case`scalar`:return uO(e.T,r,i);case`oneof`:if(r.case!==i.case)return!1;let a=e.findField(r.case);if(a===void 0)return!0;switch(a.kind){case`message`:return a.T.equals(r.value,i.value);case`enum`:return uO(K.INT32,r.value,i.value);case`scalar`:return uO(a.T,r.value,i.value)}throw Error(`oneof cannot contain ${a.kind}`);case`map`:let o=Object.keys(r).concat(Object.keys(i));switch(e.V.kind){case`message`:let t=e.V.T;return o.every(e=>t.equals(r[e],i[e]));case`enum`:return o.every(e=>uO(K.INT32,r[e],i[e]));case`scalar`:let n=e.V.T;return o.every(e=>uO(n,r[e],i[e]))}}})},clone(e){let t=e.getType(),n=new t,r=n;for(let n of t.fields.byMember()){let t=e[n.localName],a;if(n.repeated)a=t.map(kk);else if(n.kind==`map`){a=r[n.localName];for(let e of Object.entries(t)){var i=wO(e,2);let t=i[0],n=i[1];a[t]=kk(n)}}else a=n.kind==`oneof`?n.findField(t.case)?{case:t.case,value:kk(t.value)}:{case:void 0}:kk(t);r[n.localName]=a}for(let n of t.runtime.bin.listUnknownFields(e))t.runtime.bin.onUnknownField(r,n.no,n.wireType,n.data);return n}}}function kk(e){if(e===void 0)return e;if(qO(e))return e.clone();if(e instanceof Uint8Array){let t=new Uint8Array(e.byteLength);return t.set(e),t}return e}function Ak(e){return e instanceof Uint8Array?e:new Uint8Array(e)}function jk(e,t,n){return{syntax:e,json:tk(),bin:gk(),util:Object.assign(Object.assign({},Ok()),{newFieldList:t,initFields:n}),makeMessageType(e,t,n){return JD(this,e,t,n)},makeEnum:GD,makeEnumType:WD,getEnumType:HD,makeExtension(e,t,n){return PO(this,e,t,n)}}}var Mk=class{constructor(e,t){this._fields=e,this._normalizer=t}findJsonName(e){if(!this.jsonNames){let e={};for(let t of this.list())e[t.jsonName]=e[t.name]=t;this.jsonNames=e}return this.jsonNames[e]}find(e){if(!this.numbers){let e={};for(let t of this.list())e[t.no]=t;this.numbers=e}return this.numbers[e]}list(){return this.all||=this._normalizer(this._fields),this.all}byNumber(){return this.numbersAsc||=this.list().concat().sort((e,t)=>e.no-t.no),this.numbersAsc}byMember(){if(!this.members){this.members=[];let e=this.members,t;for(let n of this.list())n.oneof?n.oneof!==t&&(t=n.oneof,e.push(t)):e.push(n)}return this.members}};function Nk(e,t){let n=Ik(e);return t?n:Vk(Bk(n))}function Pk(e){return Nk(e,!1)}var Fk=Ik;function Ik(e){let t=!1,n=[];for(let r=0;r<e.length;r++){let i=e.charAt(r);switch(i){case`_`:t=!0;break;case`0`:case`1`:case`2`:case`3`:case`4`:case`5`:case`6`:case`7`:case`8`:case`9`:n.push(i),t=!1;break;default:t&&(t=!1,i=i.toUpperCase()),n.push(i)}}return n.join(``)}var Lk=new Set([`constructor`,`toString`,`toJSON`,`valueOf`]),Rk=new Set([`getType`,`clone`,`equals`,`fromBinary`,`fromJson`,`fromJsonString`,`toBinary`,`toJson`,`toJsonString`,`toObject`]),zk=e=>`${e}\$`,Bk=e=>Rk.has(e)?zk(e):e,Vk=e=>Lk.has(e)?zk(e):e,Hk=class{constructor(e){this.kind=`oneof`,this.repeated=!1,this.packed=!1,this.opt=!1,this.req=!1,this.default=void 0,this.fields=[],this.name=e,this.localName=Pk(e)}addField(e){MD(e.oneof===this,`field ${e.name} not one of ${this.name}`),this.fields.push(e)}findField(e){if(!this._lookup){this._lookup=Object.create(null);for(let e=0;e<this.fields.length;e++)this._lookup[this.fields[e].localName]=this.fields[e]}return this._lookup[e]}};function Uk(e,t){let n=[],r;for(let t of typeof e==`function`?e():e){let e=t;if(e.localName=Nk(t.name,t.oneof!==void 0),e.jsonName=t.jsonName??Fk(t.name),e.repeated=t.repeated??!1,t.kind==`scalar`&&(e.L=t.L??lO.BIGINT),e.delimited=t.delimited??!1,e.req=t.req??!1,e.opt=t.opt??!1,t.packed===void 0&&(e.packed=t.kind==`enum`||t.kind==`scalar`&&t.T!=K.BYTES&&t.T!=K.STRING),t.oneof!==void 0){let n=typeof t.oneof==`string`?t.oneof:t.oneof.name;(!r||r.name!=n)&&(r=new Hk(n)),e.oneof=r,r.addField(e)}n.push(e)}return n}var q=jk(`proto3`,e=>new Mk(e,e=>Uk(e)),e=>{for(let t of e.getType().fields.byMember()){if(t.opt)continue;let n=t.localName,r=e;if(t.repeated){r[n]=[];continue}switch(t.kind){case`oneof`:r[n]={case:void 0};break;case`enum`:r[n]=0;break;case`map`:r[n]={};break;case`scalar`:r[n]=dO(t.T,t.L)}}}),Wk=class e extends qD{constructor(e){super(),this.seconds=cO.zero,this.nanos=0,q.util.initPartial(e,this)}fromJson(e,t){if(typeof e!=`string`)throw Error(`cannot decode google.protobuf.Timestamp from JSON: ${q.json.debug(e)}`);let n=e.match(/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})(?:Z|\.([0-9]{3,9})Z|([+-][0-9][0-9]:[0-9][0-9]))$/);if(!n)throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);let r=Date.parse(n[1]+`-`+n[2]+`-`+n[3]+`T`+n[4]+`:`+n[5]+`:`+n[6]+(n[8]?n[8]:`Z`));if(Number.isNaN(r))throw Error(`cannot decode google.protobuf.Timestamp from JSON: invalid RFC 3339 string`);if(r<Date.parse(`0001-01-01T00:00:00Z`)||r>Date.parse(`9999-12-31T23:59:59Z`))throw Error(`cannot decode message google.protobuf.Timestamp from JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);return this.seconds=cO.parse(r/1e3),this.nanos=0,n[7]&&(this.nanos=parseInt(`1`+n[7]+`0`.repeat(9-n[7].length))-1e9),this}toJson(e){let t=Number(this.seconds)*1e3;if(t<Date.parse(`0001-01-01T00:00:00Z`)||t>Date.parse(`9999-12-31T23:59:59Z`))throw Error(`cannot encode google.protobuf.Timestamp to JSON: must be from 0001-01-01T00:00:00Z to 9999-12-31T23:59:59Z inclusive`);if(this.nanos<0)throw Error(`cannot encode google.protobuf.Timestamp to JSON: nanos must not be negative`);let n=`Z`;if(this.nanos>0){let e=(this.nanos+1e9).toString().substring(1);n=e.substring(3)===`000000`?`.`+e.substring(0,3)+`Z`:e.substring(6)===`000`?`.`+e.substring(0,6)+`Z`:`.`+e+`Z`}return new Date(t).toISOString().replace(`.000Z`,n)}toDate(){return new Date(Number(this.seconds)*1e3+Math.ceil(this.nanos/1e6))}static now(){return e.fromDate(new Date)}static fromDate(t){let n=t.getTime();return new e({seconds:cO.parse(Math.floor(n/1e3)),nanos:n%1e3*1e6})}static fromBinary(t,n){return new e().fromBinary(t,n)}static fromJson(t,n){return new e().fromJson(t,n)}static fromJsonString(t,n){return new e().fromJsonString(t,n)}static equals(t,n){return q.util.equals(e,t,n)}};Wk.runtime=q,Wk.typeName=`google.protobuf.Timestamp`,Wk.fields=q.util.newFieldList(()=>[{no:1,name:`seconds`,kind:`scalar`,T:3},{no:2,name:`nanos`,kind:`scalar`,T:5}]);var Gk=q.makeMessageType(`livekit.MetricsBatch`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:Wk},{no:3,name:`str_data`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`time_series`,kind:`message`,T:Kk,repeated:!0},{no:5,name:`events`,kind:`message`,T:Jk,repeated:!0}]),Kk=q.makeMessageType(`livekit.TimeSeriesMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`samples`,kind:`message`,T:qk,repeated:!0},{no:5,name:`rid`,kind:`scalar`,T:13}]),qk=q.makeMessageType(`livekit.MetricSample`,()=>[{no:1,name:`timestamp_ms`,kind:`scalar`,T:3},{no:2,name:`normalized_timestamp`,kind:`message`,T:Wk},{no:3,name:`value`,kind:`scalar`,T:2}]),Jk=q.makeMessageType(`livekit.EventMetric`,()=>[{no:1,name:`label`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:13},{no:3,name:`track_sid`,kind:`scalar`,T:13},{no:4,name:`start_timestamp_ms`,kind:`scalar`,T:3},{no:5,name:`end_timestamp_ms`,kind:`scalar`,T:3,opt:!0},{no:6,name:`normalized_start_timestamp`,kind:`message`,T:Wk},{no:7,name:`normalized_end_timestamp`,kind:`message`,T:Wk,opt:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`rid`,kind:`scalar`,T:13}]),Yk=q.makeEnum(`livekit.BackupCodecPolicy`,[{no:0,name:`PREFER_REGRESSION`},{no:1,name:`SIMULCAST`},{no:2,name:`REGRESSION`}]),Xk=q.makeEnum(`livekit.TrackType`,[{no:0,name:`AUDIO`},{no:1,name:`VIDEO`},{no:2,name:`DATA`}]),Zk=q.makeEnum(`livekit.TrackSource`,[{no:0,name:`UNKNOWN`},{no:1,name:`CAMERA`},{no:2,name:`MICROPHONE`},{no:3,name:`SCREEN_SHARE`},{no:4,name:`SCREEN_SHARE_AUDIO`}]),Qk=q.makeEnum(`livekit.VideoQuality`,[{no:0,name:`LOW`},{no:1,name:`MEDIUM`},{no:2,name:`HIGH`},{no:3,name:`OFF`}]),$k=q.makeEnum(`livekit.ConnectionQuality`,[{no:0,name:`POOR`},{no:1,name:`GOOD`},{no:2,name:`EXCELLENT`},{no:3,name:`LOST`}]),eA=q.makeEnum(`livekit.ClientConfigSetting`,[{no:0,name:`UNSET`},{no:1,name:`DISABLED`},{no:2,name:`ENABLED`}]),tA=q.makeEnum(`livekit.DisconnectReason`,[{no:0,name:`UNKNOWN_REASON`},{no:1,name:`CLIENT_INITIATED`},{no:2,name:`DUPLICATE_IDENTITY`},{no:3,name:`SERVER_SHUTDOWN`},{no:4,name:`PARTICIPANT_REMOVED`},{no:5,name:`ROOM_DELETED`},{no:6,name:`STATE_MISMATCH`},{no:7,name:`JOIN_FAILURE`},{no:8,name:`MIGRATION`},{no:9,name:`SIGNAL_CLOSE`},{no:10,name:`ROOM_CLOSED`},{no:11,name:`USER_UNAVAILABLE`},{no:12,name:`USER_REJECTED`},{no:13,name:`SIP_TRUNK_FAILURE`},{no:14,name:`CONNECTION_TIMEOUT`},{no:15,name:`MEDIA_FAILURE`},{no:16,name:`AGENT_ERROR`}]),nA=q.makeEnum(`livekit.ReconnectReason`,[{no:0,name:`RR_UNKNOWN`},{no:1,name:`RR_SIGNAL_DISCONNECTED`},{no:2,name:`RR_PUBLISHER_FAILED`},{no:3,name:`RR_SUBSCRIBER_FAILED`},{no:4,name:`RR_SWITCH_CANDIDATE`}]),rA=q.makeEnum(`livekit.SubscriptionError`,[{no:0,name:`SE_UNKNOWN`},{no:1,name:`SE_CODEC_UNSUPPORTED`},{no:2,name:`SE_TRACK_NOTFOUND`}]),iA=q.makeEnum(`livekit.AudioTrackFeature`,[{no:0,name:`TF_STEREO`},{no:1,name:`TF_NO_DTX`},{no:2,name:`TF_AUTO_GAIN_CONTROL`},{no:3,name:`TF_ECHO_CANCELLATION`},{no:4,name:`TF_NOISE_SUPPRESSION`},{no:5,name:`TF_ENHANCED_NOISE_CANCELLATION`},{no:6,name:`TF_PRECONNECT_BUFFER`}]),aA=q.makeEnum(`livekit.PacketTrailerFeature`,[{no:0,name:`PTF_USER_TIMESTAMP`},{no:1,name:`PTF_FRAME_ID`},{no:2,name:`PTF_USER_DATA`}]),oA=q.makeMessageType(`livekit.Room`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`empty_timeout`,kind:`scalar`,T:13},{no:14,name:`departure_timeout`,kind:`scalar`,T:13},{no:4,name:`max_participants`,kind:`scalar`,T:13},{no:5,name:`creation_time`,kind:`scalar`,T:3},{no:15,name:`creation_time_ms`,kind:`scalar`,T:3},{no:6,name:`turn_password`,kind:`scalar`,T:9},{no:7,name:`enabled_codecs`,kind:`message`,T:sA,repeated:!0},{no:8,name:`metadata`,kind:`scalar`,T:9},{no:9,name:`num_participants`,kind:`scalar`,T:13},{no:11,name:`num_publishers`,kind:`scalar`,T:13},{no:10,name:`active_recording`,kind:`scalar`,T:8},{no:13,name:`version`,kind:`message`,T:ZA}]),sA=q.makeMessageType(`livekit.Codec`,()=>[{no:1,name:`mime`,kind:`scalar`,T:9},{no:2,name:`fmtp_line`,kind:`scalar`,T:9}]),cA=q.makeMessageType(`livekit.ParticipantPermission`,()=>[{no:1,name:`can_subscribe`,kind:`scalar`,T:8},{no:2,name:`can_publish`,kind:`scalar`,T:8},{no:3,name:`can_publish_data`,kind:`scalar`,T:8},{no:9,name:`can_publish_sources`,kind:`enum`,T:q.getEnumType(Zk),repeated:!0},{no:7,name:`hidden`,kind:`scalar`,T:8},{no:8,name:`recorder`,kind:`scalar`,T:8},{no:10,name:`can_update_metadata`,kind:`scalar`,T:8},{no:11,name:`agent`,kind:`scalar`,T:8},{no:12,name:`can_subscribe_metrics`,kind:`scalar`,T:8},{no:13,name:`can_manage_agent_session`,kind:`scalar`,T:8}]),lA=q.makeMessageType(`livekit.ParticipantInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`identity`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:q.getEnumType(uA)},{no:4,name:`tracks`,kind:`message`,T:hA,repeated:!0},{no:5,name:`metadata`,kind:`scalar`,T:9},{no:6,name:`joined_at`,kind:`scalar`,T:3},{no:17,name:`joined_at_ms`,kind:`scalar`,T:3},{no:9,name:`name`,kind:`scalar`,T:9},{no:10,name:`version`,kind:`scalar`,T:13},{no:11,name:`permission`,kind:`message`,T:cA},{no:12,name:`region`,kind:`scalar`,T:9},{no:13,name:`is_publisher`,kind:`scalar`,T:8},{no:14,name:`kind`,kind:`enum`,T:q.getEnumType(dA)},{no:15,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:16,name:`disconnect_reason`,kind:`enum`,T:q.getEnumType(tA)},{no:18,name:`kind_details`,kind:`enum`,T:q.getEnumType(fA),repeated:!0},{no:19,name:`data_tracks`,kind:`message`,T:gA,repeated:!0},{no:20,name:`client_protocol`,kind:`scalar`,T:5},{no:21,name:`capabilities`,kind:`enum`,T:q.getEnumType(qA),repeated:!0}]),uA=q.makeEnum(`livekit.ParticipantInfo.State`,[{no:0,name:`JOINING`},{no:1,name:`JOINED`},{no:2,name:`ACTIVE`},{no:3,name:`DISCONNECTED`}]),dA=q.makeEnum(`livekit.ParticipantInfo.Kind`,[{no:0,name:`STANDARD`},{no:1,name:`INGRESS`},{no:2,name:`EGRESS`},{no:3,name:`SIP`},{no:4,name:`AGENT`},{no:7,name:`CONNECTOR`},{no:8,name:`BRIDGE`}]),fA=q.makeEnum(`livekit.ParticipantInfo.KindDetail`,[{no:0,name:`CLOUD_AGENT`},{no:1,name:`FORWARDED`},{no:2,name:`CONNECTOR_WHATSAPP`},{no:3,name:`CONNECTOR_TWILIO`},{no:4,name:`BRIDGE_RTSP`},{no:5,name:`SIMULATION`}]),pA=q.makeEnum(`livekit.Encryption.Type`,[{no:0,name:`NONE`},{no:1,name:`GCM`},{no:2,name:`CUSTOM`}]),mA=q.makeMessageType(`livekit.SimulcastCodecInfo`,()=>[{no:1,name:`mime_type`,kind:`scalar`,T:9},{no:2,name:`mid`,kind:`scalar`,T:9},{no:3,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:TA,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:q.getEnumType(EA)},{no:6,name:`sdp_cid`,kind:`scalar`,T:9}]),hA=q.makeMessageType(`livekit.TrackInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`type`,kind:`enum`,T:q.getEnumType(Xk)},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`muted`,kind:`scalar`,T:8},{no:5,name:`width`,kind:`scalar`,T:13},{no:6,name:`height`,kind:`scalar`,T:13},{no:7,name:`simulcast`,kind:`scalar`,T:8},{no:8,name:`disable_dtx`,kind:`scalar`,T:8},{no:9,name:`source`,kind:`enum`,T:q.getEnumType(Zk)},{no:10,name:`layers`,kind:`message`,T:TA,repeated:!0},{no:11,name:`mime_type`,kind:`scalar`,T:9},{no:12,name:`mid`,kind:`scalar`,T:9},{no:13,name:`codecs`,kind:`message`,T:mA,repeated:!0},{no:14,name:`stereo`,kind:`scalar`,T:8},{no:15,name:`disable_red`,kind:`scalar`,T:8},{no:16,name:`encryption`,kind:`enum`,T:q.getEnumType(pA)},{no:17,name:`stream`,kind:`scalar`,T:9},{no:18,name:`version`,kind:`message`,T:ZA},{no:19,name:`audio_features`,kind:`enum`,T:q.getEnumType(iA),repeated:!0},{no:20,name:`backup_codec_policy`,kind:`enum`,T:q.getEnumType(Yk)},{no:21,name:`packet_trailer_features`,kind:`enum`,T:q.getEnumType(aA),repeated:!0}]),gA=q.makeMessageType(`livekit.DataTrackInfo`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`sid`,kind:`scalar`,T:9},{no:3,name:`name`,kind:`scalar`,T:9},{no:4,name:`encryption`,kind:`enum`,T:q.getEnumType(pA)},{no:5,name:`frame_encoding`,kind:`message`,T:_A,opt:!0},{no:6,name:`schema`,kind:`message`,T:xA,opt:!0}]),_A=q.makeMessageType(`livekit.DataTrackFrameEncoding`,()=>[{no:1,name:`well_known`,kind:`enum`,T:q.getEnumType(vA),oneof:`value`},{no:2,name:`custom`,kind:`scalar`,T:9,oneof:`value`}]),vA=q.makeEnum(`livekit.DataTrackFrameEncoding.WellKnownFrameEncoding`,[{no:0,name:`WELL_KNOWN_FRAME_ENCODING_UNSPECIFIED`,localName:`UNSPECIFIED`},{no:1,name:`WELL_KNOWN_FRAME_ENCODING_ROS1`,localName:`ROS1`},{no:2,name:`WELL_KNOWN_FRAME_ENCODING_CDR`,localName:`CDR`},{no:3,name:`WELL_KNOWN_FRAME_ENCODING_PROTOBUF`,localName:`PROTOBUF`},{no:4,name:`WELL_KNOWN_FRAME_ENCODING_FLATBUFFER`,localName:`FLATBUFFER`},{no:5,name:`WELL_KNOWN_FRAME_ENCODING_CBOR`,localName:`CBOR`},{no:6,name:`WELL_KNOWN_FRAME_ENCODING_MSGPACK`,localName:`MSGPACK`},{no:7,name:`WELL_KNOWN_FRAME_ENCODING_JSON`,localName:`JSON`}]),yA=q.makeMessageType(`livekit.DataTrackSchemaEncoding`,()=>[{no:1,name:`well_known`,kind:`enum`,T:q.getEnumType(bA),oneof:`value`},{no:2,name:`custom`,kind:`scalar`,T:9,oneof:`value`}]),bA=q.makeEnum(`livekit.DataTrackSchemaEncoding.WellKnownSchemaEncoding`,[{no:0,name:`WELL_KNOWN_SCHEMA_ENCODING_UNSPECIFIED`,localName:`UNSPECIFIED`},{no:1,name:`WELL_KNOWN_SCHEMA_ENCODING_PROTOBUF`,localName:`PROTOBUF`},{no:2,name:`WELL_KNOWN_SCHEMA_ENCODING_FLATBUFFER`,localName:`FLATBUFFER`},{no:3,name:`WELL_KNOWN_SCHEMA_ENCODING_ROS1_MSG`,localName:`ROS1_MSG`},{no:4,name:`WELL_KNOWN_SCHEMA_ENCODING_ROS2_MSG`,localName:`ROS2_MSG`},{no:5,name:`WELL_KNOWN_SCHEMA_ENCODING_ROS2_IDL`,localName:`ROS2_IDL`},{no:6,name:`WELL_KNOWN_SCHEMA_ENCODING_OMG_IDL`,localName:`OMG_IDL`},{no:7,name:`WELL_KNOWN_SCHEMA_ENCODING_JSON_SCHEMA`,localName:`JSON_SCHEMA`}]),xA=q.makeMessageType(`livekit.DataTrackSchemaId`,()=>[{no:1,name:`name`,kind:`scalar`,T:9},{no:2,name:`encoding`,kind:`message`,T:yA}]),SA=q.makeMessageType(`livekit.DataTrackSubscriptionOptions`,()=>[{no:1,name:`target_fps`,kind:`scalar`,T:13,opt:!0}]),CA=q.makeMessageType(`livekit.DataBlobKey`,()=>[{no:1,name:`generic`,kind:`scalar`,T:9,oneof:`key`},{no:2,name:`schema_id`,kind:`message`,T:xA,oneof:`key`}]),wA=q.makeMessageType(`livekit.DataBlob`,()=>[{no:1,name:`key`,kind:`message`,T:CA},{no:2,name:`contents`,kind:`scalar`,T:12}]),TA=q.makeMessageType(`livekit.VideoLayer`,()=>[{no:1,name:`quality`,kind:`enum`,T:q.getEnumType(Qk)},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13},{no:4,name:`bitrate`,kind:`scalar`,T:13},{no:5,name:`ssrc`,kind:`scalar`,T:13},{no:6,name:`spatial_layer`,kind:`scalar`,T:5},{no:7,name:`rid`,kind:`scalar`,T:9},{no:8,name:`repair_ssrc`,kind:`scalar`,T:13}]),EA=q.makeEnum(`livekit.VideoLayer.Mode`,[{no:0,name:`MODE_UNUSED`},{no:1,name:`ONE_SPATIAL_LAYER_PER_STREAM`},{no:2,name:`MULTIPLE_SPATIAL_LAYERS_PER_STREAM`},{no:3,name:`ONE_SPATIAL_LAYER_PER_STREAM_INCOMPLETE_RTCP_SR`}]),DA=q.makeMessageType(`livekit.DataPacket`,()=>[{no:1,name:`kind`,kind:`enum`,T:q.getEnumType(OA)},{no:4,name:`participant_identity`,kind:`scalar`,T:9},{no:5,name:`destination_identities`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`user`,kind:`message`,T:NA,oneof:`value`},{no:3,name:`speaker`,kind:`message`,T:jA,oneof:`value`},{no:6,name:`sip_dtmf`,kind:`message`,T:PA,oneof:`value`},{no:7,name:`transcription`,kind:`message`,T:FA,oneof:`value`},{no:8,name:`metrics`,kind:`message`,T:Gk,oneof:`value`},{no:9,name:`chat_message`,kind:`message`,T:LA,oneof:`value`},{no:10,name:`rpc_request`,kind:`message`,T:RA,oneof:`value`},{no:11,name:`rpc_ack`,kind:`message`,T:zA,oneof:`value`},{no:12,name:`rpc_response`,kind:`message`,T:BA,oneof:`value`},{no:13,name:`stream_header`,kind:`message`,T:nj,oneof:`value`},{no:14,name:`stream_chunk`,kind:`message`,T:rj,oneof:`value`},{no:15,name:`stream_trailer`,kind:`message`,T:ij,oneof:`value`},{no:18,name:`encrypted_packet`,kind:`message`,T:kA,oneof:`value`},{no:16,name:`sequence`,kind:`scalar`,T:13},{no:17,name:`participant_sid`,kind:`scalar`,T:9}]),OA=q.makeEnum(`livekit.DataPacket.Kind`,[{no:0,name:`RELIABLE`},{no:1,name:`LOSSY`}]),kA=q.makeMessageType(`livekit.EncryptedPacket`,()=>[{no:1,name:`encryption_type`,kind:`enum`,T:q.getEnumType(pA)},{no:2,name:`iv`,kind:`scalar`,T:12},{no:3,name:`key_index`,kind:`scalar`,T:13},{no:4,name:`encrypted_value`,kind:`scalar`,T:12}]),AA=q.makeMessageType(`livekit.EncryptedPacketPayload`,()=>[{no:1,name:`user`,kind:`message`,T:NA,oneof:`value`},{no:3,name:`chat_message`,kind:`message`,T:LA,oneof:`value`},{no:4,name:`rpc_request`,kind:`message`,T:RA,oneof:`value`},{no:5,name:`rpc_ack`,kind:`message`,T:zA,oneof:`value`},{no:6,name:`rpc_response`,kind:`message`,T:BA,oneof:`value`},{no:7,name:`stream_header`,kind:`message`,T:nj,oneof:`value`},{no:8,name:`stream_chunk`,kind:`message`,T:rj,oneof:`value`},{no:9,name:`stream_trailer`,kind:`message`,T:ij,oneof:`value`}]),jA=q.makeMessageType(`livekit.ActiveSpeakerUpdate`,()=>[{no:1,name:`speakers`,kind:`message`,T:MA,repeated:!0}]),MA=q.makeMessageType(`livekit.SpeakerInfo`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`level`,kind:`scalar`,T:2},{no:3,name:`active`,kind:`scalar`,T:8}]),NA=q.makeMessageType(`livekit.UserPacket`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:5,name:`participant_identity`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:12},{no:3,name:`destination_sids`,kind:`scalar`,T:9,repeated:!0},{no:6,name:`destination_identities`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`topic`,kind:`scalar`,T:9,opt:!0},{no:8,name:`id`,kind:`scalar`,T:9,opt:!0},{no:9,name:`start_time`,kind:`scalar`,T:4,opt:!0},{no:10,name:`end_time`,kind:`scalar`,T:4,opt:!0},{no:11,name:`nonce`,kind:`scalar`,T:12}]),PA=q.makeMessageType(`livekit.SipDTMF`,()=>[{no:3,name:`code`,kind:`scalar`,T:13},{no:4,name:`digit`,kind:`scalar`,T:9}]),FA=q.makeMessageType(`livekit.Transcription`,()=>[{no:2,name:`transcribed_participant_identity`,kind:`scalar`,T:9},{no:3,name:`track_id`,kind:`scalar`,T:9},{no:4,name:`segments`,kind:`message`,T:IA,repeated:!0}]),IA=q.makeMessageType(`livekit.TranscriptionSegment`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`text`,kind:`scalar`,T:9},{no:3,name:`start_time`,kind:`scalar`,T:4},{no:4,name:`end_time`,kind:`scalar`,T:4},{no:5,name:`final`,kind:`scalar`,T:8},{no:6,name:`language`,kind:`scalar`,T:9}]),LA=q.makeMessageType(`livekit.ChatMessage`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`edit_timestamp`,kind:`scalar`,T:3,opt:!0},{no:4,name:`message`,kind:`scalar`,T:9},{no:5,name:`deleted`,kind:`scalar`,T:8},{no:6,name:`generated`,kind:`scalar`,T:8}]),RA=q.makeMessageType(`livekit.RpcRequest`,()=>[{no:1,name:`id`,kind:`scalar`,T:9},{no:2,name:`method`,kind:`scalar`,T:9},{no:3,name:`payload`,kind:`scalar`,T:9},{no:4,name:`response_timeout_ms`,kind:`scalar`,T:13},{no:5,name:`version`,kind:`scalar`,T:13},{no:6,name:`compressed_payload`,kind:`scalar`,T:12}]),zA=q.makeMessageType(`livekit.RpcAck`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9}]),BA=q.makeMessageType(`livekit.RpcResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:9},{no:2,name:`payload`,kind:`scalar`,T:9,oneof:`value`},{no:3,name:`error`,kind:`message`,T:VA,oneof:`value`},{no:4,name:`compressed_payload`,kind:`scalar`,T:12,oneof:`value`}]),VA=q.makeMessageType(`livekit.RpcError`,()=>[{no:1,name:`code`,kind:`scalar`,T:13},{no:2,name:`message`,kind:`scalar`,T:9},{no:3,name:`data`,kind:`scalar`,T:9}]),HA=q.makeMessageType(`livekit.ParticipantTracks`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sids`,kind:`scalar`,T:9,repeated:!0}]),UA=q.makeMessageType(`livekit.ServerInfo`,()=>[{no:1,name:`edition`,kind:`enum`,T:q.getEnumType(WA)},{no:2,name:`version`,kind:`scalar`,T:9},{no:3,name:`protocol`,kind:`scalar`,T:5},{no:4,name:`region`,kind:`scalar`,T:9},{no:5,name:`node_id`,kind:`scalar`,T:9},{no:6,name:`debug_info`,kind:`scalar`,T:9},{no:7,name:`agent_protocol`,kind:`scalar`,T:5}]),WA=q.makeEnum(`livekit.ServerInfo.Edition`,[{no:0,name:`Standard`},{no:1,name:`Cloud`}]),GA=q.makeMessageType(`livekit.ClientInfo`,()=>[{no:1,name:`sdk`,kind:`enum`,T:q.getEnumType(KA)},{no:2,name:`version`,kind:`scalar`,T:9},{no:3,name:`protocol`,kind:`scalar`,T:5},{no:4,name:`os`,kind:`scalar`,T:9},{no:5,name:`os_version`,kind:`scalar`,T:9},{no:6,name:`device_model`,kind:`scalar`,T:9},{no:7,name:`browser`,kind:`scalar`,T:9},{no:8,name:`browser_version`,kind:`scalar`,T:9},{no:9,name:`address`,kind:`scalar`,T:9},{no:10,name:`network`,kind:`scalar`,T:9},{no:11,name:`other_sdks`,kind:`scalar`,T:9},{no:12,name:`client_protocol`,kind:`scalar`,T:5},{no:13,name:`capabilities`,kind:`enum`,T:q.getEnumType(qA),repeated:!0}]),KA=q.makeEnum(`livekit.ClientInfo.SDK`,[{no:0,name:`UNKNOWN`},{no:1,name:`JS`},{no:2,name:`SWIFT`},{no:3,name:`ANDROID`},{no:4,name:`FLUTTER`},{no:5,name:`GO`},{no:6,name:`UNITY`},{no:7,name:`REACT_NATIVE`},{no:8,name:`RUST`},{no:9,name:`PYTHON`},{no:10,name:`CPP`},{no:11,name:`UNITY_WEB`},{no:12,name:`NODE`},{no:13,name:`UNREAL`},{no:14,name:`ESP32`}]),qA=q.makeEnum(`livekit.ClientInfo.Capability`,[{no:0,name:`CAP_UNUSED`},{no:1,name:`CAP_PACKET_TRAILER`},{no:2,name:`CAP_COMPRESSION_DEFLATE_RAW`}]),JA=q.makeMessageType(`livekit.ClientConfiguration`,()=>[{no:1,name:`video`,kind:`message`,T:YA},{no:2,name:`screen`,kind:`message`,T:YA},{no:3,name:`resume_connection`,kind:`enum`,T:q.getEnumType(eA)},{no:4,name:`disabled_codecs`,kind:`message`,T:XA},{no:5,name:`force_relay`,kind:`enum`,T:q.getEnumType(eA)}]),YA=q.makeMessageType(`livekit.VideoConfiguration`,()=>[{no:1,name:`hardware_encoder`,kind:`enum`,T:q.getEnumType(eA)}]),XA=q.makeMessageType(`livekit.DisabledCodecs`,()=>[{no:1,name:`codecs`,kind:`message`,T:sA,repeated:!0},{no:2,name:`publish`,kind:`message`,T:sA,repeated:!0}]),ZA=q.makeMessageType(`livekit.TimedVersion`,()=>[{no:1,name:`unix_micro`,kind:`scalar`,T:3},{no:2,name:`ticks`,kind:`scalar`,T:5}]),QA=q.makeEnum(`livekit.DataStream.OperationType`,[{no:0,name:`CREATE`},{no:1,name:`UPDATE`},{no:2,name:`DELETE`},{no:3,name:`REACTION`}]),$A=q.makeEnum(`livekit.DataStream.CompressionType`,[{no:0,name:`NONE`},{no:1,name:`DEFLATE_RAW`}]),ej=q.makeMessageType(`livekit.DataStream.TextHeader`,()=>[{no:1,name:`operation_type`,kind:`enum`,T:q.getEnumType(QA)},{no:2,name:`version`,kind:`scalar`,T:5},{no:3,name:`reply_to_stream_id`,kind:`scalar`,T:9},{no:4,name:`attached_stream_ids`,kind:`scalar`,T:9,repeated:!0},{no:5,name:`generated`,kind:`scalar`,T:8}],{localName:`DataStream_TextHeader`}),tj=q.makeMessageType(`livekit.DataStream.ByteHeader`,()=>[{no:1,name:`name`,kind:`scalar`,T:9}],{localName:`DataStream_ByteHeader`}),nj=q.makeMessageType(`livekit.DataStream.Header`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`timestamp`,kind:`scalar`,T:3},{no:3,name:`topic`,kind:`scalar`,T:9},{no:4,name:`mime_type`,kind:`scalar`,T:9},{no:5,name:`total_length`,kind:`scalar`,T:4,opt:!0},{no:7,name:`encryption_type`,kind:`enum`,T:q.getEnumType(pA)},{no:8,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:9,name:`text_header`,kind:`message`,T:ej,oneof:`content_header`},{no:10,name:`byte_header`,kind:`message`,T:tj,oneof:`content_header`},{no:11,name:`inline_content`,kind:`scalar`,T:12,opt:!0},{no:12,name:`compression`,kind:`enum`,T:q.getEnumType($A)}],{localName:`DataStream_Header`}),rj=q.makeMessageType(`livekit.DataStream.Chunk`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`chunk_index`,kind:`scalar`,T:4},{no:3,name:`content`,kind:`scalar`,T:12},{no:4,name:`version`,kind:`scalar`,T:5},{no:5,name:`iv`,kind:`scalar`,T:12,opt:!0}],{localName:`DataStream_Chunk`}),ij=q.makeMessageType(`livekit.DataStream.Trailer`,()=>[{no:1,name:`stream_id`,kind:`scalar`,T:9},{no:2,name:`reason`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}],{localName:`DataStream_Trailer`}),aj=q.makeMessageType(`livekit.SubscribedAudioCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`enabled`,kind:`scalar`,T:8}]),oj=q.makeEnum(`livekit.SignalTarget`,[{no:0,name:`PUBLISHER`},{no:1,name:`SUBSCRIBER`}]),sj=q.makeEnum(`livekit.StreamState`,[{no:0,name:`ACTIVE`},{no:1,name:`PAUSED`}]),cj=q.makeEnum(`livekit.CandidateProtocol`,[{no:0,name:`UDP`},{no:1,name:`TCP`},{no:2,name:`TLS`}]),lj=q.makeMessageType(`livekit.SignalRequest`,()=>[{no:1,name:`offer`,kind:`message`,T:Tj,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Tj,oneof:`message`},{no:3,name:`trickle`,kind:`message`,T:yj,oneof:`message`},{no:4,name:`add_track`,kind:`message`,T:fj,oneof:`message`},{no:5,name:`mute`,kind:`message`,T:bj,oneof:`message`},{no:6,name:`subscription`,kind:`message`,T:Dj,oneof:`message`},{no:7,name:`track_setting`,kind:`message`,T:Pj,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Lj,oneof:`message`},{no:10,name:`update_layers`,kind:`message`,T:zj,oneof:`message`},{no:11,name:`subscription_permission`,kind:`message`,T:$j,oneof:`message`},{no:12,name:`sync_state`,kind:`message`,T:nM,oneof:`message`},{no:13,name:`simulate`,kind:`message`,T:aM,oneof:`message`},{no:14,name:`ping`,kind:`scalar`,T:3,oneof:`message`},{no:15,name:`update_metadata`,kind:`message`,T:Bj,oneof:`message`},{no:16,name:`ping_req`,kind:`message`,T:oM,oneof:`message`},{no:17,name:`update_audio_track`,kind:`message`,T:Fj,oneof:`message`},{no:18,name:`update_video_track`,kind:`message`,T:Ij,oneof:`message`},{no:19,name:`publish_data_track_request`,kind:`message`,T:pj,oneof:`message`},{no:20,name:`unpublish_data_track_request`,kind:`message`,T:hj,oneof:`message`},{no:21,name:`update_data_subscription`,kind:`message`,T:Oj,oneof:`message`},{no:22,name:`store_data_blob_request`,kind:`message`,T:Aj,oneof:`message`},{no:23,name:`get_data_blob_request`,kind:`message`,T:Mj,oneof:`message`}]),uj=q.makeMessageType(`livekit.SignalResponse`,()=>[{no:1,name:`join`,kind:`message`,T:xj,oneof:`message`},{no:2,name:`answer`,kind:`message`,T:Tj,oneof:`message`},{no:3,name:`offer`,kind:`message`,T:Tj,oneof:`message`},{no:4,name:`trickle`,kind:`message`,T:yj,oneof:`message`},{no:5,name:`update`,kind:`message`,T:Ej,oneof:`message`},{no:6,name:`track_published`,kind:`message`,T:Cj,oneof:`message`},{no:8,name:`leave`,kind:`message`,T:Lj,oneof:`message`},{no:9,name:`mute`,kind:`message`,T:bj,oneof:`message`},{no:10,name:`speakers_changed`,kind:`message`,T:Hj,oneof:`message`},{no:11,name:`room_update`,kind:`message`,T:Uj,oneof:`message`},{no:12,name:`connection_quality`,kind:`message`,T:Gj,oneof:`message`},{no:13,name:`stream_state_update`,kind:`message`,T:qj,oneof:`message`},{no:14,name:`subscribed_quality_update`,kind:`message`,T:Xj,oneof:`message`},{no:15,name:`subscription_permission_update`,kind:`message`,T:eM,oneof:`message`},{no:16,name:`refresh_token`,kind:`scalar`,T:9,oneof:`message`},{no:17,name:`track_unpublished`,kind:`message`,T:wj,oneof:`message`},{no:18,name:`pong`,kind:`scalar`,T:3,oneof:`message`},{no:19,name:`reconnect`,kind:`message`,T:Sj,oneof:`message`},{no:20,name:`pong_resp`,kind:`message`,T:sM,oneof:`message`},{no:21,name:`subscription_response`,kind:`message`,T:uM,oneof:`message`},{no:22,name:`request_response`,kind:`message`,T:dM,oneof:`message`},{no:23,name:`track_subscribed`,kind:`message`,T:pM,oneof:`message`},{no:24,name:`room_moved`,kind:`message`,T:tM,oneof:`message`},{no:25,name:`media_sections_requirement`,kind:`message`,T:vM,oneof:`message`},{no:26,name:`subscribed_audio_codec_update`,kind:`message`,T:Zj,oneof:`message`},{no:27,name:`publish_data_track_response`,kind:`message`,T:mj,oneof:`message`},{no:28,name:`unpublish_data_track_response`,kind:`message`,T:gj,oneof:`message`},{no:29,name:`data_track_subscriber_handles`,kind:`message`,T:_j,oneof:`message`},{no:30,name:`store_data_blob_response`,kind:`message`,T:jj,oneof:`message`},{no:31,name:`get_data_blob_response`,kind:`message`,T:Nj,oneof:`message`}]),dj=q.makeMessageType(`livekit.SimulcastCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`cid`,kind:`scalar`,T:9},{no:4,name:`layers`,kind:`message`,T:TA,repeated:!0},{no:5,name:`video_layer_mode`,kind:`enum`,T:q.getEnumType(EA)}]),fj=q.makeMessageType(`livekit.AddTrackRequest`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`type`,kind:`enum`,T:q.getEnumType(Xk)},{no:4,name:`width`,kind:`scalar`,T:13},{no:5,name:`height`,kind:`scalar`,T:13},{no:6,name:`muted`,kind:`scalar`,T:8},{no:7,name:`disable_dtx`,kind:`scalar`,T:8},{no:8,name:`source`,kind:`enum`,T:q.getEnumType(Zk)},{no:9,name:`layers`,kind:`message`,T:TA,repeated:!0},{no:10,name:`simulcast_codecs`,kind:`message`,T:dj,repeated:!0},{no:11,name:`sid`,kind:`scalar`,T:9},{no:12,name:`stereo`,kind:`scalar`,T:8},{no:13,name:`disable_red`,kind:`scalar`,T:8},{no:14,name:`encryption`,kind:`enum`,T:q.getEnumType(pA)},{no:15,name:`stream`,kind:`scalar`,T:9},{no:16,name:`backup_codec_policy`,kind:`enum`,T:q.getEnumType(Yk)},{no:17,name:`audio_features`,kind:`enum`,T:q.getEnumType(iA),repeated:!0},{no:18,name:`packet_trailer_features`,kind:`enum`,T:q.getEnumType(aA),repeated:!0}]),pj=q.makeMessageType(`livekit.PublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`encryption`,kind:`enum`,T:q.getEnumType(pA)},{no:4,name:`frame_encoding`,kind:`message`,T:_A,opt:!0},{no:5,name:`schema`,kind:`message`,T:xA,opt:!0}]),mj=q.makeMessageType(`livekit.PublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:gA}]),hj=q.makeMessageType(`livekit.UnpublishDataTrackRequest`,()=>[{no:1,name:`pub_handle`,kind:`scalar`,T:13}]),gj=q.makeMessageType(`livekit.UnpublishDataTrackResponse`,()=>[{no:1,name:`info`,kind:`message`,T:gA}]),_j=q.makeMessageType(`livekit.DataTrackSubscriberHandles`,()=>[{no:1,name:`sub_handles`,kind:`map`,K:13,V:{kind:`message`,T:vj}}]),vj=q.makeMessageType(`livekit.DataTrackSubscriberHandles.PublishedDataTrack`,()=>[{no:1,name:`publisher_identity`,kind:`scalar`,T:9},{no:2,name:`publisher_sid`,kind:`scalar`,T:9},{no:3,name:`track_sid`,kind:`scalar`,T:9}],{localName:`DataTrackSubscriberHandles_PublishedDataTrack`}),yj=q.makeMessageType(`livekit.TrickleRequest`,()=>[{no:1,name:`candidateInit`,kind:`scalar`,T:9},{no:2,name:`target`,kind:`enum`,T:q.getEnumType(oj)},{no:3,name:`final`,kind:`scalar`,T:8}]),bj=q.makeMessageType(`livekit.MuteTrackRequest`,()=>[{no:1,name:`sid`,kind:`scalar`,T:9},{no:2,name:`muted`,kind:`scalar`,T:8}]),xj=q.makeMessageType(`livekit.JoinResponse`,()=>[{no:1,name:`room`,kind:`message`,T:oA},{no:2,name:`participant`,kind:`message`,T:lA},{no:3,name:`other_participants`,kind:`message`,T:lA,repeated:!0},{no:4,name:`server_version`,kind:`scalar`,T:9},{no:5,name:`ice_servers`,kind:`message`,T:Vj,repeated:!0},{no:6,name:`subscriber_primary`,kind:`scalar`,T:8},{no:7,name:`alternative_url`,kind:`scalar`,T:9},{no:8,name:`client_configuration`,kind:`message`,T:JA},{no:9,name:`server_region`,kind:`scalar`,T:9},{no:10,name:`ping_timeout`,kind:`scalar`,T:5},{no:11,name:`ping_interval`,kind:`scalar`,T:5},{no:12,name:`server_info`,kind:`message`,T:UA},{no:13,name:`sif_trailer`,kind:`scalar`,T:12},{no:14,name:`enabled_publish_codecs`,kind:`message`,T:sA,repeated:!0},{no:15,name:`fast_publish`,kind:`scalar`,T:8}]),Sj=q.makeMessageType(`livekit.ReconnectResponse`,()=>[{no:1,name:`ice_servers`,kind:`message`,T:Vj,repeated:!0},{no:2,name:`client_configuration`,kind:`message`,T:JA},{no:3,name:`server_info`,kind:`message`,T:UA},{no:4,name:`last_message_seq`,kind:`scalar`,T:13}]),Cj=q.makeMessageType(`livekit.TrackPublishedResponse`,()=>[{no:1,name:`cid`,kind:`scalar`,T:9},{no:2,name:`track`,kind:`message`,T:hA}]),wj=q.makeMessageType(`livekit.TrackUnpublishedResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),Tj=q.makeMessageType(`livekit.SessionDescription`,()=>[{no:1,name:`type`,kind:`scalar`,T:9},{no:2,name:`sdp`,kind:`scalar`,T:9},{no:3,name:`id`,kind:`scalar`,T:13},{no:4,name:`mid_to_track_id`,kind:`map`,K:9,V:{kind:`scalar`,T:9}}]),Ej=q.makeMessageType(`livekit.ParticipantUpdate`,()=>[{no:1,name:`participants`,kind:`message`,T:lA,repeated:!0}]),Dj=q.makeMessageType(`livekit.UpdateSubscription`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`participant_tracks`,kind:`message`,T:HA,repeated:!0}]),Oj=q.makeMessageType(`livekit.UpdateDataSubscription`,()=>[{no:1,name:`updates`,kind:`message`,T:kj,repeated:!0}]),kj=q.makeMessageType(`livekit.UpdateDataSubscription.Update`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribe`,kind:`scalar`,T:8},{no:3,name:`options`,kind:`message`,T:SA}],{localName:`UpdateDataSubscription_Update`}),Aj=q.makeMessageType(`livekit.StoreDataBlobRequest`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`blob`,kind:`message`,T:wA}]),jj=q.makeMessageType(`livekit.StoreDataBlobResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`key`,kind:`message`,T:CA}]),Mj=q.makeMessageType(`livekit.GetDataBlobRequest`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`participant_identity`,kind:`scalar`,T:9},{no:3,name:`key`,kind:`message`,T:CA}]),Nj=q.makeMessageType(`livekit.GetDataBlobResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`blob`,kind:`message`,T:wA}]),Pj=q.makeMessageType(`livekit.UpdateTrackSettings`,()=>[{no:1,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:3,name:`disabled`,kind:`scalar`,T:8},{no:4,name:`quality`,kind:`enum`,T:q.getEnumType(Qk)},{no:5,name:`width`,kind:`scalar`,T:13},{no:6,name:`height`,kind:`scalar`,T:13},{no:7,name:`fps`,kind:`scalar`,T:13},{no:8,name:`priority`,kind:`scalar`,T:13}]),Fj=q.makeMessageType(`livekit.UpdateLocalAudioTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`features`,kind:`enum`,T:q.getEnumType(iA),repeated:!0}]),Ij=q.makeMessageType(`livekit.UpdateLocalVideoTrack`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`width`,kind:`scalar`,T:13},{no:3,name:`height`,kind:`scalar`,T:13}]),Lj=q.makeMessageType(`livekit.LeaveRequest`,()=>[{no:1,name:`can_reconnect`,kind:`scalar`,T:8},{no:2,name:`reason`,kind:`enum`,T:q.getEnumType(tA)},{no:3,name:`action`,kind:`enum`,T:q.getEnumType(Rj)},{no:4,name:`regions`,kind:`message`,T:cM}]),Rj=q.makeEnum(`livekit.LeaveRequest.Action`,[{no:0,name:`DISCONNECT`},{no:1,name:`RESUME`},{no:2,name:`RECONNECT`}]),zj=q.makeMessageType(`livekit.UpdateVideoLayers`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`layers`,kind:`message`,T:TA,repeated:!0}]),Bj=q.makeMessageType(`livekit.UpdateParticipantMetadata`,()=>[{no:1,name:`metadata`,kind:`scalar`,T:9},{no:2,name:`name`,kind:`scalar`,T:9},{no:3,name:`attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:4,name:`request_id`,kind:`scalar`,T:13}]),Vj=q.makeMessageType(`livekit.ICEServer`,()=>[{no:1,name:`urls`,kind:`scalar`,T:9,repeated:!0},{no:2,name:`username`,kind:`scalar`,T:9},{no:3,name:`credential`,kind:`scalar`,T:9}]),Hj=q.makeMessageType(`livekit.SpeakersChanged`,()=>[{no:1,name:`speakers`,kind:`message`,T:MA,repeated:!0}]),Uj=q.makeMessageType(`livekit.RoomUpdate`,()=>[{no:1,name:`room`,kind:`message`,T:oA}]),Wj=q.makeMessageType(`livekit.ConnectionQualityInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`quality`,kind:`enum`,T:q.getEnumType($k)},{no:3,name:`score`,kind:`scalar`,T:2}]),Gj=q.makeMessageType(`livekit.ConnectionQualityUpdate`,()=>[{no:1,name:`updates`,kind:`message`,T:Wj,repeated:!0}]),Kj=q.makeMessageType(`livekit.StreamStateInfo`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`state`,kind:`enum`,T:q.getEnumType(sj)}]),qj=q.makeMessageType(`livekit.StreamStateUpdate`,()=>[{no:1,name:`stream_states`,kind:`message`,T:Kj,repeated:!0}]),Jj=q.makeMessageType(`livekit.SubscribedQuality`,()=>[{no:1,name:`quality`,kind:`enum`,T:q.getEnumType(Qk)},{no:2,name:`enabled`,kind:`scalar`,T:8}]),Yj=q.makeMessageType(`livekit.SubscribedCodec`,()=>[{no:1,name:`codec`,kind:`scalar`,T:9},{no:2,name:`qualities`,kind:`message`,T:Jj,repeated:!0}]),Xj=q.makeMessageType(`livekit.SubscribedQualityUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_qualities`,kind:`message`,T:Jj,repeated:!0},{no:3,name:`subscribed_codecs`,kind:`message`,T:Yj,repeated:!0}]),Zj=q.makeMessageType(`livekit.SubscribedAudioCodecUpdate`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`subscribed_audio_codecs`,kind:`message`,T:aj,repeated:!0}]),Qj=q.makeMessageType(`livekit.TrackPermission`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`all_tracks`,kind:`scalar`,T:8},{no:3,name:`track_sids`,kind:`scalar`,T:9,repeated:!0},{no:4,name:`participant_identity`,kind:`scalar`,T:9}]),$j=q.makeMessageType(`livekit.SubscriptionPermission`,()=>[{no:1,name:`all_participants`,kind:`scalar`,T:8},{no:2,name:`track_permissions`,kind:`message`,T:Qj,repeated:!0}]),eM=q.makeMessageType(`livekit.SubscriptionPermissionUpdate`,()=>[{no:1,name:`participant_sid`,kind:`scalar`,T:9},{no:2,name:`track_sid`,kind:`scalar`,T:9},{no:3,name:`allowed`,kind:`scalar`,T:8}]),tM=q.makeMessageType(`livekit.RoomMovedResponse`,()=>[{no:1,name:`room`,kind:`message`,T:oA},{no:2,name:`token`,kind:`scalar`,T:9},{no:3,name:`participant`,kind:`message`,T:lA},{no:4,name:`other_participants`,kind:`message`,T:lA,repeated:!0}]),nM=q.makeMessageType(`livekit.SyncState`,()=>[{no:1,name:`answer`,kind:`message`,T:Tj},{no:2,name:`subscription`,kind:`message`,T:Dj},{no:3,name:`publish_tracks`,kind:`message`,T:Cj,repeated:!0},{no:4,name:`data_channels`,kind:`message`,T:iM,repeated:!0},{no:5,name:`offer`,kind:`message`,T:Tj},{no:6,name:`track_sids_disabled`,kind:`scalar`,T:9,repeated:!0},{no:7,name:`datachannel_receive_states`,kind:`message`,T:rM,repeated:!0},{no:8,name:`publish_data_tracks`,kind:`message`,T:mj,repeated:!0}]),rM=q.makeMessageType(`livekit.DataChannelReceiveState`,()=>[{no:1,name:`publisher_sid`,kind:`scalar`,T:9},{no:2,name:`last_seq`,kind:`scalar`,T:13}]),iM=q.makeMessageType(`livekit.DataChannelInfo`,()=>[{no:1,name:`label`,kind:`scalar`,T:9},{no:2,name:`id`,kind:`scalar`,T:13},{no:3,name:`target`,kind:`enum`,T:q.getEnumType(oj)}]),aM=q.makeMessageType(`livekit.SimulateScenario`,()=>[{no:1,name:`speaker_update`,kind:`scalar`,T:5,oneof:`scenario`},{no:2,name:`node_failure`,kind:`scalar`,T:8,oneof:`scenario`},{no:3,name:`migration`,kind:`scalar`,T:8,oneof:`scenario`},{no:4,name:`server_leave`,kind:`scalar`,T:8,oneof:`scenario`},{no:5,name:`switch_candidate_protocol`,kind:`enum`,T:q.getEnumType(cj),oneof:`scenario`},{no:6,name:`subscriber_bandwidth`,kind:`scalar`,T:3,oneof:`scenario`},{no:7,name:`disconnect_signal_on_resume`,kind:`scalar`,T:8,oneof:`scenario`},{no:8,name:`disconnect_signal_on_resume_no_messages`,kind:`scalar`,T:8,oneof:`scenario`},{no:9,name:`leave_request_full_reconnect`,kind:`scalar`,T:8,oneof:`scenario`}]),oM=q.makeMessageType(`livekit.Ping`,()=>[{no:1,name:`timestamp`,kind:`scalar`,T:3},{no:2,name:`rtt`,kind:`scalar`,T:3}]),sM=q.makeMessageType(`livekit.Pong`,()=>[{no:1,name:`last_ping_timestamp`,kind:`scalar`,T:3},{no:2,name:`timestamp`,kind:`scalar`,T:3}]),cM=q.makeMessageType(`livekit.RegionSettings`,()=>[{no:1,name:`regions`,kind:`message`,T:lM,repeated:!0}]),lM=q.makeMessageType(`livekit.RegionInfo`,()=>[{no:1,name:`region`,kind:`scalar`,T:9},{no:2,name:`url`,kind:`scalar`,T:9},{no:3,name:`distance`,kind:`scalar`,T:3}]),uM=q.makeMessageType(`livekit.SubscriptionResponse`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9},{no:2,name:`err`,kind:`enum`,T:q.getEnumType(rA)}]),dM=q.makeMessageType(`livekit.RequestResponse`,()=>[{no:1,name:`request_id`,kind:`scalar`,T:13},{no:2,name:`reason`,kind:`enum`,T:q.getEnumType(fM)},{no:3,name:`message`,kind:`scalar`,T:9},{no:4,name:`trickle`,kind:`message`,T:yj,oneof:`request`},{no:5,name:`add_track`,kind:`message`,T:fj,oneof:`request`},{no:6,name:`mute`,kind:`message`,T:bj,oneof:`request`},{no:7,name:`update_metadata`,kind:`message`,T:Bj,oneof:`request`},{no:8,name:`update_audio_track`,kind:`message`,T:Fj,oneof:`request`},{no:9,name:`update_video_track`,kind:`message`,T:Ij,oneof:`request`},{no:10,name:`publish_data_track`,kind:`message`,T:pj,oneof:`request`},{no:11,name:`unpublish_data_track`,kind:`message`,T:hj,oneof:`request`}]),fM=q.makeEnum(`livekit.RequestResponse.Reason`,[{no:0,name:`OK`},{no:1,name:`NOT_FOUND`},{no:2,name:`NOT_ALLOWED`},{no:3,name:`LIMIT_EXCEEDED`},{no:4,name:`QUEUED`},{no:5,name:`UNSUPPORTED_TYPE`},{no:6,name:`UNCLASSIFIED_ERROR`},{no:7,name:`INVALID_HANDLE`},{no:8,name:`INVALID_NAME`},{no:9,name:`DUPLICATE_HANDLE`},{no:10,name:`DUPLICATE_NAME`},{no:11,name:`INVALID_REQUEST`}]),pM=q.makeMessageType(`livekit.TrackSubscribed`,()=>[{no:1,name:`track_sid`,kind:`scalar`,T:9}]),mM=q.makeMessageType(`livekit.ConnectionSettings`,()=>[{no:1,name:`auto_subscribe`,kind:`scalar`,T:8},{no:2,name:`adaptive_stream`,kind:`scalar`,T:8},{no:3,name:`subscriber_allow_pause`,kind:`scalar`,T:8,opt:!0},{no:4,name:`disable_ice_lite`,kind:`scalar`,T:8},{no:5,name:`auto_subscribe_data_track`,kind:`scalar`,T:8,opt:!0}]),hM=q.makeMessageType(`livekit.JoinRequest`,()=>[{no:1,name:`client_info`,kind:`message`,T:GA},{no:2,name:`connection_settings`,kind:`message`,T:mM},{no:3,name:`metadata`,kind:`scalar`,T:9},{no:4,name:`participant_attributes`,kind:`map`,K:9,V:{kind:`scalar`,T:9}},{no:5,name:`add_track_requests`,kind:`message`,T:fj,repeated:!0},{no:6,name:`publisher_offer`,kind:`message`,T:Tj},{no:7,name:`reconnect`,kind:`scalar`,T:8},{no:8,name:`reconnect_reason`,kind:`enum`,T:q.getEnumType(nA)},{no:9,name:`participant_sid`,kind:`scalar`,T:9},{no:10,name:`sync_state`,kind:`message`,T:nM}]),gM=q.makeMessageType(`livekit.WrappedJoinRequest`,()=>[{no:1,name:`compression`,kind:`enum`,T:q.getEnumType(_M)},{no:2,name:`join_request`,kind:`scalar`,T:12}]),_M=q.makeEnum(`livekit.WrappedJoinRequest.Compression`,[{no:0,name:`NONE`},{no:1,name:`GZIP`}]),vM=q.makeMessageType(`livekit.MediaSectionsRequirement`,()=>[{no:1,name:`num_audios`,kind:`scalar`,T:13},{no:2,name:`num_videos`,kind:`scalar`,T:13}]);function yM(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,`default`)?e.default:e}var bM={exports:{}},xM=bM.exports,SM;function CM(){return SM?bM.exports:(SM=1,(function(e){(function(t,n){e.exports?e.exports=n():t.log=n()})(xM,function(){var e=function(){},t=`undefined`,n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=[`trace`,`debug`,`info`,`warn`,`error`],i={},a=null;function o(e,t){var n=e[t];if(typeof n.bind==`function`)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch{return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function c(r){return r===`debug`&&(r=`log`),typeof console===t?!1:r===`trace`&&n?s:console[r]===void 0?console.log===void 0?e:o(console,`log`):o(console,r)}function l(){for(var n=this.getLevel(),i=0;i<r.length;i++){var a=r[i];this[a]=i<n?e:this.methodFactory(a,n,this.name)}if(this.log=this.debug,typeof console===t&&n<this.levels.SILENT)return`No console available for logging`}function u(e){return function(){typeof console!==t&&(l.call(this),this[e].apply(this,arguments))}}function d(e,t,n){return c(e)||u.apply(this,arguments)}function f(e,n){var o=this,s,c,u,f=`loglevel`;typeof e==`string`?f+=`:`+e:typeof e==`symbol`&&(f=void 0);function p(e){var n=(r[e]||`silent`).toUpperCase();if(typeof window!==t&&f){try{window.localStorage[f]=n;return}catch{}try{window.document.cookie=encodeURIComponent(f)+`=`+n+`;`}catch{}}}function m(){var e;if(typeof window!==t&&f){try{e=window.localStorage[f]}catch{}if(typeof e===t)try{var n=window.document.cookie,r=encodeURIComponent(f),i=n.indexOf(r+`=`);i!==-1&&(e=/^([^;]+)/.exec(n.slice(i+r.length+1))[1])}catch{}return o.levels[e]===void 0&&(e=void 0),e}}function h(){if(typeof window!==t&&f){try{window.localStorage.removeItem(f)}catch{}try{window.document.cookie=encodeURIComponent(f)+`=; expires=Thu, 01 Jan 1970 00:00:00 UTC`}catch{}}}function g(e){var t=e;if(typeof t==`string`&&o.levels[t.toUpperCase()]!==void 0&&(t=o.levels[t.toUpperCase()]),typeof t==`number`&&t>=0&&t<=o.levels.SILENT)return t;throw TypeError(`log.setLevel() called with invalid level: `+e)}o.name=e,o.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},o.methodFactory=n||d,o.getLevel=function(){return u??c??s},o.setLevel=function(e,t){return u=g(e),t!==!1&&p(u),l.call(o)},o.setDefaultLevel=function(e){c=g(e),m()||o.setLevel(e,!1)},o.resetLevel=function(){u=null,h(),l.call(o)},o.enableAll=function(e){o.setLevel(o.levels.TRACE,e)},o.disableAll=function(e){o.setLevel(o.levels.SILENT,e)},o.rebuild=function(){if(a!==o&&(s=g(a.getLevel())),l.call(o),a===o)for(var e in i)i[e].rebuild()},s=g(a?a.getLevel():`WARN`);var _=m();_!=null&&(u=g(_)),l.call(o)}a=new f,a.getLogger=function(e){if(typeof e!=`symbol`&&typeof e!=`string`||e===``)throw TypeError(`You must supply a name when creating a logger.`);var t=i[e];return t||=i[e]=new f(e,a.methodFactory),t};var p=typeof window===t?void 0:window.log;return a.noConflict=function(){return typeof window!==t&&window.log===a&&(window.log=p),a},a.getLoggers=function(){return i},a.default=a,a})})(bM),bM.exports)}var wM=CM(),TM;(function(e){e[e.trace=0]=`trace`,e[e.debug=1]=`debug`,e[e.info=2]=`info`,e[e.warn=3]=`warn`,e[e.error=4]=`error`,e[e.silent=5]=`silent`})(TM||={});var EM;(function(e){e.Default=`livekit`,e.Room=`livekit-room`,e.TokenSource=`livekit-token-source`,e.Participant=`livekit-participant`,e.Track=`livekit-track`,e.Publication=`livekit-track-publication`,e.Engine=`livekit-engine`,e.Signal=`livekit-signal`,e.PCManager=`livekit-pc-manager`,e.PCTransport=`livekit-pc-transport`,e.E2EE=`lk-e2ee`,e.DataTracks=`livekit-data-tracks`,e.Region=`livekit-region`,e.ICE=`livekit-ice`,e.Stats=`livekit-stats`})(EM||={});var DM=wM.getLogger(EM.Default);Object.values(EM).map(e=>wM.getLogger(e)),DM.setDefaultLevel(TM.info);function OM(e,t){let n=wM.getLogger(e);return n.setDefaultLevel(DM.getLevel()),t?kM(n,t):n}function kM(e,t){let n=n=>(r,i)=>{let a=t(),o=a||i?Object.assign(Object.assign({},a),i):void 0;e[n](r,o)},r=Object.create(e);return r.trace=n(`trace`),r.debug=n(`debug`),r.info=n(`info`),r.warn=n(`warn`),r.error=n(`error`),r}var AM=wM.getLogger(EM.E2EE),jM=new Set,MM=AM.setLevel.bind(AM);AM.setLevel=(e,t)=>{MM(e,t);let n=AM.getLevel();jM.forEach(e=>e(n))};function NM(e){return jM.add(e),()=>{jM.delete(e)}}var PM=7e3,FM=[0,300,1200,2700,4800,PM,PM,PM,PM,PM],IM=class{constructor(e){this._retryDelays=e===void 0?FM:[...e]}nextRetryDelayInMs(e){if(e.retryCount>=this._retryDelays.length)return null;let t=this._retryDelays[e.retryCount];return e.retryCount<=1?t:t+Math.random()*1e3}};function LM(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function J(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function RM(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function zM(e){return this instanceof zM?(this.v=e,this):new zM(e)}function BM(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof zM?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function VM(e){var t={},n;return r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:zM(e[r](t)),done:!1}:i?i(t):t}:i}}function HM(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof RM==`function`?RM(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}var UM={exports:{}},WM;function GM(){if(WM)return UM.exports;WM=1;var e=typeof Reflect==`object`?Reflect:null,t=e&&typeof e.apply==`function`?e.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)},n=e&&typeof e.ownKeys==`function`?e.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};function r(e){console&&console.warn&&console.warn(e)}var i=Number.isNaN||function(e){return e!==e};function a(){a.init.call(this)}UM.exports=a,UM.exports.once=_,a.EventEmitter=a,a.prototype._events=void 0,a.prototype._eventsCount=0,a.prototype._maxListeners=void 0;var o=10;function s(e){if(typeof e!=`function`)throw TypeError(`The "listener" argument must be of type Function. Received type `+typeof e)}Object.defineProperty(a,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if(typeof e!=`number`||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}}),a.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},a.prototype.setMaxListeners=function(e){if(typeof e!=`number`||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};function c(e){return e._maxListeners===void 0?a.defaultMaxListeners:e._maxListeners}a.prototype.getMaxListeners=function(){return c(this)},a.prototype.emit=function(e){for(var n=[],r=1;r<arguments.length;r++)n.push(arguments[r]);var i=e===`error`,a=this._events;if(a!==void 0)i&&=a.error===void 0;else if(!i)return!1;if(i){var o;if(n.length>0&&(o=n[0]),o instanceof Error)throw o;var s=Error(`Unhandled error.`+(o?` (`+o.message+`)`:``));throw s.context=o,s}var c=a[e];if(c===void 0)return!1;if(typeof c==`function`)t(c,this,n);else for(var l=c.length,u=m(c,l),r=0;r<l;++r)t(u[r],this,n);return!0};function l(e,t,n,i){var a,o,l;if(s(n),o=e._events,o===void 0?(o=e._events=Object.create(null),e._eventsCount=0):(o.newListener!==void 0&&(e.emit(`newListener`,t,n.listener?n.listener:n),o=e._events),l=o[t]),l===void 0)l=o[t]=n,++e._eventsCount;else if(typeof l==`function`?l=o[t]=i?[n,l]:[l,n]:i?l.unshift(n):l.push(n),a=c(e),a>0&&l.length>a&&!l.warned){l.warned=!0;var u=Error(`Possible EventEmitter memory leak detected. `+l.length+` `+String(t)+` listeners added. Use emitter.setMaxListeners() to increase limit`);u.name=`MaxListenersExceededWarning`,u.emitter=e,u.type=t,u.count=l.length,r(u)}return e}a.prototype.addListener=function(e,t){return l(this,e,t,!1)},a.prototype.on=a.prototype.addListener,a.prototype.prependListener=function(e,t){return l(this,e,t,!0)};function u(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,arguments.length===0?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function d(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=u.bind(r);return i.listener=n,r.wrapFn=i,i}a.prototype.once=function(e,t){return s(t),this.on(e,d(this,e,t)),this},a.prototype.prependOnceListener=function(e,t){return s(t),this.prependListener(e,d(this,e,t)),this},a.prototype.removeListener=function(e,t){var n,r,i,a,o;if(s(t),r=this._events,r===void 0||(n=r[e],n===void 0))return this;if(n===t||n.listener===t)--this._eventsCount===0?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit(`removeListener`,e,n.listener||t));else if(typeof n!=`function`){for(i=-1,a=n.length-1;a>=0;a--)if(n[a]===t||n[a].listener===t){o=n[a].listener,i=a;break}if(i<0)return this;i===0?n.shift():h(n,i),n.length===1&&(r[e]=n[0]),r.removeListener!==void 0&&this.emit(`removeListener`,e,o||t)}return this},a.prototype.off=a.prototype.removeListener,a.prototype.removeAllListeners=function(e){var t,n=this._events,r;if(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),a;for(r=0;r<i.length;++r)a=i[r],a!==`removeListener`&&this.removeAllListeners(a);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(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this};function f(e,t,n){var r=e._events;if(r===void 0)return[];var i=r[t];return i===void 0?[]:typeof i==`function`?n?[i.listener||i]:[i]:n?g(i):m(i,i.length)}a.prototype.listeners=function(e){return f(this,e,!0)},a.prototype.rawListeners=function(e){return f(this,e,!1)},a.listenerCount=function(e,t){return typeof e.listenerCount==`function`?e.listenerCount(t):p.call(e,t)},a.prototype.listenerCount=p;function p(e){var t=this._events;if(t!==void 0){var n=t[e];if(typeof n==`function`)return 1;if(n!==void 0)return n.length}return 0}a.prototype.eventNames=function(){return this._eventsCount>0?n(this._events):[]};function m(e,t){for(var n=Array(t),r=0;r<t;++r)n[r]=e[r];return n}function h(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}function g(e){for(var t=Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}function _(e,t){return new Promise(function(n,r){function i(n){e.removeListener(t,a),r(n)}function a(){typeof e.removeListener==`function`&&e.removeListener(`error`,i),n([].slice.call(arguments))}y(e,t,a,{once:!0}),t!==`error`&&v(e,i,{once:!0})})}function v(e,t,n){typeof e.on==`function`&&y(e,`error`,t,n)}function y(e,t,n,r){if(typeof e.on==`function`)r.once?e.once(t,n):e.on(t,n);else if(typeof e.addEventListener==`function`)e.addEventListener(t,function i(a){r.once&&e.removeEventListener(t,i),n(a)});else throw TypeError(`The "emitter" argument must be of type EventEmitter. Received type `+typeof e)}return UM.exports}var KM=GM(),qM=!0,JM=!0;function YM(e,t,n){let r=e.match(t);return r&&r.length>=n&&parseFloat(r[n],10)}function XM(e,t,n){if(!e.RTCPeerConnection)return;if(!Object.getOwnPropertyDescriptor(EventTarget.prototype,`addEventListener`).writable){$M(`Unable to polyfill events`);return}let r=e.RTCPeerConnection.prototype,i=r.addEventListener;r.addEventListener=function(e,r){if(e!==t)return i.apply(this,arguments);let a=e=>{let t=n(e);t&&(r.handleEvent?r.handleEvent(t):r(t))};return this._eventMap=this._eventMap||{},this._eventMap[t]||(this._eventMap[t]=new Map),this._eventMap[t].set(r,a),i.apply(this,[e,a])};let a=r.removeEventListener;r.removeEventListener=function(e,n){if(e!==t||!this._eventMap||!this._eventMap[t]||!this._eventMap[t].has(n))return a.apply(this,arguments);let r=this._eventMap[t].get(n);return this._eventMap[t].delete(n),this._eventMap[t].size===0&&delete this._eventMap[t],Object.keys(this._eventMap).length===0&&delete this._eventMap,a.apply(this,[e,r])},Object.defineProperty(r,`on`+t,{get(){return this[`_on`+t]},set(e){this[`_on`+t]&&(this.removeEventListener(t,this[`_on`+t]),delete this[`_on`+t]),e&&this.addEventListener(t,this[`_on`+t]=e)},enumerable:!0,configurable:!0})}function ZM(e){return typeof e==`boolean`?(qM=e,e?`adapter.js logging disabled`:`adapter.js logging enabled`):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function QM(e){return typeof e==`boolean`?(JM=!e,`adapter.js deprecation warnings `+(e?`disabled`:`enabled`)):Error(`Argument type: `+typeof e+`. Please use a boolean.`)}function $M(){if(typeof window==`object`){if(qM)return;typeof console<`u`&&typeof console.log==`function`&&console.log.apply(console,arguments)}}function eN(e,t){JM&&console.warn(e+` is deprecated, please use `+t+` instead.`)}function tN(e){let t={browser:null,version:null};if(e===void 0||!e.navigator||!e.navigator.userAgent)return t.browser=`Not a browser.`,t;let n=e.navigator;if(n.userAgentData&&n.userAgentData.brands){let e=n.userAgentData.brands.find(e=>e.brand===`Chromium`);if(e){let t=parseInt(e.version,10);if(t>=90)return{browser:`chrome`,version:t}}}if(n.mozGetUserMedia)t.browser=`firefox`,t.version=parseInt(YM(n.userAgent,/Firefox\/(\d+)\./,1));else if(n.webkitGetUserMedia||e.isSecureContext===!1&&e.webkitRTCPeerConnection)t.browser=`chrome`,t.version=parseInt(YM(n.userAgent,/Chrom(e|ium)\/(\d+)\./,2))||null;else if(e.RTCPeerConnection&&n.userAgent.match(/AppleWebKit\/(\d+)\./))t.browser=`safari`,t.version=parseInt(YM(n.userAgent,/AppleWebKit\/(\d+)\./,1)),t.supportsUnifiedPlan=e.RTCRtpTransceiver&&`currentDirection`in e.RTCRtpTransceiver.prototype,t._safariVersion=YM(n.userAgent,/Version\/(\d+(\.?\d+))/,1);else return t.browser=`Not a supported browser.`,t;return t}function nN(e){return Object.prototype.toString.call(e)===`[object Object]`}function rN(e){return nN(e)?Object.keys(e).reduce(function(t,n){let r=nN(e[n]),i=r?rN(e[n]):e[n],a=r&&!Object.keys(i).length;return i===void 0||a?t:Object.assign(t,{[n]:i})},{}):e}function iN(e,t,n){t&&!n.has(t.id)&&(n.set(t.id,t),Object.keys(t).forEach(r=>{r.endsWith(`Id`)?iN(e,e.get(t[r]),n):r.endsWith(`Ids`)&&t[r].forEach(t=>{iN(e,e.get(t),n)})}))}function aN(e,t,n){let r=n?`outbound-rtp`:`inbound-rtp`,i=new Map;if(t===null)return i;let a=[];return e.forEach(e=>{e.type===`track`&&e.trackIdentifier===t.id&&a.push(e)}),a.forEach(t=>{e.forEach(n=>{n.type===r&&n.trackId===t.id&&iN(e,n,i)})}),i}var oN=$M;function sN(e,t){if(t.version>=64)return;let n=e&&e.navigator;if(!n.mediaDevices)return;let r=function(e){if(typeof e!=`object`||e.mandatory||e.optional)return e;let t={};return Object.keys(e).forEach(n=>{if(n===`require`||n===`advanced`||n===`mediaSource`)return;let r=typeof e[n]==`object`?e[n]:{ideal:e[n]};r.exact!==void 0&&typeof r.exact==`number`&&(r.min=r.max=r.exact);let i=function(e,t){return e?e+t.charAt(0).toUpperCase()+t.slice(1):t===`deviceId`?`sourceId`:t};if(r.ideal!==void 0){t.optional=t.optional||[];let e={};typeof r.ideal==`number`?(e[i(`min`,n)]=r.ideal,t.optional.push(e),e={},e[i(`max`,n)]=r.ideal,t.optional.push(e)):(e[i(``,n)]=r.ideal,t.optional.push(e))}r.exact!==void 0&&typeof r.exact!=`number`?(t.mandatory=t.mandatory||{},t.mandatory[i(``,n)]=r.exact):[`min`,`max`].forEach(e=>{r[e]!==void 0&&(t.mandatory=t.mandatory||{},t.mandatory[i(e,n)]=r[e])})}),e.advanced&&(t.optional=(t.optional||[]).concat(e.advanced)),t},i=function(e,i){if(t.version>=61)return i(e);if(e=JSON.parse(JSON.stringify(e)),e&&typeof e.audio==`object`){let t=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])};e=JSON.parse(JSON.stringify(e)),t(e.audio,`autoGainControl`,`googAutoGainControl`),t(e.audio,`noiseSuppression`,`googNoiseSuppression`),e.audio=r(e.audio)}if(e&&typeof e.video==`object`){let a=e.video.facingMode;a&&=typeof a==`object`?a:{ideal:a};let o=t.version<66;if(a&&(a.exact===`user`||a.exact===`environment`||a.ideal===`user`||a.ideal===`environment`)&&!(n.mediaDevices.getSupportedConstraints&&n.mediaDevices.getSupportedConstraints().facingMode&&!o)){delete e.video.facingMode;let t;if(a.exact===`environment`||a.ideal===`environment`?t=[`back`,`rear`]:(a.exact===`user`||a.ideal===`user`)&&(t=[`front`]),t)return n.mediaDevices.enumerateDevices().then(n=>{n=n.filter(e=>e.kind===`videoinput`);let o=n.find(e=>t.some(t=>e.label.toLowerCase().includes(t)));return!o&&n.length&&t.includes(`back`)&&(o=n[n.length-1]),o&&(e.video.deviceId=a.exact?{exact:o.deviceId}:{ideal:o.deviceId}),e.video=r(e.video),oN(`chrome: `+JSON.stringify(e)),i(e)})}e.video=r(e.video)}return oN(`chrome: `+JSON.stringify(e)),i(e)},a=function(e){return t.version>=64?e:{name:{PermissionDeniedError:`NotAllowedError`,PermissionDismissedError:`NotAllowedError`,InvalidStateError:`NotAllowedError`,DevicesNotFoundError:`NotFoundError`,ConstraintNotSatisfiedError:`OverconstrainedError`,TrackStartError:`NotReadableError`,MediaDeviceFailedDueToShutdown:`NotAllowedError`,MediaDeviceKillSwitchOn:`NotAllowedError`,TabCaptureError:`AbortError`,ScreenCaptureError:`AbortError`,DeviceCaptureError:`AbortError`}[e.name]||e.name,message:e.message,constraint:e.constraint||e.constraintName,toString(){return this.name+(this.message&&`: `)+this.message}}};if(n.getUserMedia=function(e,t,r){i(e,e=>{n.webkitGetUserMedia(e,t,e=>{r&&r(a(e))})})}.bind(n),n.mediaDevices.getUserMedia){let e=n.mediaDevices.getUserMedia.bind(n.mediaDevices);n.mediaDevices.getUserMedia=function(t){return i(t,t=>e(t).then(e=>{if(t.audio&&!e.getAudioTracks().length||t.video&&!e.getVideoTracks().length)throw e.getTracks().forEach(e=>{e.stop()}),new DOMException(``,`NotFoundError`);return e},e=>Promise.reject(a(e))))}}}function cN(e){e.MediaStream=e.MediaStream||e.webkitMediaStream}function lN(e,t){if(!(t.version>102)){if(typeof e==`object`&&e.RTCPeerConnection&&!(`ontrack`in e.RTCPeerConnection.prototype)){Object.defineProperty(e.RTCPeerConnection.prototype,"ontrack",{get(){return this._ontrack},set(e){this._ontrack&&this.removeEventListener(`track`,this._ontrack),this.addEventListener(`track`,this._ontrack=e)},enumerable:!0,configurable:!0});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){return this._ontrackpoly||(this._ontrackpoly=t=>{t.stream.addEventListener(`addtrack`,n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.track.id):{track:n.track};let i=new Event(`track`);i.track=n.track,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)}),t.stream.getTracks().forEach(n=>{let r;r=e.RTCPeerConnection.prototype.getReceivers?this.getReceivers().find(e=>e.track&&e.track.id===n.id):{track:n};let i=new Event(`track`);i.track=n,i.receiver=r,i.transceiver={receiver:r},i.streams=[t.stream],this.dispatchEvent(i)})},this.addEventListener(`addstream`,this._ontrackpoly)),t.apply(this,arguments)}}else XM(e,`track`,e=>(e.transceiver||Object.defineProperty(e,"transceiver",{value:{receiver:e.receiver}}),e))}}function uN(e){if(typeof e==`object`&&e.RTCPeerConnection&&!(`getSenders`in e.RTCPeerConnection.prototype)&&`createDTMFSender`in e.RTCPeerConnection.prototype){let t=function(e,t){return{track:t,get dtmf(){return this._dtmf===void 0&&(this._dtmf=t.kind===`audio`?e.createDTMFSender(t):null),this._dtmf},_pc:e}};if(!e.RTCPeerConnection.prototype.getSenders){e.RTCPeerConnection.prototype.getSenders=function(){return this._senders=this._senders||[],this._senders.slice()};let n=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,r){let i=n.apply(this,arguments);return i||(i=t(this,e),this._senders.push(i)),i};let r=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){r.apply(this,arguments);let t=this._senders.indexOf(e);t!==-1&&this._senders.splice(t,1)}}let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._senders=this._senders||[],n.apply(this,[e]),e.getTracks().forEach(e=>{this._senders.push(t(this,e))})};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._senders=this._senders||[],r.apply(this,[e]),e.getTracks().forEach(e=>{let t=this._senders.find(t=>t.track===e);t&&this._senders.splice(this._senders.indexOf(t),1)})}}else if(typeof e==`object`&&e.RTCPeerConnection&&`getSenders`in e.RTCPeerConnection.prototype&&`createDTMFSender`in e.RTCPeerConnection.prototype&&e.RTCRtpSender&&!(`dtmf`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e},Object.defineProperty(e.RTCRtpSender.prototype,"dtmf",{get(){return this._dtmf===void 0&&(this._dtmf=this.track.kind===`audio`?this._pc.createDTMFSender(this.track):null),this._dtmf}})}}function dN(e,t){if(t.version>=67||!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender&&e.RTCRtpReceiver))return;if(!(`getStats`in e.RTCRtpSender.prototype)){let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>aN(t,e.track,!0))}}if(!(`getStats`in e.RTCRtpReceiver.prototype)){let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),XM(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){let e=this;return this._pc.getStats().then(t=>aN(t,e.track,!1))}}if(!(`getStats`in e.RTCRtpSender.prototype&&`getStats`in e.RTCRtpReceiver.prototype))return;let n=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){if(arguments.length>0&&arguments[0]instanceof e.MediaStreamTrack){let e=arguments[0],t,n,r;return this.getSenders().forEach(n=>{n.track===e&&(t?r=!0:t=n)}),this.getReceivers().forEach(t=>(t.track===e&&(n?r=!0:n=t),t.track===e)),r||t&&n?Promise.reject(new DOMException(`There are more than one sender or receiver for the track.`,`InvalidAccessError`)):t?t.getStats():n?n.getStats():Promise.reject(new DOMException(`There is no sender or receiver for the track.`,`InvalidAccessError`))}return n.apply(this,arguments)}}function fN(e){e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},Object.keys(this._shimmedLocalStreams).map(e=>this._shimmedLocalStreams[e][0])};let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addTrack=function(e,n){if(!n)return t.apply(this,arguments);this._shimmedLocalStreams=this._shimmedLocalStreams||{};let r=t.apply(this,arguments);return this._shimmedLocalStreams[n.id]?this._shimmedLocalStreams[n.id].indexOf(r)===-1&&this._shimmedLocalStreams[n.id].push(r):this._shimmedLocalStreams[n.id]=[n,r],r};let n=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(e){this._shimmedLocalStreams=this._shimmedLocalStreams||{},e.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)});let t=this.getSenders();n.apply(this,arguments);let r=this.getSenders().filter(e=>t.indexOf(e)===-1);this._shimmedLocalStreams[e.id]=[e].concat(r)};let r=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},delete this._shimmedLocalStreams[e.id],r.apply(this,arguments)};let i=e.RTCPeerConnection.prototype.removeTrack;e.RTCPeerConnection.prototype.removeTrack=function(e){return this._shimmedLocalStreams=this._shimmedLocalStreams||{},e&&Object.keys(this._shimmedLocalStreams).forEach(t=>{let n=this._shimmedLocalStreams[t].indexOf(e);n!==-1&&this._shimmedLocalStreams[t].splice(n,1),this._shimmedLocalStreams[t].length===1&&delete this._shimmedLocalStreams[t]}),i.apply(this,arguments)}}function pN(e,t){if(!e.RTCPeerConnection)return;if(e.RTCPeerConnection.prototype.addTrack&&t.version>=65)return fN(e);let n=e.RTCPeerConnection.prototype.getLocalStreams;e.RTCPeerConnection.prototype.getLocalStreams=function(){let e=n.apply(this);return this._reverseStreams=this._reverseStreams||{},e.map(e=>this._reverseStreams[e.id])};let r=e.RTCPeerConnection.prototype.addStream;e.RTCPeerConnection.prototype.addStream=function(t){if(this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},t.getTracks().forEach(e=>{if(this.getSenders().find(t=>t.track===e))throw new DOMException(`Track already exists.`,`InvalidAccessError`)}),!this._reverseStreams[t.id]){let n=new e.MediaStream(t.getTracks());this._streams[t.id]=n,this._reverseStreams[n.id]=t,t=n}r.apply(this,[t])};let i=e.RTCPeerConnection.prototype.removeStream;e.RTCPeerConnection.prototype.removeStream=function(e){this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{},i.apply(this,[this._streams[e.id]||e]),delete this._reverseStreams[this._streams[e.id]?this._streams[e.id].id:e.id],delete this._streams[e.id]},e.RTCPeerConnection.prototype.addTrack=function(t,n){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);let r=[].slice.call(arguments,1);if(r.length!==1||!r[0].getTracks().find(e=>e===t))throw new DOMException(`The adapter.js addTrack polyfill only supports a single stream which is associated with the specified track.`,`NotSupportedError`);if(this.getSenders().find(e=>e.track===t))throw new DOMException(`Track already exists.`,`InvalidAccessError`);this._streams=this._streams||{},this._reverseStreams=this._reverseStreams||{};let i=this._streams[n.id];if(i)i.addTrack(t),Promise.resolve().then(()=>{this.dispatchEvent(new Event(`negotiationneeded`))});else{let r=new e.MediaStream([t]);this._streams[n.id]=r,this._reverseStreams[r.id]=n,this.addStream(r)}return this.getSenders().find(e=>e.track===t)};function a(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(i.id,`g`),r.id)}),new RTCSessionDescription({type:t.type,sdp:n})}function o(e,t){let n=t.sdp;return Object.keys(e._reverseStreams||[]).forEach(t=>{let r=e._reverseStreams[t],i=e._streams[r.id];n=n.replace(new RegExp(r.id,`g`),i.id)}),new RTCSessionDescription({type:t.type,sdp:n})}[`createOffer`,`createAnswer`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){let e=arguments;return arguments.length&&typeof arguments[0]==`function`?n.apply(this,[t=>{let n=a(this,t);e[0].apply(null,[n])},t=>{e[1]&&e[1].apply(null,t)},arguments[2]]):n.apply(this,arguments).then(e=>a(this,e))}};e.RTCPeerConnection.prototype[t]=r[t]});let s=e.RTCPeerConnection.prototype.setLocalDescription;e.RTCPeerConnection.prototype.setLocalDescription=function(){return!arguments.length||!arguments[0].type||(arguments[0]=o(this,arguments[0])),s.apply(this,arguments)};let c=Object.getOwnPropertyDescriptor(e.RTCPeerConnection.prototype,`localDescription`);Object.defineProperty(e.RTCPeerConnection.prototype,"localDescription",{get(){let e=c.get.apply(this);return e.type===``?e:a(this,e)}}),e.RTCPeerConnection.prototype.removeTrack=function(e){if(this.signalingState===`closed`)throw new DOMException(`The RTCPeerConnection's signalingState is 'closed'.`,`InvalidStateError`);if(!e._pc)throw new DOMException(`Argument 1 of RTCPeerConnection.removeTrack does not implement interface RTCRtpSender.`,`TypeError`);if(e._pc!==this)throw new DOMException(`Sender was not created by this connection.`,`InvalidAccessError`);this._streams=this._streams||{};let t;Object.keys(this._streams).forEach(n=>{this._streams[n].getTracks().find(t=>e.track===t)&&(t=this._streams[n])}),t&&(t.getTracks().length===1?this.removeStream(this._reverseStreams[t.id]):t.removeTrack(e.track),this.dispatchEvent(new Event(`negotiationneeded`)))}}function mN(e,t){!e.RTCPeerConnection&&e.webkitRTCPeerConnection&&(e.RTCPeerConnection=e.webkitRTCPeerConnection),e.RTCPeerConnection&&t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]})}function hN(e,t){t.version>102||XM(e,`negotiationneeded`,e=>{let n=e.target;if(!((t.version<72||n.getConfiguration&&n.getConfiguration().sdpSemantics===`plan-b`)&&n.signalingState!==`stable`))return e})}var gN=Object.freeze({__proto__:null,fixNegotiationNeeded:hN,shimAddTrackRemoveTrack:pN,shimAddTrackRemoveTrackWithNative:fN,shimGetSendersWithDtmf:uN,shimGetUserMedia:sN,shimMediaStream:cN,shimOnTrack:lN,shimPeerConnection:mN,shimSenderReceiverGetStats:dN});function _N(e,t){let n=e&&e.navigator;if(!n.mediaDevices)return;let r=e&&e.MediaStreamTrack;if(n.getUserMedia=function(e,t,r){eN(`navigator.getUserMedia`,`navigator.mediaDevices.getUserMedia`),n.mediaDevices.getUserMedia(e).then(t,r)},!(t.version>55&&`autoGainControl`in n.mediaDevices.getSupportedConstraints())){let e=function(e,t,n){t in e&&!(n in e)&&(e[n]=e[t],delete e[t])},t=n.mediaDevices.getUserMedia.bind(n.mediaDevices);if(n.mediaDevices.getUserMedia=function(n){return typeof n==`object`&&typeof n.audio==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n.audio,`autoGainControl`,`mozAutoGainControl`),e(n.audio,`noiseSuppression`,`mozNoiseSuppression`)),t(n)},r&&r.prototype.getSettings){let t=r.prototype.getSettings;r.prototype.getSettings=function(){let n=t.apply(this,arguments);return e(n,`mozAutoGainControl`,`autoGainControl`),e(n,`mozNoiseSuppression`,`noiseSuppression`),n}}if(r&&r.prototype.applyConstraints){let t=r.prototype.applyConstraints;r.prototype.applyConstraints=function(n){return this.kind===`audio`&&typeof n==`object`&&(n=JSON.parse(JSON.stringify(n)),e(n,`autoGainControl`,`mozAutoGainControl`),e(n,`noiseSuppression`,`mozNoiseSuppression`)),t.apply(this,[n])}}}}function vN(e,t){e.navigator.mediaDevices&&(e.navigator.mediaDevices&&`getDisplayMedia`in e.navigator.mediaDevices||(e.navigator.mediaDevices.getDisplayMedia=function(n){if(!(n&&n.video)){let e=new DOMException(`getDisplayMedia without video constraints is undefined`);return e.name=`NotFoundError`,e.code=8,Promise.reject(e)}return n.video===!0?n.video={mediaSource:t}:n.video.mediaSource=t,e.navigator.mediaDevices.getUserMedia(n)}))}function yN(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function bN(e,t){typeof e==`object`&&(e.RTCPeerConnection||e.mozRTCPeerConnection)&&(!e.RTCPeerConnection&&e.mozRTCPeerConnection&&(e.RTCPeerConnection=e.mozRTCPeerConnection),t.version<53&&[`setLocalDescription`,`setRemoteDescription`,`addIceCandidate`].forEach(function(t){let n=e.RTCPeerConnection.prototype[t],r={[t](){return arguments[0]=new(t===`addIceCandidate`?e.RTCIceCandidate:e.RTCSessionDescription)(arguments[0]),n.apply(this,arguments)}};e.RTCPeerConnection.prototype[t]=r[t]}))}function xN(e,t){if(typeof e!=`object`||!(e.RTCPeerConnection||e.mozRTCPeerConnection)||t.version>=151)return;let n={inboundrtp:`inbound-rtp`,outboundrtp:`outbound-rtp`,candidatepair:`candidate-pair`,localcandidate:`local-candidate`,remotecandidate:`remote-candidate`},r=e.RTCPeerConnection.prototype.getStats;e.RTCPeerConnection.prototype.getStats=function(){let e=Array.prototype.slice.call(arguments),i=e[0],a=e[1],o=e[2];return this.signalingState===`closed`?Promise.resolve(new Map):r.apply(this,[i||null]).then(e=>{if(t.version<53&&!a)try{e.forEach(e=>{e.type=n[e.type]||e.type})}catch(t){if(t.name!==`TypeError`)throw t;e.forEach((t,r)=>{e.set(r,Object.assign({},t,{type:n[t.type]||t.type}))})}return e}).then(a,o)}}function SN(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpSender.prototype)return;let t=e.RTCPeerConnection.prototype.getSenders;t&&(e.RTCPeerConnection.prototype.getSenders=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e});let n=e.RTCPeerConnection.prototype.addTrack;n&&(e.RTCPeerConnection.prototype.addTrack=function(){let e=n.apply(this,arguments);return e._pc=this,e}),e.RTCRtpSender.prototype.getStats=function(){return this.track?this._pc.getStats(this.track):Promise.resolve(new Map)}}function CN(e){if(!(typeof e==`object`&&e.RTCPeerConnection&&e.RTCRtpSender)||e.RTCRtpSender&&`getStats`in e.RTCRtpReceiver.prototype)return;let t=e.RTCPeerConnection.prototype.getReceivers;t&&(e.RTCPeerConnection.prototype.getReceivers=function(){let e=t.apply(this,[]);return e.forEach(e=>e._pc=this),e}),XM(e,`track`,e=>(e.receiver._pc=e.srcElement,e)),e.RTCRtpReceiver.prototype.getStats=function(){return this._pc.getStats(this.track)}}function wN(e){!e.RTCPeerConnection||`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){eN(`removeStream`,`removeTrack`),this.getSenders().forEach(t=>{t.track&&e.getTracks().includes(t.track)&&this.removeTrack(t)})})}function TN(e){e.DataChannel&&!e.RTCDataChannel&&(e.RTCDataChannel=e.DataChannel)}function EN(e,t){if(!(typeof e==`object`&&e.RTCPeerConnection)||t.version>=110)return;let n=e.RTCPeerConnection.prototype.addTransceiver;n&&(e.RTCPeerConnection.prototype.addTransceiver=function(){this.setParametersPromises=[];let e=arguments[1]&&arguments[1].sendEncodings;e===void 0&&(e=[]),e=[...e];let t=e.length>0;t&&e.forEach(e=>{if(`rid`in e&&!/^[a-z0-9]{0,16}$/i.test(e.rid))throw TypeError(`Invalid RID value provided.`);if(`scaleResolutionDownBy`in e&&!(parseFloat(e.scaleResolutionDownBy)>=1))throw RangeError(`scale_resolution_down_by must be >= 1.0`);if(`maxFramerate`in e&&!(parseFloat(e.maxFramerate)>=0))throw RangeError(`max_framerate must be >= 0.0`)});let r=n.apply(this,arguments);if(t){let t=r.sender,n=t.getParameters();(!(`encodings`in n)||n.encodings.length===1&&Object.keys(n.encodings[0]).length===0)&&(n.encodings=e,t.sendEncodings=e,this.setParametersPromises.push(t.setParameters(n).then(()=>{delete t.sendEncodings}).catch(()=>{delete t.sendEncodings})))}return r})}function DN(e,t){if(!(typeof e==`object`&&e.RTCRtpSender)||t.version>=110)return;let n=e.RTCRtpSender.prototype.getParameters;n&&(e.RTCRtpSender.prototype.getParameters=function(){let e=n.apply(this,arguments);return`encodings`in e||(e.encodings=[].concat(this.sendEncodings||[{}])),e})}function ON(e,t){if(!(typeof e==`object`&&e.RTCPeerConnection)||t.version>=110)return;let n=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}function kN(e,t){if(!(typeof e==`object`&&e.RTCPeerConnection)||t.version>=110)return;let n=e.RTCPeerConnection.prototype.createAnswer;e.RTCPeerConnection.prototype.createAnswer=function(){return this.setParametersPromises&&this.setParametersPromises.length?Promise.all(this.setParametersPromises).then(()=>n.apply(this,arguments)).finally(()=>{this.setParametersPromises=[]}):n.apply(this,arguments)}}var AN=Object.freeze({__proto__:null,shimAddTransceiver:EN,shimCreateAnswer:kN,shimCreateOffer:ON,shimGetDisplayMedia:vN,shimGetParameters:DN,shimGetStats:xN,shimGetUserMedia:_N,shimOnTrack:yN,shimPeerConnection:bN,shimRTCDataChannel:TN,shimReceiverGetStats:CN,shimRemoveStream:wN,shimSenderGetStats:SN});function jN(e){if(typeof e==`object`&&e.RTCPeerConnection){if(`getLocalStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getLocalStreams=function(){return this._localStreams||=[],this._localStreams}),!(`addStream`in e.RTCPeerConnection.prototype)){let t=e.RTCPeerConnection.prototype.addTrack;e.RTCPeerConnection.prototype.addStream=function(e){this._localStreams||=[],this._localStreams.includes(e)||this._localStreams.push(e),e.getAudioTracks().forEach(n=>t.call(this,n,e)),e.getVideoTracks().forEach(n=>t.call(this,n,e))},e.RTCPeerConnection.prototype.addTrack=function(e){var n=[...arguments].slice(1);return n&&n.forEach(e=>{this._localStreams?this._localStreams.includes(e)||this._localStreams.push(e):this._localStreams=[e]}),t.apply(this,arguments)}}`removeStream`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.removeStream=function(e){this._localStreams||=[];let t=this._localStreams.indexOf(e);if(t===-1)return;this._localStreams.splice(t,1);let n=e.getTracks();this.getSenders().forEach(e=>{n.includes(e.track)&&this.removeTrack(e)})})}}function MN(e){if(typeof e==`object`&&e.RTCPeerConnection&&(`getRemoteStreams`in e.RTCPeerConnection.prototype||(e.RTCPeerConnection.prototype.getRemoteStreams=function(){return this._remoteStreams?this._remoteStreams:[]}),!(`onaddstream`in e.RTCPeerConnection.prototype))){Object.defineProperty(e.RTCPeerConnection.prototype,"onaddstream",{get(){return this._onaddstream},set(e){this._onaddstream&&(this.removeEventListener(`addstream`,this._onaddstream),this.removeEventListener(`track`,this._onaddstreampoly)),this.addEventListener(`addstream`,this._onaddstream=e),this.addEventListener(`track`,this._onaddstreampoly=e=>{e.streams.forEach(e=>{if(this._remoteStreams||=[],this._remoteStreams.includes(e))return;this._remoteStreams.push(e);let t=new Event(`addstream`);t.stream=e,this.dispatchEvent(t)})})}});let t=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){let e=this;return this._onaddstreampoly||this.addEventListener(`track`,this._onaddstreampoly=function(t){t.streams.forEach(t=>{if(e._remoteStreams||=[],e._remoteStreams.indexOf(t)>=0)return;e._remoteStreams.push(t);let n=new Event(`addstream`);n.stream=t,e.dispatchEvent(n)})}),t.apply(e,arguments)}}}function NN(e){if(typeof e!=`object`||!e.RTCPeerConnection)return;let t=e.RTCPeerConnection.prototype,n=t.createOffer,r=t.createAnswer,i=t.setLocalDescription,a=t.setRemoteDescription,o=t.addIceCandidate;t.createOffer=function(e,t){let r=arguments.length>=2?arguments[2]:arguments[0],i=n.apply(this,[r]);return t?(i.then(e,t),Promise.resolve()):i},t.createAnswer=function(e,t){let n=arguments.length>=2?arguments[2]:arguments[0],i=r.apply(this,[n]);return t?(i.then(e,t),Promise.resolve()):i};let s=function(e,t,n){let r=i.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r};t.setLocalDescription=s,s=function(e,t,n){let r=a.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.setRemoteDescription=s,s=function(e,t,n){let r=o.apply(this,[e]);return n?(r.then(t,n),Promise.resolve()):r},t.addIceCandidate=s}function PN(e){let t=e&&e.navigator;if(t.mediaDevices&&t.mediaDevices.getUserMedia){let e=t.mediaDevices,n=e.getUserMedia.bind(e);t.mediaDevices.getUserMedia=e=>n(FN(e))}!t.getUserMedia&&t.mediaDevices&&t.mediaDevices.getUserMedia&&(t.getUserMedia=function(e,n,r){t.mediaDevices.getUserMedia(e).then(n,r)}.bind(t))}function FN(e){return e&&e.video!==void 0?Object.assign({},e,{video:rN(e.video)}):e}function IN(e){if(!e.RTCPeerConnection)return;let t=e.RTCPeerConnection;e.RTCPeerConnection=function(e,n){if(e&&e.iceServers){let t=[];for(let n=0;n<e.iceServers.length;n++){let r=e.iceServers[n];r.urls===void 0&&r.url?(eN(`RTCIceServer.url`,`RTCIceServer.urls`),r=JSON.parse(JSON.stringify(r)),r.urls=r.url,delete r.url,t.push(r)):t.push(e.iceServers[n])}e.iceServers=t}return new t(e,n)},e.RTCPeerConnection.prototype=t.prototype,`generateCertificate`in t&&Object.defineProperty(e.RTCPeerConnection,"generateCertificate",{get(){return t.generateCertificate}})}function LN(e){typeof e==`object`&&e.RTCTrackEvent&&`receiver`in e.RTCTrackEvent.prototype&&!(`transceiver`in e.RTCTrackEvent.prototype)&&Object.defineProperty(e.RTCTrackEvent.prototype,"transceiver",{get(){return{receiver:this.receiver}}})}function RN(e){let t=e.RTCPeerConnection.prototype.createOffer;e.RTCPeerConnection.prototype.createOffer=function(e){if(e){e.offerToReceiveAudio!==void 0&&(e.offerToReceiveAudio=!!e.offerToReceiveAudio);let t=this.getTransceivers().find(e=>e.receiver.track.kind===`audio`);e.offerToReceiveAudio===!1&&t?t.direction===`sendrecv`?t.setDirection?t.setDirection(`sendonly`):t.direction=`sendonly`:t.direction===`recvonly`&&(t.setDirection?t.setDirection(`inactive`):t.direction=`inactive`):e.offerToReceiveAudio===!0&&!t&&this.addTransceiver(`audio`,{direction:`recvonly`}),e.offerToReceiveVideo!==void 0&&(e.offerToReceiveVideo=!!e.offerToReceiveVideo);let n=this.getTransceivers().find(e=>e.receiver.track.kind===`video`);e.offerToReceiveVideo===!1&&n?n.direction===`sendrecv`?n.setDirection?n.setDirection(`sendonly`):n.direction=`sendonly`:n.direction===`recvonly`&&(n.setDirection?n.setDirection(`inactive`):n.direction=`inactive`):e.offerToReceiveVideo===!0&&!n&&this.addTransceiver(`video`,{direction:`recvonly`})}return t.apply(this,arguments)}}function zN(e){typeof e!=`object`||e.AudioContext||(e.AudioContext=e.webkitAudioContext)}var BN=Object.freeze({__proto__:null,shimAudioContext:zN,shimCallbacksAPI:NN,shimConstraints:FN,shimCreateOfferLegacy:RN,shimGetUserMedia:PN,shimLocalStreamsAPI:jN,shimRTCIceServerUrls:IN,shimRemoteStreamsAPI:MN,shimTrackEventTransceiver:LN}),VN={exports:{}},HN;function UN(){return HN?VN.exports:(HN=1,(function(e){let t={};t.generateIdentifier=function(){return Math.random().toString(36).substring(2,12)},t.localCName=t.generateIdentifier(),t.splitLines=function(e){return e.trim().split(`
69
+ `).map(e=>e.trim())},t.splitSections=function(e){return e.split(`
70
+ m=`).map((e,t)=>(t>0?`m=`+e:e).trim()+`\r
71
+ `)},t.getDescription=function(e){let n=t.splitSections(e);return n&&n[0]},t.getMediaSections=function(e){let n=t.splitSections(e);return n.shift(),n},t.matchPrefix=function(e,n){return t.splitLines(e).filter(e=>e.indexOf(n)===0)},t.parseCandidate=function(e){let t;t=e.indexOf(`a=candidate:`)===0?e.substring(12).split(` `):e.substring(10).split(` `);let n={foundation:t[0],component:{1:`rtp`,2:`rtcp`}[t[1]]||t[1],protocol:t[2].toLowerCase(),priority:parseInt(t[3],10),ip:t[4],address:t[4],port:parseInt(t[5],10),type:t[7]};for(let e=8;e<t.length;e+=2)switch(t[e]){case`raddr`:n.relatedAddress=t[e+1];break;case`rport`:n.relatedPort=parseInt(t[e+1],10);break;case`tcptype`:n.tcpType=t[e+1];break;case`ufrag`:n.ufrag=t[e+1],n.usernameFragment=t[e+1];break;default:n[t[e]]===void 0&&(n[t[e]]=t[e+1])}return n},t.writeCandidate=function(e){let t=[];t.push(e.foundation);let n=e.component;n===`rtp`?t.push(1):n===`rtcp`?t.push(2):t.push(n),t.push(e.protocol.toUpperCase()),t.push(e.priority),t.push(e.address||e.ip),t.push(e.port);let r=e.type;return t.push(`typ`),t.push(r),r!==`host`&&e.relatedAddress&&e.relatedPort!==void 0&&(t.push(`raddr`),t.push(e.relatedAddress),t.push(`rport`),t.push(e.relatedPort)),e.tcpType&&e.protocol.toLowerCase()===`tcp`&&(t.push(`tcptype`),t.push(e.tcpType)),(e.usernameFragment||e.ufrag)&&(t.push(`ufrag`),t.push(e.usernameFragment||e.ufrag)),`candidate:`+t.join(` `)},t.parseIceOptions=function(e){return e.substring(14).split(` `)},t.parseRtpMap=function(e){let t=e.substring(9).split(` `),n={payloadType:parseInt(t.shift(),10)};return t=t[0].split(`/`),n.name=t[0],n.clockRate=parseInt(t[1],10),n.channels=t.length===3?parseInt(t[2],10):1,n.numChannels=n.channels,n},t.writeRtpMap=function(e){let t=e.payloadType;e.preferredPayloadType!==void 0&&(t=e.preferredPayloadType);let n=e.channels||e.numChannels||1;return`a=rtpmap:`+t+` `+e.name+`/`+e.clockRate+(n===1?``:`/`+n)+`\r
72
+ `},t.parseExtmap=function(e){let t=e.substring(9).split(` `);return{id:parseInt(t[0],10),direction:t[0].indexOf(`/`)>0?t[0].split(`/`)[1]:`sendrecv`,uri:t[1],attributes:t.slice(2).join(` `)}},t.writeExtmap=function(e){return`a=extmap:`+(e.id||e.preferredId)+(e.direction&&e.direction!==`sendrecv`?`/`+e.direction:``)+` `+e.uri+(e.attributes?` `+e.attributes:``)+`\r
73
+ `},t.parseFmtp=function(e){let t={},n,r=e.substring(e.indexOf(` `)+1).split(`;`);for(let e=0;e<r.length;e++)n=r[e].trim().split(`=`),t[n[0].trim()]=n[1];return t},t.writeFmtp=function(e){let t=``,n=e.payloadType;if(e.preferredPayloadType!==void 0&&(n=e.preferredPayloadType),e.parameters&&Object.keys(e.parameters).length){let r=[];Object.keys(e.parameters).forEach(t=>{e.parameters[t]===void 0?r.push(t):r.push(t+`=`+e.parameters[t])}),t+=`a=fmtp:`+n+` `+r.join(`;`)+`\r
74
+ `}return t},t.parseRtcpFb=function(e){let t=e.substring(e.indexOf(` `)+1).split(` `);return{type:t.shift(),parameter:t.join(` `)}},t.writeRtcpFb=function(e){let t=``,n=e.payloadType;return e.preferredPayloadType!==void 0&&(n=e.preferredPayloadType),e.rtcpFeedback&&e.rtcpFeedback.length&&e.rtcpFeedback.forEach(e=>{t+=`a=rtcp-fb:`+n+` `+e.type+(e.parameter&&e.parameter.length?` `+e.parameter:``)+`\r
75
+ `}),t},t.parseSsrcMedia=function(e){let t=e.indexOf(` `),n={ssrc:parseInt(e.substring(7,t),10)},r=e.indexOf(`:`,t);return r>-1?(n.attribute=e.substring(t+1,r),n.value=e.substring(r+1)):n.attribute=e.substring(t+1),n},t.parseSsrcGroup=function(e){let t=e.substring(13).split(` `);return{semantics:t.shift(),ssrcs:t.map(e=>parseInt(e,10))}},t.getMid=function(e){let n=t.matchPrefix(e,`a=mid:`)[0];if(n)return n.substring(6)},t.parseFingerprint=function(e){let t=e.substring(14).split(` `);return{algorithm:t[0].toLowerCase(),value:t[1].toUpperCase()}},t.getDtlsParameters=function(e,n){return{role:`auto`,fingerprints:t.matchPrefix(e+n,`a=fingerprint:`).map(t.parseFingerprint)}},t.writeDtlsParameters=function(e,t){let n=`a=setup:`+t+`\r
76
+ `;return e.fingerprints.forEach(e=>{n+=`a=fingerprint:`+e.algorithm+` `+e.value+`\r
77
+ `}),n},t.parseCryptoLine=function(e){let t=e.substring(9).split(` `);return{tag:parseInt(t[0],10),cryptoSuite:t[1],keyParams:t[2],sessionParams:t.slice(3)}},t.writeCryptoLine=function(e){return`a=crypto:`+e.tag+` `+e.cryptoSuite+` `+(typeof e.keyParams==`object`?t.writeCryptoKeyParams(e.keyParams):e.keyParams)+(e.sessionParams?` `+e.sessionParams.join(` `):``)+`\r
78
+ `},t.parseCryptoKeyParams=function(e){if(e.indexOf(`inline:`)!==0)return null;let t=e.substring(7).split(`|`);return{keyMethod:`inline`,keySalt:t[0],lifeTime:t[1],mkiValue:t[2]?t[2].split(`:`)[0]:void 0,mkiLength:t[2]?t[2].split(`:`)[1]:void 0}},t.writeCryptoKeyParams=function(e){return e.keyMethod+`:`+e.keySalt+(e.lifeTime?`|`+e.lifeTime:``)+(e.mkiValue&&e.mkiLength?`|`+e.mkiValue+`:`+e.mkiLength:``)},t.getCryptoParameters=function(e,n){return t.matchPrefix(e+n,`a=crypto:`).map(t.parseCryptoLine)},t.getIceParameters=function(e,n){let r=t.matchPrefix(e+n,`a=ice-ufrag:`)[0],i=t.matchPrefix(e+n,`a=ice-pwd:`)[0];return r&&i?{usernameFragment:r.substring(12),password:i.substring(10)}:null},t.writeIceParameters=function(e){let t=`a=ice-ufrag:`+e.usernameFragment+`\r
79
+ a=ice-pwd:`+e.password+`\r
80
+ `;return e.iceLite&&(t+=`a=ice-lite\r
81
+ `),t},t.parseRtpParameters=function(e){let n={codecs:[],headerExtensions:[],fecMechanisms:[],rtcp:[]},r=t.splitLines(e)[0].split(` `);n.profile=r[2];for(let i=3;i<r.length;i++){let a=r[i],o=t.matchPrefix(e,`a=rtpmap:`+a+` `)[0];if(o){let r=t.parseRtpMap(o),i=t.matchPrefix(e,`a=fmtp:`+a+` `);switch(r.parameters=i.length?t.parseFmtp(i[0]):{},r.rtcpFeedback=t.matchPrefix(e,`a=rtcp-fb:`+a+` `).map(t.parseRtcpFb),n.codecs.push(r),r.name.toUpperCase()){case`RED`:case`ULPFEC`:n.fecMechanisms.push(r.name.toUpperCase())}}}t.matchPrefix(e,`a=extmap:`).forEach(e=>{n.headerExtensions.push(t.parseExtmap(e))});let i=t.matchPrefix(e,`a=rtcp-fb:* `).map(t.parseRtcpFb);return n.codecs.forEach(e=>{i.forEach(t=>{e.rtcpFeedback.find(e=>e.type===t.type&&e.parameter===t.parameter)||e.rtcpFeedback.push(t)})}),n},t.writeRtpDescription=function(e,n){let r=``;r+=`m=`+e+` `,r+=n.codecs.length>0?`9`:`0`,r+=` `+(n.profile||`UDP/TLS/RTP/SAVPF`)+` `,r+=n.codecs.map(e=>e.preferredPayloadType===void 0?e.payloadType:e.preferredPayloadType).join(` `)+`\r
82
+ `,r+=`c=IN IP4 0.0.0.0\r
83
+ `,r+=`a=rtcp:9 IN IP4 0.0.0.0\r
84
+ `,n.codecs.forEach(e=>{r+=t.writeRtpMap(e),r+=t.writeFmtp(e),r+=t.writeRtcpFb(e)});let i=0;return n.codecs.forEach(e=>{e.maxptime>i&&(i=e.maxptime)}),i>0&&(r+=`a=maxptime:`+i+`\r
85
+ `),n.headerExtensions&&n.headerExtensions.forEach(e=>{r+=t.writeExtmap(e)}),r},t.parseRtpEncodingParameters=function(e){let n=[],r=t.parseRtpParameters(e),i=r.fecMechanisms.indexOf(`RED`)!==-1,a=r.fecMechanisms.indexOf(`ULPFEC`)!==-1,o=t.matchPrefix(e,`a=ssrc:`).map(e=>t.parseSsrcMedia(e)).filter(e=>e.attribute===`cname`),s=o.length>0&&o[0].ssrc,c,l=t.matchPrefix(e,`a=ssrc-group:FID`).map(e=>e.substring(17).split(` `).map(e=>parseInt(e,10)));l.length>0&&l[0].length>1&&l[0][0]===s&&(c=l[0][1]),r.codecs.forEach(e=>{if(e.name.toUpperCase()===`RTX`&&e.parameters.apt){let t={ssrc:s,codecPayloadType:parseInt(e.parameters.apt,10)};s&&c&&(t.rtx={ssrc:c}),n.push(t),i&&(t=JSON.parse(JSON.stringify(t)),t.fec={ssrc:s,mechanism:a?`red+ulpfec`:`red`},n.push(t))}}),n.length===0&&s&&n.push({ssrc:s});let u=t.matchPrefix(e,`b=`);return u.length&&(u=u[0].indexOf(`b=TIAS:`)===0?parseInt(u[0].substring(7),10):u[0].indexOf(`b=AS:`)===0?parseInt(u[0].substring(5),10)*1e3*.95-16e3:void 0,n.forEach(e=>{e.maxBitrate=u})),n},t.parseRtcpParameters=function(e){let n={},r=t.matchPrefix(e,`a=ssrc:`).map(e=>t.parseSsrcMedia(e)).filter(e=>e.attribute===`cname`)[0];r&&(n.cname=r.value,n.ssrc=r.ssrc);let i=t.matchPrefix(e,`a=rtcp-rsize`);return n.reducedSize=i.length>0,n.compound=i.length===0,n.mux=t.matchPrefix(e,`a=rtcp-mux`).length>0,n},t.writeRtcpParameters=function(e){let t=``;return e.reducedSize&&(t+=`a=rtcp-rsize\r
86
+ `),e.mux&&(t+=`a=rtcp-mux\r
87
+ `),e.ssrc!==void 0&&e.cname&&(t+=`a=ssrc:`+e.ssrc+` cname:`+e.cname+`\r
88
+ `),t},t.parseMsid=function(e){let n,r=t.matchPrefix(e,`a=msid:`);if(r.length===1)return n=r[0].substring(7).split(` `),{stream:n[0],track:n[1]};let i=t.matchPrefix(e,`a=ssrc:`).map(e=>t.parseSsrcMedia(e)).filter(e=>e.attribute===`msid`);if(i.length>0)return n=i[0].value.split(` `),{stream:n[0],track:n[1]}},t.parseSctpDescription=function(e){let n=t.parseMLine(e),r=t.matchPrefix(e,`a=max-message-size:`),i;r.length>0&&(i=parseInt(r[0].substring(19),10)),isNaN(i)&&(i=65536);let a=t.matchPrefix(e,`a=sctp-port:`);if(a.length>0)return{port:parseInt(a[0].substring(12),10),protocol:n.fmt,maxMessageSize:i};let o=t.matchPrefix(e,`a=sctpmap:`);if(o.length>0){let e=o[0].substring(10).split(` `);return{port:parseInt(e[0],10),protocol:e[1],maxMessageSize:i}}},t.writeSctpDescription=function(e,t){let n=[];return n=e.protocol===`DTLS/SCTP`?[`m=`+e.kind+` 9 `+e.protocol+` `+t.port+`\r
89
+ `,`c=IN IP4 0.0.0.0\r
90
+ `,`a=sctpmap:`+t.port+` `+t.protocol+` 65535\r
91
+ `]:[`m=`+e.kind+` 9 `+e.protocol+` `+t.protocol+`\r
92
+ `,`c=IN IP4 0.0.0.0\r
93
+ `,`a=sctp-port:`+t.port+`\r
94
+ `],t.maxMessageSize!==void 0&&n.push(`a=max-message-size:`+t.maxMessageSize+`\r
95
+ `),n.join(``)},t.generateSessionId=function(){return Math.random().toString().substr(2,22)},t.writeSessionBoilerplate=function(e,n,r){let i,a=n===void 0?2:n;return i=e||t.generateSessionId(),`v=0\r
96
+ o=`+(r||`thisisadapterortc`)+` `+i+` `+a+` IN IP4 127.0.0.1\r
97
+ s=-\r
98
+ t=0 0\r
99
+ `},t.getDirection=function(e,n){let r=t.splitLines(e);for(let e=0;e<r.length;e++)switch(r[e]){case`a=sendrecv`:case`a=sendonly`:case`a=recvonly`:case`a=inactive`:return r[e].substring(2)}return n?t.getDirection(n):`sendrecv`},t.getKind=function(e){return t.splitLines(e)[0].split(` `)[0].substring(2)},t.isRejected=function(e){return e.split(` `,2)[1]===`0`},t.parseMLine=function(e){let n=t.splitLines(e)[0].substring(2).split(` `);return{kind:n[0],port:parseInt(n[1],10),protocol:n[2],fmt:n.slice(3).join(` `)}},t.parseOLine=function(e){let n=t.matchPrefix(e,`o=`)[0].substring(2).split(` `);return{username:n[0],sessionId:n[1],sessionVersion:parseInt(n[2],10),netType:n[3],addressType:n[4],address:n[5]}},t.isValidSDP=function(e){if(typeof e!=`string`||e.length===0)return!1;let n=t.splitLines(e);for(let e=0;e<n.length;e++)if(n[e].length<2||n[e].charAt(1)!==`=`)return!1;return!0},e.exports=t})(VN),VN.exports)}var WN=UN(),GN=yM(WN),KN=DD({__proto__:null,default:GN},[WN]);function qN(e){if(!e.RTCIceCandidate||e.RTCIceCandidate&&`foundation`in e.RTCIceCandidate.prototype)return;let t=e.RTCIceCandidate;e.RTCIceCandidate=function(e){if(typeof e==`object`&&e.candidate&&e.candidate.indexOf(`a=`)===0&&(e=JSON.parse(JSON.stringify(e)),e.candidate=e.candidate.substring(2)),e.candidate&&e.candidate.length){let n=new t(e),r=GN.parseCandidate(e.candidate);for(let e in r)e in n||Object.defineProperty(n,e,{value:r[e]});return n.toJSON=function(){return{candidate:n.candidate,sdpMid:n.sdpMid,sdpMLineIndex:n.sdpMLineIndex,usernameFragment:n.usernameFragment}},n}return new t(e)},e.RTCIceCandidate.prototype=t.prototype,XM(e,`icecandidate`,t=>(t.candidate&&Object.defineProperty(t,"candidate",{value:new e.RTCIceCandidate(t.candidate),writable:`false`}),t))}function JN(e){!e.RTCIceCandidate||e.RTCIceCandidate&&`relayProtocol`in e.RTCIceCandidate.prototype||XM(e,`icecandidate`,e=>{if(e.candidate){let t=GN.parseCandidate(e.candidate.candidate);t.type===`relay`&&(e.candidate.relayProtocol={0:`tls`,1:`tcp`,2:`udp`}[t.priority>>24])}return e})}function YN(e,t){if(!e.RTCPeerConnection||t.browser===`chrome`&&t.version>102||t.browser===`firefox`&&t.version>=113)return;`sctp`in e.RTCPeerConnection.prototype||Object.defineProperty(e.RTCPeerConnection.prototype,"sctp",{get(){return this._sctp===void 0?null:this._sctp}});let n=function(e){if(!e||!e.sdp)return!1;let t=GN.splitSections(e.sdp);return t.shift(),t.some(e=>{let t=GN.parseMLine(e);return t&&t.kind===`application`&&t.protocol.indexOf(`SCTP`)!==-1})},r=function(e){let t=e.sdp.match(/mozilla...THIS_IS_SDPARTA-(\d+)/);if(t===null||t.length<2)return-1;let n=parseInt(t[1],10);return n===n?n:-1},i=function(e){let n=65536;return t.browser===`firefox`&&(n=t.version<57?e===-1?16384:2147483637:t.version<60?t.version===57?65535:65536:2147483637),n},a=function(e,n){let r=65536;t.browser===`firefox`&&t.version===57&&(r=65535);let i=GN.matchPrefix(e.sdp,`a=max-message-size:`);return i.length>0?r=parseInt(i[0].substring(19),10):t.browser===`firefox`&&n!==-1&&(r=2147483637),r},o=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(){if(this._sctp=null,t.browser===`chrome`&&t.version>=76&&this.getConfiguration().sdpSemantics===`plan-b`&&Object.defineProperty(this,"sctp",{get(){return this._sctp===void 0?null:this._sctp},enumerable:!0,configurable:!0}),n(arguments[0])){let e=r(arguments[0]),t=i(e),n=a(arguments[0],e),o;o=t===0&&n===0?1/0:t===0||n===0?Math.max(t,n):Math.min(t,n);let s={};Object.defineProperty(s,"maxMessageSize",{get(){return o}}),this._sctp=s}return o.apply(this,arguments)}}function XN(e,t){if(!(e.RTCPeerConnection&&`createDataChannel`in e.RTCPeerConnection.prototype)||t.browser===`chrome`&&t.version>=149||t.browser===`firefox`&&t.version>60)return;function n(e,t){let n=e.send;e.send=function(){let r=arguments[0],i=r.length||r.size||r.byteLength;if(e.readyState===`open`&&t.sctp&&i>t.sctp.maxMessageSize)throw TypeError(`Message too large (can send a maximum of `+t.sctp.maxMessageSize+` bytes)`);return n.apply(e,arguments)}}let r=e.RTCPeerConnection.prototype.createDataChannel;e.RTCPeerConnection.prototype.createDataChannel=function(){let e=r.apply(this,arguments);return n(e,this),e},XM(e,`datachannel`,e=>(n(e.channel,e.target),e))}function ZN(e){if(!e.RTCPeerConnection||`connectionState`in e.RTCPeerConnection.prototype)return;let t=e.RTCPeerConnection.prototype;Object.defineProperty(t,"connectionState",{get(){return{completed:`connected`,checking:`connecting`}[this.iceConnectionState]||this.iceConnectionState},enumerable:!0,configurable:!0}),Object.defineProperty(t,"onconnectionstatechange",{get(){return this._onconnectionstatechange||null},set(e){this._onconnectionstatechange&&(this.removeEventListener(`connectionstatechange`,this._onconnectionstatechange),delete this._onconnectionstatechange),e&&this.addEventListener(`connectionstatechange`,this._onconnectionstatechange=e)},enumerable:!0,configurable:!0}),[`setLocalDescription`,`setRemoteDescription`].forEach(e=>{let n=t[e];t[e]=function(){return this._connectionstatechangepoly||(this._connectionstatechangepoly=e=>{let t=e.target;if(t._lastConnectionState!==t.connectionState){t._lastConnectionState=t.connectionState;let n=new Event(`connectionstatechange`,e);t.dispatchEvent(n)}return e},this.addEventListener(`iceconnectionstatechange`,this._connectionstatechangepoly)),n.apply(this,arguments)}})}function QN(e,t){if(!e.RTCPeerConnection||t.browser===`chrome`&&t.version>=71||t.browser===`safari`&&t._safariVersion>=13.1)return;let n=e.RTCPeerConnection.prototype.setRemoteDescription;e.RTCPeerConnection.prototype.setRemoteDescription=function(t){if(t&&t.sdp&&t.sdp.indexOf(`
100
+ a=extmap-allow-mixed`)!==-1){let n=t.sdp.split(`
101
+ `).filter(e=>e.trim()!==`a=extmap-allow-mixed`).join(`
102
+ `);e.RTCSessionDescription&&t instanceof e.RTCSessionDescription?arguments[0]=new e.RTCSessionDescription({type:t.type,sdp:n}):t.sdp=n}return n.apply(this,arguments)}}function $N(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.addIceCandidate;n&&n.length!==0&&(e.RTCPeerConnection.prototype.addIceCandidate=function(){return arguments[0]?(t.browser===`chrome`&&t.version<78||t.browser===`firefox`&&t.version<68||t.browser===`safari`)&&arguments[0]&&arguments[0].candidate===``?Promise.resolve():n.apply(this,arguments):(arguments[1]&&arguments[1].apply(null),Promise.resolve())})}function eP(e,t){if(!(e.RTCPeerConnection&&e.RTCPeerConnection.prototype))return;let n=e.RTCPeerConnection.prototype.setLocalDescription;n&&n.length!==0&&(e.RTCPeerConnection.prototype.setLocalDescription=function(){let e=arguments[0]||{};if(typeof e!=`object`||e.type&&e.sdp)return n.apply(this,arguments);if(e={type:e.type,sdp:e.sdp},!e.type)switch(this.signalingState){case`stable`:case`have-local-offer`:case`have-remote-pranswer`:e.type=`offer`;break;default:e.type=`answer`}return e.sdp||e.type!==`offer`&&e.type!==`answer`?n.apply(this,[e]):(e.type===`offer`?this.createOffer:this.createAnswer).apply(this).then(e=>n.apply(this,[e]))})}var tP=Object.freeze({__proto__:null,removeExtmapAllowMixed:QN,shimAddIceCandidateNullOrEmpty:$N,shimConnectionState:ZN,shimMaxMessageSize:YN,shimParameterlessSetLocalDescription:eP,shimRTCIceCandidate:qN,shimRTCIceCandidateRelayProtocol:JN,shimSendThrowTypeError:XN});function nP(){let e=(arguments.length>0&&arguments[0]!==void 0?arguments[0]:{}).window,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{shimChrome:!0,shimFirefox:!0,shimSafari:!0},n=$M,r=tN(e),i={browserDetails:r,commonShim:tP,extractVersion:YM,disableLog:ZM,disableWarnings:QM,sdp:KN};switch(r.browser){case`chrome`:if(!gN||!mN||!t.shimChrome)return n(`Chrome shim is not included in this adapter release.`),i;if(r.version===null)return n(`Chrome shim can not determine version, not shimming.`),i;n(`adapter.js shimming chrome.`),i.browserShim=gN,$N(e,r),eP(e),sN(e,r),cN(e),mN(e,r),lN(e,r),pN(e,r),uN(e),dN(e,r),hN(e,r),qN(e),JN(e),ZN(e),YN(e,r),XN(e,r),QN(e,r);break;case`firefox`:if(!AN||!bN||!t.shimFirefox)return n(`Firefox shim is not included in this adapter release.`),i;n(`adapter.js shimming firefox.`),i.browserShim=AN,$N(e,r),eP(e),_N(e,r),bN(e,r),xN(e,r),yN(e),wN(e),SN(e),CN(e),TN(e),EN(e,r),DN(e,r),ON(e,r),kN(e,r),qN(e),ZN(e),YN(e,r),XN(e,r);break;case`safari`:if(!BN||!t.shimSafari)return n(`Safari shim is not included in this adapter release.`),i;n(`adapter.js shimming safari.`),i.browserShim=BN,$N(e,r),eP(e),IN(e),RN(e),NN(e),jN(e),MN(e),LN(e),PN(e),zN(e),qN(e),JN(e),YN(e,r),XN(e,r),QN(e,r);break;default:n(`Unsupported browser!`)}return i}nP({window:typeof window>`u`?void 0:window});var rP,iP,aP=class extends (iP=Promise){constructor(e){super(e)}catch(e){return super.catch(e)}static reject(e){return super.reject(e)}static all(e){return super.all(e)}static race(e){return super.race(e)}};rP=aP,aP.resolve=e=>Reflect.get(iP,`resolve`,rP).call(rP,e);var oP=/version\/(\d+(\.?_?\d+)+)/i,sP;function cP(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;if(e===void 0&&typeof navigator>`u`)return;let n=(e??navigator.userAgent).toLowerCase();return(sP===void 0||t)&&(sP=lP.find(e=>e.test.test(n))?.describe(n)),sP}var lP=[{test:/firefox|iceweasel|fxios/i,describe(e){return{name:`Firefox`,version:uP(/(?:firefox|iceweasel|fxios)[\s/](\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`fxios`)?`iOS`:void 0,osVersion:dP(e)}}},{test:/chrom|crios|crmo/i,describe(e){return{name:`Chrome`,version:uP(/(?:chrome|chromium|crios|crmo)\/(\d+(\.?_?\d+)+)/i,e),os:e.toLowerCase().includes(`crios`)?`iOS`:void 0,osVersion:dP(e)}}},{test:/safari|applewebkit/i,describe(e){return{name:`Safari`,version:uP(oP,e),os:e.includes(`mobile/`)?`iOS`:`macOS`,osVersion:dP(e)}}}];function uP(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:1,r=t.match(e);return r&&r.length>=n&&r[n]||``}function dP(e){return e.includes(`mac os`)?uP(/\(.+?(\d+_\d+(:?_\d+)?)/,e,1).replace(/_/g,`.`):void 0}var fP=`2.22.3`,pP=class extends Error{constructor(e,t,n){super(t||`an error has occurred`),this.name=`LiveKitError`,this.code=e,n?.cause!==void 0&&(this.cause=n?.cause)}},mP=class extends pP{},hP;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.ServerUnreachable=1]=`ServerUnreachable`,e[e.InternalError=2]=`InternalError`,e[e.Cancelled=3]=`Cancelled`,e[e.LeaveRequest=4]=`LeaveRequest`,e[e.Timeout=5]=`Timeout`,e[e.WebSocket=6]=`WebSocket`,e[e.ServiceNotFound=7]=`ServiceNotFound`})(hP||={});var gP=class e extends mP{constructor(e,t,n,r){super(1,e),this.name=`ConnectionError`,this.status=n,this.reason=t,this.context=r,this.reasonName=hP[t]}static notAllowed(t,n,r){return new e(t,hP.NotAllowed,n,r)}static timeout(t){return new e(t,hP.Timeout)}static leaveRequest(t,n){return new e(t,hP.LeaveRequest,void 0,n)}static internal(t,n){return new e(t,hP.InternalError,void 0,n)}static cancelled(t){return new e(t,hP.Cancelled)}static serverUnreachable(t,n){return new e(t,hP.ServerUnreachable,n)}static websocket(t,n,r){return new e(t,hP.WebSocket,n,r)}static serviceNotFound(t,n){return new e(t,hP.ServiceNotFound,void 0,n)}},_P=class extends pP{constructor(e){super(21,e??`device is unsupported`),this.name=`DeviceUnsupportedError`}},vP=class extends pP{constructor(e){super(20,e??`track is invalid`),this.name=`TrackInvalidError`}},yP=class extends pP{constructor(e){super(10,e||`unsupported server`),this.name=`UnsupportedServer`}},bP=class extends pP{constructor(e){super(12,e||`unexpected connection state`),this.name=`UnexpectedConnectionState`}},xP=class extends pP{constructor(e){super(13,e||`unable to negotiate`),this.name=`NegotiationError`}},SP=class extends pP{constructor(e){super(14,e||`unable to publish data`),this.name=`PublishDataError`}},CP=class extends pP{constructor(e,t){super(15,e),this.name=`PublishTrackError`,this.status=t}},wP=class extends mP{constructor(e,t){super(15,e),this.name=`SignalRequestError`,this.reason=t,this.reasonName=typeof t==`string`?t:fM[t]}},TP;(function(e){e[e.AlreadyOpened=0]=`AlreadyOpened`,e[e.AbnormalEnd=1]=`AbnormalEnd`,e[e.DecodeFailed=2]=`DecodeFailed`,e[e.LengthExceeded=3]=`LengthExceeded`,e[e.Incomplete=4]=`Incomplete`,e[e.HandlerAlreadyRegistered=7]=`HandlerAlreadyRegistered`,e[e.EncryptionTypeMismatch=8]=`EncryptionTypeMismatch`,e[e.HeaderTooLarge=9]=`HeaderTooLarge`,e[e.PayloadTooLarge=10]=`PayloadTooLarge`})(TP||={});var EP=class extends mP{constructor(e,t){super(16,e),this.name=`DataStreamError`,this.reason=t,this.reasonName=TP[t]}},DP=class extends pP{constructor(e){super(18,e),this.name=`SignalReconnectError`}},OP;(function(e){e.PermissionDenied=`PermissionDenied`,e.NotFound=`NotFound`,e.DeviceInUse=`DeviceInUse`,e.Other=`Other`})(OP||={}),(function(e){function t(t){if(t&&`name`in t)return t.name===`NotFoundError`||t.name===`DevicesNotFoundError`?e.NotFound:t.name===`NotAllowedError`||t.name===`PermissionDeniedError`?e.PermissionDenied:t.name===`NotReadableError`||t.name===`TrackStartError`?e.DeviceInUse:e.Other}e.getFailure=t})(OP||={});var kP=class{};kP.setTimeout=function(){return setTimeout(...arguments)},kP.setInterval=function(){return setInterval(...arguments)},kP.clearTimeout=function(){return clearTimeout(...arguments)},kP.clearInterval=function(){return clearInterval(...arguments)};var Y;(function(e){e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`,e.Reconnected=`reconnected`,e.Disconnected=`disconnected`,e.ConnectionStateChanged=`connectionStateChanged`,e.Moved=`moved`,e.MediaDevicesChanged=`mediaDevicesChanged`,e.ParticipantConnected=`participantConnected`,e.ParticipantDisconnected=`participantDisconnected`,e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalAudioSilenceDetected=`localAudioSilenceDetected`,e.ActiveSpeakersChanged=`activeSpeakersChanged`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.ParticipantAttributesChanged=`participantAttributesChanged`,e.ParticipantActive=`participantActive`,e.RoomMetadataChanged=`roomMetadataChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.AudioPlaybackStatusChanged=`audioPlaybackChanged`,e.VideoPlaybackStatusChanged=`videoPlaybackChanged`,e.MediaDevicesError=`mediaDevicesError`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.SignalConnected=`signalConnected`,e.RecordingStatusChanged=`recordingStatusChanged`,e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ActiveDeviceChanged=`activeDeviceChanged`,e.ChatMessage=`chatMessage`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.MetricsReceived=`metricsReceived`,e.DataTrackPublished=`dataTrackPublished`,e.DataTrackUnpublished=`dataTrackUnpublished`,e.LocalDataTrackPublished=`localDataTrackPublished`,e.LocalDataTrackUnpublished=`localDataTrackUnpublished`})(Y||={});var X;(function(e){e.TrackPublished=`trackPublished`,e.TrackSubscribed=`trackSubscribed`,e.TrackSubscriptionFailed=`trackSubscriptionFailed`,e.TrackUnpublished=`trackUnpublished`,e.TrackUnsubscribed=`trackUnsubscribed`,e.TrackMuted=`trackMuted`,e.TrackUnmuted=`trackUnmuted`,e.LocalTrackPublished=`localTrackPublished`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackCpuConstrained=`localTrackCpuConstrained`,e.LocalSenderCreated=`localSenderCreated`,e.ParticipantMetadataChanged=`participantMetadataChanged`,e.ParticipantNameChanged=`participantNameChanged`,e.DataReceived=`dataReceived`,e.SipDTMFReceived=`sipDTMFReceived`,e.TranscriptionReceived=`transcriptionReceived`,e.IsSpeakingChanged=`isSpeakingChanged`,e.ConnectionQualityChanged=`connectionQualityChanged`,e.TrackStreamStateChanged=`trackStreamStateChanged`,e.TrackSubscriptionPermissionChanged=`trackSubscriptionPermissionChanged`,e.TrackSubscriptionStatusChanged=`trackSubscriptionStatusChanged`,e.TrackCpuConstrained=`trackCpuConstrained`,e.MediaDevicesError=`mediaDevicesError`,e.AudioStreamAcquired=`audioStreamAcquired`,e.ParticipantPermissionsChanged=`participantPermissionsChanged`,e.PCTrackAdded=`pcTrackAdded`,e.AttributesChanged=`attributesChanged`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.ChatMessage=`chatMessage`,e.Active=`active`})(X||={});var Z;(function(e){e.TransportsCreated=`transportsCreated`,e.Connected=`connected`,e.Disconnected=`disconnected`,e.Resuming=`resuming`,e.Resumed=`resumed`,e.Restarting=`restarting`,e.Restarted=`restarted`,e.SignalResumed=`signalResumed`,e.SignalRestarted=`signalRestarted`,e.Closing=`closing`,e.MediaTrackAdded=`mediaTrackAdded`,e.ActiveSpeakersUpdate=`activeSpeakersUpdate`,e.DataPacketReceived=`dataPacketReceived`,e.RTPVideoMapUpdate=`rtpVideoMapUpdate`,e.DCBufferStatusChanged=`dcBufferStatusChanged`,e.ParticipantUpdate=`participantUpdate`,e.RoomUpdate=`roomUpdate`,e.SpeakersChanged=`speakersChanged`,e.StreamStateChanged=`streamStateChanged`,e.ConnectionQualityUpdate=`connectionQualityUpdate`,e.SubscriptionError=`subscriptionError`,e.SubscriptionPermissionUpdate=`subscriptionPermissionUpdate`,e.RemoteMute=`remoteMute`,e.SubscribedQualityUpdate=`subscribedQualityUpdate`,e.LocalTrackUnpublished=`localTrackUnpublished`,e.LocalTrackSubscribed=`localTrackSubscribed`,e.Offline=`offline`,e.SignalRequestResponse=`signalRequestResponse`,e.SignalConnected=`signalConnected`,e.RoomMoved=`roomMoved`,e.PublishDataTrackResponse=`publishDataTrackResponse`,e.UnPublishDataTrackResponse=`unPublishDataTrackResponse`,e.DataTrackSubscriberHandles=`dataTrackSubscriberHandles`,e.DataTrackPacketReceived=`dataTrackPacketReceived`,e.Joined=`joined`,e.TokenRefreshed=`tokenRefreshed`,e.ServerRegionsReported=`serverRegionsReported`})(Z||={});var Q;(function(e){e.Message=`message`,e.Muted=`muted`,e.Unmuted=`unmuted`,e.Restarted=`restarted`,e.Ended=`ended`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`,e.CpuConstrained=`cpuConstrained`,e.UpdateSettings=`updateSettings`,e.UpdateSubscription=`updateSubscription`,e.AudioPlaybackStarted=`audioPlaybackStarted`,e.AudioPlaybackFailed=`audioPlaybackFailed`,e.AudioSilenceDetected=`audioSilenceDetected`,e.VisibilityChanged=`visibilityChanged`,e.VideoDimensionsChanged=`videoDimensionsChanged`,e.VideoPlaybackStarted=`videoPlaybackStarted`,e.VideoPlaybackFailed=`videoPlaybackFailed`,e.ElementAttached=`elementAttached`,e.ElementDetached=`elementDetached`,e.UpstreamPaused=`upstreamPaused`,e.UpstreamResumed=`upstreamResumed`,e.SubscriptionPermissionChanged=`subscriptionPermissionChanged`,e.SubscriptionStatusChanged=`subscriptionStatusChanged`,e.SubscriptionFailed=`subscriptionFailed`,e.TrackProcessorUpdate=`trackProcessorUpdate`,e.AudioTrackFeatureUpdate=`audioTrackFeatureUpdate`,e.TranscriptionReceived=`transcriptionReceived`,e.TimeSyncUpdate=`timeSyncUpdate`,e.PreConnectBufferFlushed=`preConnectBufferFlushed`})(Q||={});function AP(e){let t={};for(let r of Object.entries(e)){var n=wO(r,2);let e=n[0],i=n[1];i!==void 0&&(t[e]=i)}return t}function jP(e,t){return e&&t?`${e}x${t}`:void 0}function MP(e){return Math.round(e*1e4)/1e4}function NP(e){let t=e.jitterBufferDelay,n=e.jitterBufferEmittedCount;return t!==void 0&&n?MP(t/n):void 0}function PP(e,t){if(e.playoutDelay!==void 0)return MP(e.playoutDelay);let n=t?.totalPlayoutDelay,r=t?.totalSamplesCount;return n!==void 0&&r?MP(n/r):void 0}function FP(e){let t=new Map,n=[],r=[],i=[],a;e.forEach(e=>t.set(e.id,e));let o=e=>e.codecId?t.get(e.codecId)?.mimeType:void 0,s=(e,n)=>e[n]?t.get(e[n]):void 0;e.forEach(e=>{switch(e.type){case`inbound-rtp`:{let t=s(e,`playoutId`);r.push(AP({kind:e.kind,ssrc:e.ssrc,mid:e.mid,trackId:e.trackIdentifier,codec:o(e),decoder:e.decoderImplementation,resolution:jP(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,bytesReceived:e.bytesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,packetsDiscarded:e.packetsDiscarded,framesReceived:e.framesReceived,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,keyFramesDecoded:e.keyFramesDecoded,freezeCount:e.freezeCount,totalFreezesDuration:e.totalFreezesDuration,pauseCount:e.pauseCount,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,jitter:e.jitter,jitterBuffer:NP(e),playoutDelay:PP(e,t),audioLevel:e.audioLevel,totalSamplesReceived:e.totalSamplesReceived,concealedSamples:e.concealedSamples}));break}case`outbound-rtp`:{let t=s(e,`remoteId`),n=s(e,`mediaSourceId`);i.push(AP({kind:e.kind,ssrc:e.ssrc,mid:e.mid,rid:e.rid,trackId:n?.trackIdentifier,active:e.active,codec:o(e),encoder:e.encoderImplementation,resolution:jP(e.frameWidth,e.frameHeight),fps:e.framesPerSecond,captureResolution:jP(n?.width,n?.height),captureFps:n?.framesPerSecond,audioLevel:n?.audioLevel,targetBitrate:e.targetBitrate,bytesSent:e.bytesSent,packetsSent:e.packetsSent,retransmittedPacketsSent:e.retransmittedPacketsSent,framesEncoded:e.framesEncoded,keyFramesEncoded:e.keyFramesEncoded,limitedBy:e.qualityLimitationReason===`none`?void 0:e.qualityLimitationReason,nackCount:e.nackCount,pliCount:e.pliCount,firCount:e.firCount,remotePacketsLost:t?.packetsLost,remoteFractionLost:t?.fractionLost,remoteJitter:t?.jitter,remoteRoundTripTime:t?.roundTripTime}));break}case`transport`:a=e;break;case`candidate-pair`:n.push(e)}});let c=a?.selectedCandidatePairId,l=(c?t.get(c):void 0)??n.find(e=>e.selected)??n.find(e=>e.nominated),u=l?.localCandidateId?t.get(l.localCandidateId):void 0,d=l?.remoteCandidateId?t.get(l.remoteCandidateId):void 0,f=AP({ice:a?.iceState,dtls:a?.dtlsState,route:u&&d?`${u.candidateType}/${u.protocol} -> ${d.candidateType}`:void 0,network:u?.networkType,currentRoundTripTime:l?.currentRoundTripTime,availableOutgoingBitrate:l?.availableOutgoingBitrate,availableIncomingBitrate:l?.availableIncomingBitrate,bytesSent:l?.bytesSent,bytesReceived:l?.bytesReceived,candidatePairChanges:a?.selectedCandidatePairChanges});return{connection:Object.keys(f).length>0?f:void 0,outbound:i.length>0?i:void 0,inbound:r.length>0?r:void 0}}function IP(e){return e===void 0?e:typeof structuredClone==`function`?typeof e==`object`&&e?structuredClone(Object.assign({},e)):structuredClone(e):JSON.parse(JSON.stringify(e))}var LP=class{constructor(e,t,n,r,i){if(typeof e==`object`)this.width=e.width,this.height=e.height,this.aspectRatio=e.aspectRatio,this.encoding={maxBitrate:e.maxBitrate,maxFramerate:e.maxFramerate,priority:e.priority};else if(t!==void 0&&n!==void 0)this.width=e,this.height=t,this.aspectRatio=e/t,this.encoding={maxBitrate:n,maxFramerate:r,priority:i};else throw TypeError(`Unsupported options: provide at least width, height and maxBitrate`)}get resolution(){return{width:this.width,height:this.height,frameRate:this.encoding.maxFramerate,aspectRatio:this.aspectRatio}}},RP=[`vp8`,`h264`],zP=[`vp8`,`h264`,`vp9`,`av1`,`h265`];function BP(e){return!!RP.find(t=>t===e)}var VP=BP,HP;(function(e){e[e.PREFER_REGRESSION=0]=`PREFER_REGRESSION`,e[e.SIMULCAST=1]=`SIMULCAST`,e[e.REGRESSION=2]=`REGRESSION`})(HP||={});var UP;(function(e){e.telephone={maxBitrate:12e3},e.speech={maxBitrate:24e3},e.music={maxBitrate:48e3},e.musicStereo={maxBitrate:64e3},e.musicHighQuality={maxBitrate:96e3},e.musicHighQualityStereo={maxBitrate:128e3}})(UP||={});var WP={h90:new LP(160,90,9e4,20),h180:new LP(320,180,16e4,20),h216:new LP(384,216,18e4,20),h360:new LP(640,360,45e4,20),h540:new LP(960,540,8e5,25),h720:new LP(1280,720,17e5,30),h1080:new LP(1920,1080,3e6,30),h1440:new LP(2560,1440,5e6,30),h2160:new LP(3840,2160,8e6,30)},GP={h120:new LP(160,120,7e4,20),h180:new LP(240,180,125e3,20),h240:new LP(320,240,14e4,20),h360:new LP(480,360,33e4,20),h480:new LP(640,480,5e5,20),h540:new LP(720,540,6e5,25),h720:new LP(960,720,13e5,30),h1080:new LP(1440,1080,23e5,30),h1440:new LP(1920,1440,38e5,30)},KP={h360fps3:new LP(640,360,2e5,3,`medium`),h360fps15:new LP(640,360,4e5,15,`medium`),h720fps5:new LP(1280,720,8e5,5,`medium`),h720fps15:new LP(1280,720,15e5,15,`medium`),h720fps30:new LP(1280,720,2e6,30,`medium`),h1080fps15:new LP(1920,1080,25e5,15,`medium`),h1080fps30:new LP(1920,1080,5e6,30,`medium`),original:new LP(0,0,7e6,30,`medium`)};function qP(e,t,n){var r,i;let a=oF(e??{}),o=a.optionsWithoutProcessor,s=a.audioProcessor,c=a.videoProcessor,l=t?.processor,u=n?.processor,d=o??{};return d.audio===!0&&(d.audio={}),d.video===!0&&(d.video={}),d.audio&&(JP(d.audio,t),(r=d.audio).deviceId??(r.deviceId={ideal:`default`}),(s||l)&&(d.audio.processor=s??l)),d.video&&(JP(d.video,n),(i=d.video).deviceId??(i.deviceId={ideal:`default`}),(c||u)&&(d.video.processor=c??u)),d}function JP(e,t){return Object.keys(t).forEach(n=>{e[n]===void 0&&(e[n]=t[n])}),e}function YP(e){var t,n;let r={};if(e.video){if(typeof e.video==`object`){let n={},i=n,a=e.video;Object.keys(a).forEach(e=>{switch(e){case`resolution`:JP(i,a.resolution);break;default:i[e]=a[e]}}),r.video=n,(t=r.video).deviceId??(t.deviceId={ideal:`default`})}else r.video=e.video?{deviceId:{ideal:`default`}}:!1}else r.video=!1;return e.audio?typeof e.audio==`object`?(r.audio=e.audio,(n=r.audio).deviceId??(n.deviceId={ideal:`default`})):r.audio={deviceId:{ideal:`default`}}:r.audio=!1,r}function XP(e){return J(this,arguments,void 0,function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:200;return function*(){let n=ZP();if(n){let r=n.createAnalyser();r.fftSize=2048;let i=r.frequencyBinCount,a=new Uint8Array(i);n.createMediaStreamSource(new MediaStream([e.mediaStreamTrack])).connect(r),yield vF(t),r.getByteTimeDomainData(a);let o=a.some(e=>e!==128&&e!==0);return n.close(),!o}return!1}()})}function ZP(){let e=typeof window<`u`&&(window.AudioContext||window.webkitAudioContext);if(e){let t=new e({latencyHint:`interactive`});if(t.state===`suspended`&&typeof window<`u`&&window.document?.body){let e=()=>J(this,void 0,void 0,function*(){var n;try{t.state===`suspended`&&(yield t.resume())}catch(e){console.warn(`Error trying to auto-resume audio context`,e)}finally{(n=window.document.body)==null||n.removeEventListener(`click`,e)}});t.addEventListener(`statechange`,()=>{var n;t.state===`closed`&&((n=window.document.body)==null||n.removeEventListener(`click`,e))}),window.document.body.addEventListener(`click`,e)}return t}}function QP(e){return e===`audioinput`?$.Source.Microphone:e===`videoinput`?$.Source.Camera:$.Source.Unknown}function $P(e){if(e===$.Source.Microphone)return`audioinput`;if(e===$.Source.Camera)return`videoinput`}function eF(e){let t=e.video??!0;return e.resolution&&e.resolution.width>0&&e.resolution.height>0&&(t=typeof t==`boolean`?{}:t,t=PF()?Object.assign(Object.assign({},t),{width:{max:e.resolution.width},height:{max:e.resolution.height},frameRate:e.resolution.frameRate}):Object.assign(Object.assign({},t),{width:{ideal:e.resolution.width},height:{ideal:e.resolution.height},frameRate:e.resolution.frameRate})),{audio:e.audio??!1,video:t,controller:e.controller,selfBrowserSurface:e.selfBrowserSurface,surfaceSwitching:e.surfaceSwitching,systemAudio:e.systemAudio,preferCurrentTab:e.preferCurrentTab}}function tF(e){return e.split(`/`)[1].toLowerCase()}function nF(e){let t=[];return e.forEach(e=>{e.track!==void 0&&t.push(new Cj({cid:e.track.mediaStreamID,track:e.trackInfo}))}),t}function rF(e){return`mediaStreamTrack`in e?{trackID:e.sid,source:e.source,muted:e.isMuted,enabled:e.mediaStreamTrack.enabled,kind:e.kind,streamID:e.mediaStreamID,streamTrackID:e.mediaStreamTrack.id}:{trackID:e.trackSid,enabled:e.isEnabled,muted:e.isMuted,trackInfo:Object.assign({mimeType:e.mimeType,name:e.trackName,encrypted:e.isEncrypted,kind:e.kind,source:e.source},e.track?rF(e.track):{})}}function iF(){return typeof RTCRtpReceiver<`u`&&typeof RTCRtpReceiver.prototype.getSynchronizationSources==`function`}function aF(e,t){e===void 0&&(e={}),t===void 0&&(t={});let n=[...Object.keys(t),...Object.keys(e)],r={};for(let i of n)e[i]!==t[i]&&(r[i]=t[i]??``);return r}function oF(e){let t=Object.assign({},e),n,r;return typeof t.audio==`object`&&t.audio.processor&&(n=t.audio.processor,t.audio=Object.assign(Object.assign({},t.audio),{processor:void 0})),typeof t.video==`object`&&t.video.processor&&(r=t.video.processor,t.video=Object.assign(Object.assign({},t.video),{processor:void 0})),{audioProcessor:n,videoProcessor:r,optionsWithoutProcessor:IP(t)}}function sF(e){switch(e){case Zk.CAMERA:return $.Source.Camera;case Zk.MICROPHONE:return $.Source.Microphone;case Zk.SCREEN_SHARE:return $.Source.ScreenShare;case Zk.SCREEN_SHARE_AUDIO:return $.Source.ScreenShareAudio;default:return $.Source.Unknown}}function cF(e,t){return e.width*e.height<t.width*t.height}function lF(e,t){return e.layers?.find(e=>e.quality===t)}var uF=5e3,dF=[],fF;(function(e){e[e.LOW=0]=`LOW`,e[e.MEDIUM=1]=`MEDIUM`,e[e.HIGH=2]=`HIGH`})(fF||={});var $=class e extends KM.EventEmitter{get streamState(){return this._streamState}setStreamState(e){this._streamState!==e&&this.log.debug(`stream state changed: ${this._streamState} -> ${e}`),this._streamState=e}constructor(t,n){let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};super(),this.attachedElements=[],this.isMuted=!1,this._streamState=e.StreamState.Active,this.isInBackground=!1,this._currentBitrate=0,this.finalStatsLogged=!1,this.log=DM,this.appVisibilityChangedListener=()=>{this.backgroundTimeout&&clearTimeout(this.backgroundTimeout),document.visibilityState===`hidden`?this.backgroundTimeout=setTimeout(()=>this.handleAppVisibilityChanged(),uF):this.handleAppVisibilityChanged()},this.loggerContextCb=r.loggerContextCb,this.log=OM(r.loggerName??EM.Track,()=>this.logContext),this.setMaxListeners(100),this.kind=n,this._mediaStreamTrack=t,this._mediaStreamID=t.id,this.source=e.Source.Unknown}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),rF(this))}get currentBitrate(){return this._currentBitrate}get mediaStreamTrack(){return this._mediaStreamTrack}get mediaStreamID(){return this._mediaStreamID}attach(t){let n=`audio`;this.kind===e.Kind.Video&&(n=`video`),this.attachedElements.length===0&&this.kind===e.Kind.Video&&this.addAppVisibilityListener(),t||(n===`audio`&&(dF.forEach(e=>{e.parentElement===null&&!t&&(t=e)}),t&&dF.splice(dF.indexOf(t),1)),t||=document.createElement(n)),this.attachedElements.includes(t)||this.attachedElements.push(t),pF(this.mediaStreamTrack,t);let r=t.srcObject.getTracks(),i=r.some(e=>e.kind===`audio`);return t.play().then(()=>{this.emit(i?Q.AudioPlaybackStarted:Q.VideoPlaybackStarted)}).catch(e=>{e.name===`NotAllowedError`?this.emit(i?Q.AudioPlaybackFailed:Q.VideoPlaybackFailed,e):e.name===`AbortError`?this.log.debug(`${i?`audio`:`video`} playback aborted, likely due to new play request`):this.log.warn(`could not playback ${i?`audio`:`video`}`,{error:e}),i&&t&&r.some(e=>e.kind===`video`)&&e.name===`NotAllowedError`&&(t.muted=!0,t.play().catch(()=>{}))}),this.emit(Q.ElementAttached,t),t}detach(e){try{if(e){mF(this.mediaStreamTrack,e);let t=this.attachedElements.indexOf(e);return t>=0&&(this.attachedElements.splice(t,1),this.recycleElement(e),this.emit(Q.ElementDetached,e)),e}let t=[];return this.attachedElements.forEach(e=>{mF(this.mediaStreamTrack,e),t.push(e),this.recycleElement(e),this.emit(Q.ElementDetached,e)}),this.attachedElements=[],t}finally{this.attachedElements.length===0&&this.removeAppVisibilityListener()}}stop(){this.log.debug(`stopping track`),this.stopMonitor(),this._mediaStreamTrack.stop()}enable(){this._mediaStreamTrack.enabled=!0}disable(){this._mediaStreamTrack.enabled=!1}stopMonitor(){this.monitorInterval&&clearInterval(this.monitorInterval),this.timeSyncHandle!==void 0&&(cancelAnimationFrame(this.timeSyncHandle),this.timeSyncHandle=void 0),this.logFinalStats()}logFinalStats(){this.finalStatsLogged||(this.finalStatsLogged=!0,this.getRTCStatsReport().then(e=>{e&&this.log.info(`final track stats`,FP(e))}).catch(e=>this.log.debug(`could not collect final track stats`,{error:e})))}updateLoggerOptions(e){e.loggerContextCb&&(this.loggerContextCb=e.loggerContextCb),e.loggerName&&(this.log=OM(e.loggerName,()=>this.logContext))}recycleElement(e){if(e instanceof HTMLAudioElement){let t=!0;e.pause(),dF.forEach(e=>{e.parentElement||(t=!1)}),t&&dF.push(e)}}handleAppVisibilityChanged(){return J(this,void 0,void 0,function*(){this.isInBackground=document.visibilityState===`hidden`,!this.isInBackground&&this.kind===e.Kind.Video&&setTimeout(()=>this.attachedElements.forEach(e=>e.play().catch(()=>{})),0)})}addAppVisibilityListener(){BF()?(this.isInBackground=document.visibilityState===`hidden`,document.addEventListener(`visibilitychange`,this.appVisibilityChangedListener)):this.isInBackground=!1}removeAppVisibilityListener(){BF()&&document.removeEventListener(`visibilitychange`,this.appVisibilityChangedListener)}};function pF(e,t){let n;n=t.srcObject instanceof MediaStream?t.srcObject:new MediaStream;let r;r=e.kind===`audio`?n.getAudioTracks():n.getVideoTracks(),r.includes(e)||(r.forEach(e=>{n.removeTrack(e)}),n.addTrack(e)),(!PF()||!(t instanceof HTMLVideoElement))&&(t.autoplay=!0),t.muted=n.getAudioTracks().length===0,t instanceof HTMLVideoElement&&(t.playsInline=!0),t.srcObject!==n&&(t.srcObject=n,(PF()||jF())&&t instanceof HTMLVideoElement&&setTimeout(()=>{t.srcObject=n,t.play().catch(()=>{})},0))}function mF(e,t){if(t.srcObject instanceof MediaStream){let n=t.srcObject;n.removeTrack(e),t.srcObject=n.getTracks().length>0?n:null}}(function(e){let t;(function(e){e.Audio=`audio`,e.Video=`video`,e.Unknown=`unknown`})(t=e.Kind||={});let n;(function(e){e.Camera=`camera`,e.Microphone=`microphone`,e.ScreenShare=`screen_share`,e.ScreenShareAudio=`screen_share_audio`,e.Unknown=`unknown`})(n=e.Source||={});let r;(function(e){e.Active=`active`,e.Paused=`paused`,e.Unknown=`unknown`})(r=e.StreamState||={});function i(e){switch(e){case t.Audio:return Xk.AUDIO;case t.Video:return Xk.VIDEO;default:return Xk.DATA}}e.kindToProto=i;function a(e){switch(e){case Xk.AUDIO:return t.Audio;case Xk.VIDEO:return t.Video;default:return t.Unknown}}e.kindFromProto=a;function o(e){switch(e){case n.Camera:return Zk.CAMERA;case n.Microphone:return Zk.MICROPHONE;case n.ScreenShare:return Zk.SCREEN_SHARE;case n.ScreenShareAudio:return Zk.SCREEN_SHARE_AUDIO;default:return Zk.UNKNOWN}}e.sourceToProto=o;function s(e){switch(e){case Zk.CAMERA:return n.Camera;case Zk.MICROPHONE:return n.Microphone;case Zk.SCREEN_SHARE:return n.ScreenShare;case Zk.SCREEN_SHARE_AUDIO:return n.ScreenShareAudio;default:return n.Unknown}}e.sourceFromProto=s;function c(e){switch(e){case sj.ACTIVE:return r.Active;case sj.PAUSED:return r.Paused;default:return r.Unknown}}e.streamStateFromProto=c})($||={});var hF=`|`,gF=`https://aomediacodec.github.io/av1-rtp-spec/#dependency-descriptor-rtp-header-extension`;function _F(e){let t=e.split(hF);return t.length>1?[t[0],e.substr(t[0].length+1)]:[e,``]}function vF(e){return new aP(t=>kP.setTimeout(t,e))}function yF(){return`addTransceiver`in RTCPeerConnection.prototype}function bF(){return`addTrack`in RTCPeerConnection.prototype}function xF(){if(!(`getCapabilities`in RTCRtpSender)||PF()||jF())return!1;let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/av1`){t=!0;break}}return t}function SF(){if(!(`getCapabilities`in RTCRtpSender)||jF())return!1;if(PF()){let e=cP();if(e?.version&&qF(e.version,`16`)<0||e?.os===`iOS`&&e?.osVersion&&qF(e.osVersion,`16`)<0)return!1}let e=RTCRtpSender.getCapabilities(`video`),t=!1;if(e){for(let n of e.codecs)if(n.mimeType.toLowerCase()===`video/vp9`){t=!0;break}}return t}function CF(e){return e===`av1`||e===`vp9`}function wF(e){let t=e.getHeaderExtensionsToNegotiate?.call(e);if(!t||!e.setHeaderExtensionsToNegotiate)return!1;let n=t.find(e=>e.uri===gF);if(!n)return!1;if(n.direction!==`stopped`)return!0;n.direction=`sendrecv`;try{return e.setHeaderExtensionsToNegotiate(t),!0}catch{return!1}}function TF(e,t){return CF(e)&&!!t?.simulcast&&!!t.scalabilityMode?.startsWith(`L1T`)}function EF(){let e=cP();return FF()||VF()||e?.name===`Chrome`&&qF(e.version,`113`)<0}var DF=`1.13.6`;function OF(e){return e?qF(e,DF)>0:!1}function kF(e){return!document||FF()?!1:(e||=document.createElement(`audio`),`setSinkId`in e)}function AF(){return typeof RTCPeerConnection>`u`?!1:yF()||bF()}function jF(){return cP()?.name===`Firefox`}function MF(){let e=cP();return!!e&&e.name===`Chrome`&&e.os!==`iOS`}function NF(){return typeof window<`u`&&window.RTCRtpScriptTransform!==void 0&&!MF()}function PF(){return cP()?.name===`Safari`}function FF(){let e=cP();return e?.name===`Safari`||e?.os===`iOS`}function IF(){let e=cP();return e?.name===`Safari`&&e.version.startsWith(`17.`)||e?.os===`iOS`&&!!e?.osVersion&&qF(e.osVersion,`17`)>=0}function LF(e){return e||=cP(),e?.name===`Safari`&&qF(e.version,`18.3`)>0||e?.os===`iOS`&&!!e?.osVersion&&qF(e.osVersion,`18.3`)>0}function RF(){return BF()?navigator.userAgentData?.mobile??/Tablet|iPad|Mobile|Android|BlackBerry/.test(navigator.userAgent):!1}function zF(){let e=cP(),t=`17.2`;if(e)return e.name!==`Safari`&&e.os!==`iOS`||e.os===`iOS`&&e.osVersion&&qF(e.osVersion,t)>=0?!0:e.name===`Safari`&&qF(e.version,t)>=0}function BF(){return typeof document<`u`}function VF(){return navigator.product==`ReactNative`}function HF(e){return e.hostname.endsWith(`.livekit.cloud`)||e.hostname.endsWith(`.livekit.run`)}function UF(e){return HF(e)?e.hostname.split(`.`)[0]:null}function WF(){if(global&&global.LiveKitReactNativeGlobal)return global.LiveKitReactNativeGlobal}function GF(){if(!VF())return;let e=WF();if(e)return e.platform}function KF(){if(BF())return window.devicePixelRatio;if(VF()){let e=WF();if(e)return e.devicePixelRatio}return 1}function qF(e,t){let n=e.split(`.`),r=t.split(`.`),i=Math.min(n.length,r.length);for(let e=0;e<i;++e){let t=parseInt(n[e],10),a=parseInt(r[e],10);if(t>a)return 1;if(t<a)return-1;if(e===i-1&&t===a)return 0}return e===``&&t!==``?-1:t===``?1:n.length==r.length?0:n.length<r.length?-1:1}function JF(e){for(let t of e)t.target.handleResize(t)}function YF(e){for(let t of e)t.target.handleVisibilityChanged(t)}var XF=null,ZF=()=>(XF||=new ResizeObserver(JF),XF),QF=null,$F=()=>(QF||=new IntersectionObserver(YF,{root:null,rootMargin:`0px`}),QF);function eI(e){let t=new GA({capabilities:e,sdk:KA.JS,protocol:17,clientProtocol:2,version:fP});return VF()&&(t.os=GF()??``),t}function tI(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:16,t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:16,n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=arguments.length>3&&arguments[3]!==void 0&&arguments[3],i=document.createElement(`canvas`);i.width=e,i.height=t;let a=i.getContext(`2d`);a?.fillRect(0,0,i.width,i.height),r&&a&&(a.beginPath(),a.arc(e/2,t/2,50,0,Math.PI*2,!0),a.closePath(),a.fillStyle=`grey`,a.fill());let o=wO(i.captureStream().getTracks(),1)[0];if(!o)throw Error(`Could not get empty media stream video track`);return o.enabled=n,o}var nI;function rI(){if(!nI){let e=new AudioContext,t=e.createOscillator(),n=e.createGain();n.gain.setValueAtTime(0,0);let r=e.createMediaStreamDestination();if(t.connect(n),n.connect(r),t.start(),nI=wO(r.stream.getAudioTracks(),1)[0],!nI)throw Error(`Could not get empty media stream audio track`);nI.enabled=!1}return nI.clone()}var iI=class{get isResolved(){return this._isResolved}constructor(e,t){this._isResolved=!1,this.onFinally=t,this.promise=new Promise((t,n)=>J(this,void 0,void 0,function*(){this.resolve=t,this.reject=n,e&&(yield e(t,n))})).finally(()=>{var e;this._isResolved=!0,(e=this.onFinally)==null||e.call(this)})}};function aI(e){return zP.includes(e)}function oI(e){if(typeof e==`string`||typeof e==`number`)return e;if(Array.isArray(e))return e[0];if(e.exact!==void 0)return Array.isArray(e.exact)?e.exact[0]:e.exact;if(e.ideal!==void 0)return Array.isArray(e.ideal)?e.ideal[0]:e.ideal;throw Error(`could not unwrap constraint`)}function sI(e){return e.startsWith(`http`)?e.replace(/^(http)/,`ws`):e}function cI(e){return e.startsWith(`ws`)?e.replace(/^(ws)/,`http`):e}function lI(e,t){return e.segments.map(e=>{let n=e.id,r=e.text,i=e.language,a=e.startTime,o=e.endTime,s=e.final,c=t.get(n)??Date.now(),l=Date.now();return s?t.delete(n):t.set(n,c),{id:n,text:r,startTime:Number.parseInt(a.toString()),endTime:Number.parseInt(o.toString()),final:s,language:i,firstReceivedTime:c,lastReceivedTime:l}})}function uI(e){let t=e.id,n=e.timestamp,r=e.message,i=e.editTimestamp;return{id:t,timestamp:Number.parseInt(n.toString()),editTimestamp:i?Number.parseInt(i.toString()):void 0,message:r}}function dI(e){switch(e.reason){case hP.LeaveRequest:return e.context;case hP.Cancelled:return tA.CLIENT_INITIATED;case hP.NotAllowed:return tA.USER_REJECTED;case hP.ServerUnreachable:return tA.JOIN_FAILURE;default:return tA.UNKNOWN_REASON}}function fI(e){return e===void 0?void 0:Number(e)}function pI(e){return e===void 0?void 0:BigInt(e)}function mI(e){return!!e&&!(e instanceof MediaStreamTrack)&&e.isLocal}function hI(e){return!!e&&e.kind==$.Kind.Audio}function gI(e){return!!e&&e.kind==$.Kind.Video}function _I(e){return mI(e)&&gI(e)}function vI(e){return mI(e)&&hI(e)}function yI(e){return!!e&&!e.isLocal}function bI(e){return!!e&&!e.isLocal}function xI(e){return yI(e)&&gI(e)}function SI(e){return e.isLocal}function CI(e,t){let n=[],r=new TextEncoder().encode(e);for(;r.length>t;){let e=t;for(;e>0;){let t=r[e];if(t!==void 0&&(t&192)!=128)break;e--}n.push(r.slice(0,e)),r=r.slice(e)}return r.length>0&&n.push(r),n}function wI(e){return new ReadableStream({start(t){t.enqueue(e),t.close()}})}function TI(e,t){return BM(this,arguments,function*(){let n=e.getReader(),r=new Uint8Array;try{for(;;){let e=yield zM(n.read()),i=e.done,a=e.value;if(i)break;if(a.byteLength===0)continue;let o=new Uint8Array(r.byteLength+a.byteLength);for(o.set(r),o.set(a,r.byteLength),r=o;r.byteLength>=t;)yield yield zM(r.slice(0,t)),r=r.slice(t)}r.byteLength>0&&(yield yield zM(r))}finally{n.releaseLock()}})}function EI(e){let t=e.get(`Cache-Control`);if(t){let e=t.match(/(?:^|[,\s])max-age=(\d+)/)?.[1];if(e)return parseInt(e,10)}}function DI(){return typeof CompressionStream<`u`}function OI(){return DI()&&!jF()}function kI(e,t){let n=wO(_F(t.id),2)[1];if(n?.startsWith(`TR`))return n;if(e.id.startsWith(`TR`))return e.id}function AI(e,t){let n=arguments.length>2&&arguments[2]!==void 0&&arguments[2],r=jI(e,t);return n?r:PI(r,`v1`)}function jI(e,t){let n=new URL(sI(e));return t.forEach((e,t)=>{n.searchParams.set(t,e)}),PI(n,`rtc`)}function MI(e){return PI(new URL(cI(e)),`validate`)}function NI(e){return e.endsWith(`/`)?e:`${e}/`}function PI(e,t){return e.pathname=`${NI(e.pathname)}${t}`,e}function FI(e){if(typeof e==`string`)return uj.fromJson(JSON.parse(e),{ignoreUnknownFields:!0});if(e instanceof ArrayBuffer)return uj.fromBinary(new Uint8Array(e));throw Error(`could not decode websocket message: ${typeof e}`)}function II(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Unknown reason`;if(e instanceof Error)return e.message;if(!(e instanceof AbortSignal))return t;let n=e.reason;switch(typeof n){case`string`:return n;case`object`:return n instanceof Error?n.message:t;default:return`toString`in n?n.toString():t}}function LI(e,t){return e instanceof Error?e.name&&e.message?`${e.name}: ${e.message}`:e.name:`Encountered unknown ${t} error: ${String(e)}`}var RI=`lk_e2ee`,zI=`lk_e2ee_track_id`,BI;(function(e){e.SetKey=`setKey`,e.RatchetRequest=`ratchetRequest`,e.KeyRatcheted=`keyRatcheted`})(BI||={});var VI;(function(e){e.KeyRatcheted=`keyRatcheted`})(VI||={});var HI;(function(e){e.ParticipantEncryptionStatusChanged=`participantEncryptionStatusChanged`,e.EncryptionError=`encryptionError`})(HI||={});var UI;(function(e){e.Error=`cryptorError`})(UI||={});function WI(){return KI()||GI()}function GI(){return typeof window<`u`&&window.RTCRtpScriptTransform!==void 0}function KI(){return typeof window<`u`&&window.RTCRtpSender!==void 0&&window.RTCRtpSender.prototype.createEncodedStreams!==void 0}function qI(e){if(e.value?.case!==`sipDtmf`&&e.value?.case!==`metrics`&&e.value?.case!==`speaker`&&e.value?.case!==`transcription`&&e.value?.case!==`encryptedPacket`)return new AA({value:e.value})}KM.EventEmitter;var JI;(function(e){e[e.InvalidKey=0]=`InvalidKey`,e[e.MissingKey=1]=`MissingKey`,e[e.InternalError=2]=`InternalError`})(JI||={});var YI=class extends pP{constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:JI.InternalError,n=arguments.length>2?arguments[2]:void 0;super(40,e),this.reason=t,this.participantIdentity=n}};function XI(){return NF()}function ZI(e){return!!e?.worker&&(KI()||XI())}function QI(e){return!!(e?.timestamp||e?.frameId)}function $I(e){let t=[];return e?.timestamp&&t.push(aA.PTF_USER_TIMESTAMP),e?.frameId&&t.push(aA.PTF_FRAME_ID),t}function eL(e){if(!e||e.length===0)return;let t={};return e.includes(aA.PTF_USER_TIMESTAMP)&&(t.timestamp=!0),e.includes(aA.PTF_FRAME_ID)&&(t.frameId=!0),t.timestamp||t.frameId?t:void 0}function tL(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:50,n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},r,i=n.isImmediate??!1,a=n.callback??!1,o=n.maxWait,s=Date.now(),c=[];function l(){if(o!==void 0){let e=Date.now()-s;if(e+t>=o)return o-e}return t}let u=function(){var t=[...arguments];let n=this;return new Promise((o,u)=>{let d=function(){if(r=void 0,s=Date.now(),!i){let r=e.apply(n,t);a&&a(r),c.forEach(e=>{let t=e.resolve;return t(r)}),c=[]}},f=i&&r===void 0;if(r!==void 0&&kP.clearTimeout(r),r=kP.setTimeout(d,l()),f){let r=e.apply(n,t);return a&&a(r),o(r)}c.push({resolve:o,reject:u})})};return u.cancel=function(e){r!==void 0&&kP.clearTimeout(r),c.forEach(t=>{let n=t.reject;return n(e)}),c=[]},u}var nL=2e3;function rL(e,t){if(!t)return 0;let n,r;return`bytesReceived`in e?(n=e.bytesReceived,r=t.bytesReceived):`bytesSent`in e&&(n=e.bytesSent,r=t.bytesSent),n===void 0||r===void 0||e.timestamp===void 0||t.timestamp===void 0?0:(n-r)*8*1e3/(e.timestamp-t.timestamp)}var iL=class extends ${constructor(e,t,n,r,i){super(e,n,i),this.timeSyncLoop=()=>{if(this.listenerCount(Q.TimeSyncUpdate)===0){this.timeSyncHandle=void 0;return}this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop);let e=this.receiver?.getSynchronizationSources()[0];if(e){let t=e.timestamp,n=e.rtpTimestamp;n&&this.rtpTimestamp!==n&&(this.emit(Q.TimeSyncUpdate,{timestamp:t,rtpTimestamp:n}),this.rtpTimestamp=n)}},this.onTimeSyncListenerAdded=e=>{e===Q.TimeSyncUpdate&&this.timeSyncHandle===void 0&&(this.timeSyncHandle=requestAnimationFrame(this.timeSyncLoop))},this.sid=t,this.receiver=r}get isLocal(){return!1}setMuted(e){this.isMuted!==e&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Q.Muted:Q.Unmuted,this))}setMediaStream(e){this.mediaStream=e;let t=n=>{n.track===this._mediaStreamTrack&&(e.removeEventListener(`removetrack`,t),this.receiver&&`playoutDelayHint`in this.receiver&&(this.receiver.playoutDelayHint=void 0),this.receiver=void 0,this._currentBitrate=0,this.emit(Q.Ended,this))};e.addEventListener(`removetrack`,t)}start(){this.startMonitor(),super.enable()}stop(){this.stopMonitor(),super.disable()}getRTCStatsReport(){return J(this,void 0,void 0,function*(){if(this.receiver?.getStats)return yield this.receiver.getStats()})}setPlayoutDelay(e){this.receiver?`playoutDelayHint`in this.receiver?this.receiver.playoutDelayHint=e:this.log.warn(`Playout delay not supported in this browser`):this.log.warn(`Cannot set playout delay, track already ended`)}getPlayoutDelay(){if(this.receiver){if(`playoutDelayHint`in this.receiver)return this.receiver.playoutDelayHint;this.log.warn(`Playout delay not supported in this browser`)}else this.log.warn(`Cannot get playout delay, track already ended`);return 0}startMonitor(){this.monitorInterval||=setInterval(()=>this.monitorReceiver(),nL),iF()&&this.registerTimeSyncUpdate()}stopMonitor(){super.stopMonitor(),this.off(`newListener`,this.onTimeSyncListenerAdded)}registerTimeSyncUpdate(){let e=this;e.off(`newListener`,this.onTimeSyncListenerAdded),e.on(`newListener`,this.onTimeSyncListenerAdded),this.timeSyncHandle===void 0&&this.timeSyncLoop()}},aL=100,oL=class extends iL{constructor(e,t,n,r,i){super(e,t,$.Kind.Video,n,i),this.elementInfos=[],this.monitorReceiver=()=>J(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=rL(e,this.prevStats)),this.prevStats=e}),this.debouncedHandleResize=tL(()=>{this.updateDimensions()},aL),this.adaptiveStreamSettings=r}get isAdaptiveStream(){return this.adaptiveStreamSettings!==void 0}lookupFrameMetadata(e){let t=e.rtpTimestamp;return this.frameMetadataExtractor?.lookupMetadata(t)}setStreamState(e){super.setStreamState(e),this.log.debug(`setStreamState`,e),this.isAdaptiveStream&&e===$.StreamState.Active&&this.updateVisibility()}get mediaStreamTrack(){return this._mediaStreamTrack}setMuted(e){super.setMuted(e),this.attachedElements.forEach(t=>{e?mF(this._mediaStreamTrack,t):pF(this._mediaStreamTrack,t)})}attach(e){if(e?super.attach(e):e=super.attach(),this.adaptiveStreamSettings&&this.elementInfos.find(t=>t.element===e)===void 0){let t=new sL(e);this.observeElementInfo(t)}return e}observeElementInfo(e){this.adaptiveStreamSettings&&this.elementInfos.find(t=>t===e)===void 0?(e.handleResize=()=>{this.debouncedHandleResize()},e.handleVisibilityChanged=()=>{this.updateVisibility()},this.elementInfos.push(e),e.observe(),this.debouncedHandleResize(),this.updateVisibility()):this.log.warn(`visibility resize observer not triggered`,this.logContext)}stopObservingElementInfo(e){if(!this.isAdaptiveStream){this.log.warn(`stopObservingElementInfo ignored`,this.logContext);return}let t=this.elementInfos.filter(t=>t===e);for(let e of t)e.stopObserving();this.elementInfos=this.elementInfos.filter(t=>t!==e),this.updateVisibility(),this.debouncedHandleResize()}detach(e){if(e)return this.stopObservingElement(e),super.detach(e);let t=super.detach();for(let e of t)this.stopObservingElement(e);return t}getDecoderImplementation(){return this.prevStats?.decoderImplementation}getReceiverStats(){return J(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t,n=``,r=new Map;return e.forEach(e=>{e.type===`inbound-rtp`?(n=e.codecId,t={type:`video`,streamId:e.id,framesDecoded:e.framesDecoded,framesDropped:e.framesDropped,framesReceived:e.framesReceived,packetsReceived:e.packetsReceived,packetsLost:e.packetsLost,frameWidth:e.frameWidth,frameHeight:e.frameHeight,pliCount:e.pliCount,firCount:e.firCount,nackCount:e.nackCount,jitter:e.jitter,timestamp:e.timestamp,bytesReceived:e.bytesReceived,decoderImplementation:e.decoderImplementation}):e.type===`codec`&&r.set(e.id,e)}),t&&n!==``&&r.get(n)&&(t.mimeType=r.get(n).mimeType),t})}stopObservingElement(e){let t=this.elementInfos.filter(t=>t.element===e);for(let e of t)this.stopObservingElementInfo(e)}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return J(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),this.isAdaptiveStream&&this.updateVisibility()})}updateVisibility(e){let t=this.elementInfos.reduce((e,t)=>Math.max(e,t.visibilityChangedAt||0),0),n=this.adaptiveStreamSettings?.pauseVideoInBackground??!0?this.isInBackground:!1,r=this.elementInfos.some(e=>e.pictureInPicture),i=this.elementInfos.some(e=>e.visible)&&!n||r;if(this.lastVisible!==i||e){if(!i&&Date.now()-t<aL){kP.setTimeout(()=>{this.updateVisibility()},aL);return}this.lastVisible=i,this.emit(Q.VisibilityChanged,i,this)}}updateDimensions(){let e=0,t=0,n=this.getPixelDensity();for(let r of this.elementInfos){let i=r.width()*n,a=r.height()*n;i+a>e+t&&(e=i,t=a)}(this.lastDimensions?.width!==e||this.lastDimensions?.height!==t)&&(this.lastDimensions={width:e,height:t},this.emit(Q.VideoDimensionsChanged,this.lastDimensions,this))}getPixelDensity(){let e=this.adaptiveStreamSettings?.pixelDensity;return e===`screen`?KF():e||(KF()>2?2:1)}},sL=class{get visible(){return this.isPiP||this.isIntersecting}get pictureInPicture(){return this.isPiP}constructor(e,t){this.onVisibilityChanged=e=>{var t;let n=e.target,r=e.isIntersecting;n===this.element&&(this.isIntersecting=r,this.isPiP=cL(this.element),this.visibilityChangedAt=Date.now(),(t=this.handleVisibilityChanged)==null||t.call(this))},this.onEnterPiP=()=>{var e;(e=window.documentPictureInPicture?.window)==null||e.addEventListener(`pagehide`,this.onLeavePiP),queueMicrotask(()=>{requestAnimationFrame(()=>{var e;this.isPiP=cL(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)})})},this.onLeavePiP=()=>{var e;this.isPiP=cL(this.element),(e=this.handleVisibilityChanged)==null||e.call(this)},this.element=e,this.isIntersecting=t??lL(e),this.isPiP=BF()&&cL(e),this.visibilityChangedAt=0}width(){return this.element.clientWidth}height(){return this.element.clientHeight}observe(){var e,t;this.isIntersecting=lL(this.element),this.isPiP=cL(this.element),this.element.handleResize=()=>{var e;(e=this.handleResize)==null||e.call(this)},this.element.handleVisibilityChanged=this.onVisibilityChanged,$F().observe(this.element),ZF().observe(this.element),this.element.addEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.addEventListener(`leavepictureinpicture`,this.onLeavePiP),(e=window.documentPictureInPicture)==null||e.addEventListener(`enter`,this.onEnterPiP),(t=window.documentPictureInPicture?.window)==null||t.addEventListener(`pagehide`,this.onLeavePiP)}stopObserving(){var e,t,n,r;(e=$F())==null||e.unobserve(this.element),(t=ZF())==null||t.unobserve(this.element),this.element.removeEventListener(`enterpictureinpicture`,this.onEnterPiP),this.element.removeEventListener(`leavepictureinpicture`,this.onLeavePiP),(n=window.documentPictureInPicture)==null||n.removeEventListener(`enter`,this.onEnterPiP),(r=window.documentPictureInPicture?.window)==null||r.removeEventListener(`pagehide`,this.onLeavePiP)}};function cL(e){return document.pictureInPictureElement===e?!0:window.documentPictureInPicture?.window?lL(e,window.documentPictureInPicture?.window):!1}function lL(e,t){let n=t||window,r=e.offsetTop,i=e.offsetLeft,a=e.offsetWidth,o=e.offsetHeight,s=e.hidden,c=getComputedStyle(e).display;for(;e.offsetParent;)e=e.offsetParent,r+=e.offsetTop,i+=e.offsetLeft;return r<n.pageYOffset+n.innerHeight&&i<n.pageXOffset+n.innerWidth&&r+o>n.pageYOffset&&i+a>n.pageXOffset&&!s&&c!==`none`}var uL=class e extends KM.EventEmitter{get logContext(){return{room:this.room?.name,participant:this.room?.localParticipant.identity}}constructor(e,t){super(),this.decryptDataRequests=new Map,this.encryptDataRequests=new Map,this.log=OM(EM.E2EE,()=>this.logContext),this.onWorkerMessage=e=>{let t=e.data,n=t.kind,r=t.data;switch(n){case`error`:if(r.uuid){let e=this.decryptDataRequests.get(r.uuid);if(e?.reject){e.reject(r.error);break}let t=this.encryptDataRequests.get(r.uuid);if(t?.reject){t.reject(r.error);break}}this.log.error(r.error.message),this.emit(HI.EncryptionError,r.error,r.participantIdentity);break;case`initAck`:r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)});break;case`enable`:if(r.enabled&&this.keyProvider.getKeys().forEach(e=>{this.postKey(e,!1)}),this.encryptionEnabled!==r.enabled&&r.participantIdentity===this.room?.localParticipant.identity)this.emit(HI.ParticipantEncryptionStatusChanged,r.enabled,this.room.localParticipant),this.encryptionEnabled=r.enabled;else if(r.participantIdentity){let e=this.room?.getParticipantByIdentity(r.participantIdentity);if(!e)throw TypeError(`couldn't set encryption status, participant not found${r.participantIdentity}`);this.emit(HI.ParticipantEncryptionStatusChanged,r.enabled,e)}break;case`ratchetKey`:this.keyProvider.emit(BI.KeyRatcheted,r.ratchetResult,r.participantIdentity,r.keyIndex);break;case`decryptDataResponse`:let e=this.decryptDataRequests.get(r.uuid);e?.resolve&&e.resolve(r);break;case`encryptDataResponse`:let t=this.encryptDataRequests.get(r.uuid);t?.resolve&&t.resolve(r);break;case`packetTrailerMetadata`:this.handleFrameMetadata(r.trackId,r.rtpTimestamp,r.ssrc,r.metadata);break;case`log`:AM[r.level](r.msg,r.context)}},this.onWorkerError=e=>{this.log.error(`e2ee worker encountered an error:`,{error:e.error}),this.emit(HI.EncryptionError,e.error,void 0)},this.keyProvider=e.keyProvider,this.worker=e.worker,this.encryptionEnabled=!1,this.dataChannelEncryptionEnabled=t}get isEnabled(){return this.encryptionEnabled}get isDataChannelEncryptionEnabled(){return this.isEnabled&&this.dataChannelEncryptionEnabled}setup(e){if(!WI())throw new _P(`tried to setup end-to-end encryption on an unsupported browser`);if(this.log.info(`setting up e2ee`),e!==this.room){this.room=e,this.setupEventListeners(e,this.keyProvider);let t={kind:`init`,data:{keyProviderOptions:this.keyProvider.getOptions(),loglevel:AM.getLevel()}};this.worker&&(this.log.info(`initializing worker`,{worker:this.worker}),this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage(t),this.subscribeToLogLevelChanges())}}subscribeToLogLevelChanges(){var t;(t=this.unsubscribeLogLevel)==null||t.call(this);let n;if(e.disposeRegistry){let t=new WeakRef(this.worker);n=NM(e=>{let r=t.deref();if(!r){n?.();return}r.postMessage({kind:`setLogLevel`,data:{level:e}})}),e.disposeRegistry.register(this,n,this)}else{let e=this.worker;n=NM(t=>{e.postMessage({kind:`setLogLevel`,data:{level:t}})})}this.unsubscribeLogLevel=n}dispose(){var t,n,r;(t=this.unsubscribeLogLevel)==null||t.call(this),this.unsubscribeLogLevel=void 0,e.disposeRegistry&&e.disposeRegistry.unregister(this);let i=new YI(`E2EEManager disposed`,JI.InternalError);for(let e of[...this.encryptDataRequests.values()])(n=e.reject)==null||n.call(e,i);for(let e of[...this.decryptDataRequests.values()])(r=e.reject)==null||r.call(e,i);this.worker&&(this.worker.onmessage=null,this.worker.onerror=null),this.removeAllListeners()}setParticipantCryptorEnabled(e,t){this.log.debug(`set e2ee to ${e} for participant ${t}`),this.postEnable(e,t)}setSifTrailer(e){!e||e.length===0?this.log.warn(`ignoring server sent trailer as it's empty`):this.postSifTrailer(e)}handleFrameMetadata(e,t,n,r){if(this.room){for(let i of[this.room.localParticipant,...this.room.remoteParticipants.values()])for(let a of i.trackPublications.values())if(a.track&&a.track.mediaStreamID===e&&a.track instanceof oL&&a.track.frameMetadataExtractor){a.track.frameMetadataExtractor.storeMetadata(t,n,r);return}}}setupEngine(e){e.on(Z.RTPVideoMapUpdate,e=>{this.postRTPMap(e)})}setupEventListeners(e,t){e.on(Y.TrackPublished,(e,t)=>this.setParticipantCryptorEnabledForPublication(e,t.identity)),e.on(Y.ConnectionStateChanged,t=>{t===gH.Connected&&e.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{this.setParticipantCryptorEnabledForPublication(t,e.identity)})})}).on(Y.TrackUnsubscribed,(e,t,n)=>{var r;let i={kind:`removeTransform`,data:{participantIdentity:n.identity,trackId:e.mediaStreamID}};(r=this.worker)==null||r.postMessage(i)}).on(Y.TrackSubscribed,(e,t,n)=>{this.setupE2EEReceiver(e,n.identity,t.trackInfo)}).on(Y.SignalConnected,()=>{if(!this.room)throw TypeError(`expected room to be present on signal connect`);let e=t.getLatestManuallySetKeyIndex();t.getKeys().forEach(t=>{this.postKey(t,e===(t.keyIndex??0))}),this.setParticipantCryptorEnabled(this.room.localParticipant.isE2EEEnabled,this.room.localParticipant.identity)}),e.localParticipant.on(X.LocalSenderCreated,(e,t)=>J(this,void 0,void 0,function*(){this.setupE2EESender(t,e)})),e.localParticipant.on(X.LocalTrackPublished,e=>{if(!gI(e.track)||!FF())return;let t={kind:`updateCodec`,data:{trackId:e.track.mediaStreamID,codec:tF(e.trackInfo.codecs[0].mimeType),participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:!1}};this.worker.postMessage(t)}),t.on(BI.SetKey,(e,t)=>this.postKey(e,t??!0)).on(BI.RatchetRequest,(e,t)=>this.postRatchetRequest(e,t))}encryptData(e){return J(this,void 0,void 0,function*(){if(!this.worker)throw Error(`could not encrypt data, worker is missing`);let t=crypto.randomUUID(),n={kind:`encryptDataRequest`,data:{uuid:t,payload:e,participantIdentity:this.room.localParticipant.identity}},r=new iI;return r.onFinally=()=>{this.encryptDataRequests.delete(t)},this.encryptDataRequests.set(t,r),this.worker.postMessage(n),r.promise})}handleEncryptedData(e,t,n,r){if(!this.worker)throw Error(`could not handle encrypted data, worker is missing`);let i=crypto.randomUUID(),a={kind:`decryptDataRequest`,data:{uuid:i,payload:e,iv:t,participantIdentity:n,keyIndex:r}},o=new iI;return o.onFinally=()=>{this.decryptDataRequests.delete(i)},this.decryptDataRequests.set(i,o),this.worker.postMessage(a),o.promise}postRatchetRequest(e,t){if(!this.worker)throw Error(`could not ratchet key, worker is missing`);let n={kind:`ratchetRequest`,data:{participantIdentity:e,keyIndex:t}};this.worker.postMessage(n)}postKey(e,t){let n=e.key,r=e.participantIdentity,i=e.keyIndex;if(!this.worker)throw Error(`could not set key, worker is missing`);let a={kind:`setKey`,data:{participantIdentity:r,isPublisher:r===this.room?.localParticipant.identity,key:n,keyIndex:i,updateCurrentKeyIndex:t}};this.worker.postMessage(a)}postEnable(e,t){if(this.worker){let n={kind:`enable`,data:{enabled:e,participantIdentity:t}};this.worker.postMessage(n)}else throw ReferenceError(`failed to enable e2ee, worker is not ready`)}postRTPMap(e){if(!this.worker)throw TypeError(`could not post rtp map, worker is missing`);if(!this.room?.localParticipant.identity)throw TypeError(`could not post rtp map, local participant identity is missing`);let t={kind:`setRTPMap`,data:{map:e,participantIdentity:this.room.localParticipant.identity}};this.worker.postMessage(t)}postSifTrailer(e){if(!this.worker)throw Error(`could not post SIF trailer, worker is missing`);let t={kind:`setSifTrailer`,data:{trailer:e}};this.worker.postMessage(t)}setParticipantCryptorEnabledForPublication(e,t){if(!e.trackInfo){this.log.warn(`skipping e2ee enabled update for publication without trackInfo`,{trackSid:e.trackSid});return}this.setParticipantCryptorEnabled(e.trackInfo.encryption!==pA.NONE,t)}setupE2EEReceiver(e,t,n){if(!e.receiver)return;if(!n?.mimeType||n.mimeType===``)throw TypeError(`MimeType missing from trackInfo, cannot set up E2EE cryptor`);let r=e.kind===`video`&&!!n.packetTrailerFeatures&&n.packetTrailerFeatures.length>0;this.handleReceiver(e.receiver,e.mediaStreamID,t,e.kind===`video`?tF(n.mimeType):void 0,r)}setupE2EESender(e,t){if(!mI(e)||!t){t||this.log.warn(`early return because sender is not ready`);return}this.handleSender(t,e.mediaStreamID,void 0,gI(e)?e.publishOptions?.frameMetadata??e.publishOptions?.packetTrailer:void 0)}handleReceiver(e,t,n,r,i){return J(this,void 0,void 0,function*(){if(this.worker){if(NF()){let a={kind:`decode`,participantIdentity:n,trackId:t,codec:r,hasPacketTrailer:i};e.transform=new RTCRtpScriptTransform(this.worker,a)}else{if(RI in e&&zI in e){let a={kind:`updateCodec`,data:{trackId:t,previousTrackId:e[zI],codec:r,participantIdentity:n,hasPacketTrailer:i}};this.worker.postMessage(a),e[zI]=t;return}let a=e.writableStream,o=e.readableStream;if(!a||!o){let t=e.createEncodedStreams();e.writableStream=t.writable,a=t.writable,e.readableStream=t.readable,o=t.readable}let s={kind:`decode`,data:{readableStream:o,writableStream:a,trackId:t,codec:r,participantIdentity:n,hasPacketTrailer:i}};this.worker.postMessage(s,[o,a])}e[RI]=!0,e[zI]=t}})}handleSender(e,t,n,r){if(!(RI in e||!this.worker)){if(!this.room?.localParticipant.identity||this.room.localParticipant.identity===``)throw TypeError(`local identity needs to be known in order to set up encrypted sender`);if(NF()){this.log.info(`initialize script transform`);let i={kind:`encode`,participantIdentity:this.room.localParticipant.identity,trackId:t,codec:n,hasPacketTrailer:QI(r),packetTrailer:r};e.transform=new RTCRtpScriptTransform(this.worker,i)}else{this.log.info(`initialize encoded streams`);let i=e.createEncodedStreams(),a={kind:`encode`,data:{readableStream:i.readable,writableStream:i.writable,codec:n,trackId:t,participantIdentity:this.room.localParticipant.identity,hasPacketTrailer:QI(r),packetTrailer:r}};this.worker.postMessage(a,[i.readable,i.writable])}e[RI]=!0}}};uL.disposeRegistry=typeof FinalizationRegistry<`u`&&typeof WeakRef<`u`&&new FinalizationRegistry(e=>{e()});var dL=300,fL=class{constructor(){this.metadataMap=new Map,this.activeSsrc=0}storeMetadata(e,t,n){for(this.activeSsrc!==0&&this.activeSsrc!==t&&this.metadataMap.clear(),this.activeSsrc=t;this.metadataMap.size>=dL;){let e=this.metadataMap.keys().next().value;this.metadataMap.delete(e)}this.metadataMap.set(e,n)}lookupMetadata(e){return this.metadataMap.get(e)}dispose(){this.metadataMap.clear(),this.activeSsrc=0}},pL=class{constructor(e){this.extractors=new Map,this.workerPipelines=new Map,this.onWorkerMessage=e=>{let t=e.data;if(t.kind===`metadata`){let e=this.extractors.get(t.data.trackId);e&&e.storeMetadata(t.data.rtpTimestamp,t.data.ssrc,t.data.metadata)}},this.onWorkerError=e=>{DM.error(`frame metadata worker encountered an error:`,{error:e.error})},this.worker=e?.worker}setup(e){e!==this.room&&(this.room=e,this.worker&&(this.worker.onmessage=this.onWorkerMessage,this.worker.onerror=this.onWorkerError,this.worker.postMessage({kind:`init`})),e.on(Y.TrackSubscribed,(e,t,n)=>{e.kind===`video`&&this.setupReceiver(e,t.trackInfo)}).on(Y.TrackUnsubscribed,e=>{this.teardownTrack(e)}).on(Y.Disconnected,()=>{this.cleanup()}))}setupReceiver(e,t){let n=e.receiver;if(!n)return;if(!(t?.packetTrailerFeatures&&t.packetTrailerFeatures.length>0)){this.room?.hasE2EESetup||this.setupPassthroughReceiver(n,e.mediaStreamID);return}if(!ZI(this.worker?{worker:this.worker}:void 0)&&!this.room?.hasE2EESetup){DM.warn(`frame metadata transform not supported; skipping extraction`);return}let r=new fL,i=e.mediaStreamID;this.extractors.set(i,r),e.frameMetadataExtractor=r,!this.room?.hasE2EESetup&&this.setupWorkerReceiver(n,i,!0)}setupPassthroughReceiver(e,t){if(XI()){`transform`in e&&(e.transform=null);return}if(this.worker&&ZI({worker:this.worker})&&!this.workerPipelines.has(e)){this.setupWorkerReceiver(e,t,!1);return}this.worker&&this.workerPipelines.has(e)&&this.setupWorkerReceiver(e,t,!1)}setupWorkerReceiver(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=this.worker;if(!r)return;if(XI()){e.transform=new RTCRtpScriptTransform(r,{kind:`decode`,trackId:t});return}let i=this.workerPipelines.get(e);if(i){let a={kind:`updateTrackId`,data:{oldTrackId:i,newTrackId:t,hasPacketTrailer:n}};r.postMessage(a),this.workerPipelines.set(e,t);return}if(!(`createEncodedStreams`in e)){DM.warn(`createEncodedStreams not supported`);return}let a;try{a=e.createEncodedStreams()}catch(e){DM.warn(`failed to create encoded streams`,{error:e});return}let o={kind:`decode`,data:{readableStream:a.readable,writableStream:a.writable,trackId:t,hasPacketTrailer:n}};r.postMessage(o,[a.readable,a.writable]),this.workerPipelines.set(e,t)}teardownTrack(e){let t=e.mediaStreamID,n=this.extractors.get(t);n&&(n.dispose(),this.extractors.delete(t)),e instanceof oL&&(e.frameMetadataExtractor=void 0)}cleanup(){var e;for(let e of this.extractors.values())e.dispose();this.extractors.clear(),this.workerPipelines.clear(),(e=this.worker)==null||e.terminate()}},mL=500,hL=15e3,gL=class e{constructor(){this.failedConnectionAttempts=new Map,this.backOffPromises=new Map}static getInstance(){return this._instance||=new e,this._instance}addFailedConnectionAttempt(e){let t=UF(new URL(e));if(!t)return;let n=this.failedConnectionAttempts.get(t)??0;this.failedConnectionAttempts.set(t,n+1),this.backOffPromises.set(t,vF(Math.min(mL*2**n,hL)))}getBackOffPromise(e){let t=new URL(e),n=t&&UF(t);return n&&this.backOffPromises.get(n)||Promise.resolve()}resetFailedConnectionAttempts(e){let t=new URL(e),n=t&&UF(t);n&&(this.failedConnectionAttempts.set(n,0),this.backOffPromises.set(n,Promise.resolve()))}resetAll(){this.backOffPromises.clear(),this.failedConnectionAttempts.clear()}};gL._instance=null;var _L=`default`,vL=class e{constructor(){this._previousDevices=[]}static getInstance(){return this.instance===void 0&&(this.instance=new e),this.instance}get previousDevices(){return this._previousDevices}getDevices(t){return J(this,arguments,void 0,function(t){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){if(e.userMediaPromiseMap?.size>0){DM.debug(`awaiting getUserMedia promise`);try{t?yield e.userMediaPromiseMap.get(t):yield Promise.all(e.userMediaPromiseMap.values())}catch{DM.warn(`error waiting for media permissons`)}}let i=yield navigator.mediaDevices.enumerateDevices();if(r&&!(PF()&&n.hasDeviceInUse(t))&&(i.filter(e=>e.kind===t).length===0||i.some(e=>{let n=e.label===``,r=!t||e.kind===t;return n&&r}))){let e={video:t!==`audioinput`&&t!==`audiooutput`,audio:t!==`videoinput`&&{deviceId:{ideal:`default`}}},n=yield navigator.mediaDevices.getUserMedia(e);i=yield navigator.mediaDevices.enumerateDevices(),n.getTracks().forEach(e=>{e.stop()})}return n._previousDevices=i,t&&(i=i.filter(e=>e.kind===t)),i}()})}normalizeDeviceId(e,t,n){return J(this,void 0,void 0,function*(){if(t!==_L)return t;let r=yield this.getDevices(e),i=r.find(e=>e.deviceId===_L);if(!i){DM.warn(`could not reliably determine default device`);return}let a=r.find(e=>e.deviceId!==_L&&e.groupId===(n??i.groupId));if(!a){DM.warn(`could not reliably determine default device`);return}return a?.deviceId})}hasDeviceInUse(t){return t?e.userMediaPromiseMap.has(t):e.userMediaPromiseMap.size>0}};vL.mediaDeviceKinds=[`audioinput`,`audiooutput`,`videoinput`],vL.userMediaPromiseMap=new Map;var yL=65535,bL=4294967295,xL=class e{static u16(t){return new e(t,yL)}static u32(t){return new e(t,bL)}constructor(e,t){if(this.value=e,e<0)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer smaller than 0`);if(t>2**53-1)throw Error(`WrapAroundUnsignedInt: cannot faithfully represent an integer bigger than MAX_SAFE_INTEGER.`);this.maxSize=t,this.clamp()}clamp(){for(;this.value>this.maxSize;)this.value-=this.maxSize+1;for(;this.value<0;)this.value+=this.maxSize+1}clone(){return new e(this.value,this.maxSize)}update(e){this.value=e(this.value),this.clamp()}increment(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t+e)}decrement(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:1;this.update(t=>t-e)}getThenIncrement(){let t=this.value;return this.increment(),new e(t,this.maxSize)}isBefore(e){let t=this.value>>>0,n=(e.value>>>0)-t>>>0;return n!==0&&n<this.maxSize+1}},SL=class e{static fromRtpTicks(t){return new e(t,9e4)}static rtpRandom(){let t=Math.round(Math.random()*bL);return e.fromRtpTicks(t)}constructor(e,t){this.timestamp=xL.u32(e),this.rateInHz=t}asTicks(){return this.timestamp.value}clone(){return new e(this.timestamp.value,this.rateInHz)}wrappingAdd(e){this.timestamp.increment(e)}isBefore(e){return this.timestamp.isBefore(e.timestamp)}},CL=class e{constructor(e,t,n){this.epoch=t,this.base=n,this.previous=n.clone(),this.rateInHz=e}static startingNow(t,n){return new e(n,new Date,t)}static startingAtTime(t,n,r){return new e(r,t,n)}static rtpStartingNow(t){return e.startingNow(t,9e4)}static rtpStartingAtTime(t,n){return e.startingAtTime(t,n,9e4)}now(){return this.at(new Date)}at(t){let n=t.getTime()-this.epoch.getTime(),r=e.durationInMsToTicks(n,this.rateInHz),i=this.base.clone();return i.wrappingAdd(r),i.isBefore(this.previous)&&(i=this.previous),this.previous=i.clone(),i.clone()}static durationInMsToTicks(e,t){let n=(e*1e6*t+5e8)/1e9;return Math.round(n)}};function wL(e){if(e instanceof DataView)return e;if(e instanceof ArrayBuffer)return new DataView(e);if(e instanceof Uint8Array)return new DataView(e.buffer,e.byteOffset,e.byteLength);throw Error(`Error coercing ${e} to DataView - input was not DataView, ArrayBuffer, or Uint8Array.`)}var TL;(function(e){e[e.Reserved=0]=`Reserved`,e[e.TooLarge=1]=`TooLarge`})(TL||={});var EL=class e extends mP{constructor(e,t){super(19,e),this.name=`DataTrackHandleError`,this.reason=t,this.reasonName=TL[t]}isReason(e){return this.reason===e}static tooLarge(){return new e(`Value too large to be a valid track handle`,TL.TooLarge)}static reserved(t){return new e(`0x${t.toString(16)} is a reserved value.`,TL.Reserved)}},DL={fromNumber(e){if(e===0)throw EL.reserved(e);if(e>yL)throw EL.tooLarge();return e}},OL=class{constructor(){this.value=0}get(){return this.value+=1,this.value>yL?null:this.value}reset(){this.value=0}},kL={from(e){return{sid:e.sid,pubHandle:e.pubHandle,name:e.name,usesE2ee:e.encryption!==pA.NONE}},toProtobuf(e){return new gA({sid:e.sid,pubHandle:e.pubHandle,name:e.name,encryption:e.usesE2ee?pA.GCM:pA.NONE})}},AL;(function(e){e[e.WAITING=0]=`WAITING`,e[e.RUNNING=1]=`RUNNING`,e[e.COMPLETED=2]=`COMPLETED`})(AL||={});var jL=class{constructor(){this.pendingTasks=new Map,this.taskMutex=new jD,this.nextTaskIndex=0}run(e){return J(this,void 0,void 0,function*(){let t={id:this.nextTaskIndex++,enqueuedAt:Date.now(),status:AL.WAITING};this.pendingTasks.set(t.id,t);let n=yield this.taskMutex.lock();try{return t.executedAt=Date.now(),t.status=AL.RUNNING,yield e()}finally{t.status=AL.COMPLETED,this.pendingTasks.delete(t.id),n()}})}flush(){return J(this,void 0,void 0,function*(){return this.run(()=>J(this,void 0,void 0,function*(){}))})}snapshot(){return Array.from(this.pendingTasks.values())}},ML=[`client`],NL=class{constructor(){gO(this,`listeners`,new Map)}on(e,t){let n=this.listeners.get(e);return n||(n=new Set,this.listeners.set(e,n)),n.add(t),{off:()=>{n.delete(t)}}}emit(e,t){let n=this.listeners.get(`*`);if(n)for(let r of n)r(e,t);let r=this.listeners.get(e);if(r)for(let e of r)e(t)}clear(){this.listeners.clear()}},PL=class extends Error{constructor(e,t){super(`non-serializable value at ${e} (${t})`),this.path=e,this.label=t}},FL=(e,t)=>IL(e,t,new Set),IL=(e,t,n)=>{if(e===null)return null;switch(typeof e){case`string`:case`boolean`:return e;case`number`:if(!Number.isFinite(e))throw new PL(t,RL(e));return e;case`object`:return LL(e,t,n);default:throw new PL(t,typeof e)}},LL=(e,t,n)=>{if(n.has(e))throw new PL(t,`circular reference`);if(Array.isArray(e)){if(e.length!==Object.keys(e).length)throw new PL(t,`sparse array or array with non-index properties`);n.add(e);let r=e.map((e,r)=>IL(e,`${t}[${r}]`,n));return n.delete(e),r}let r=Object.getPrototypeOf(e);if(r!==Object.prototype&&r!==null)throw new PL(t,e.constructor?.name??`object`);n.add(e);let i={};for(let r of Object.keys(e)){let a=IL(e[r],`${t}.${r}`,n);Object.defineProperty(i,r,{value:a,enumerable:!0,writable:!0,configurable:!0})}return n.delete(e),i},RL=e=>Number.isNaN(e)?`NaN`:e>0?`Infinity`:`-Infinity`,zL=function(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:new Set;if(typeof e!=`object`||!e||t.has(e))return e;if(Array.isArray(e)){t.add(e);let n=e.map(e=>zL(e,t));return t.delete(e),n}let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)return e;t.add(e);let r={};for(let n of Object.keys(e)){let i=zL(e[n],t);Object.defineProperty(r,n,{value:i,enumerable:!0,writable:!0,configurable:!0})}return t.delete(e),r},BL=Symbol(`machina.type`),VL=20,HL=class{constructor(e){gO(this,`id`,void 0),gO(this,`initialState`,void 0),gO(this,BL,`BehavioralFsm`),gO(this,`states`,void 0),gO(this,`emitter`,new NL),gO(this,`clients`,new WeakMap),gO(this,`knownClients`,new Set),gO(this,`childSubscriptions`,[]),gO(this,`disposed`,!1),gO(this,`transitionDepth`,0),this.id=e.id,this.initialState=e.initialState,this.states=e.states,this.wrapChildLinks(),this.setupChildSubscriptions()}handle(e,t){if(this.disposed)return;let n=this.getOrCreateClientMeta(e);var r=[...arguments].slice(2);n.currentActionArgs=r;let i=this.states[n.state]?._child;if(i&&i.canHandle(e,t)){try{i.handle(e,t,...r)}finally{n.currentActionArgs=void 0}return}this.handleLocally(e,t,r,n)}canHandle(e,t){if(this.disposed)return!1;let n=this.clients.get(e)?.state??this.initialState,r=this.states[n];if(r?.[t]??r?.[`*`])return!0;let i=r?._child;return i?i.canHandle(e,t):!1}reset(e){this.disposed||this.transition(e,this.initialState)}currentState(e){return this.clients.get(e)?.state}transition(e,t){if(this.disposed)return;let n=this.getOrCreateClientMeta(e),r=n.state;if(t!==r){if(!Object.hasOwn(this.states,t)){this.emitter.emit(`invalidstate`,{stateName:t,client:e});return}if(this.transitionDepth++,this.transitionDepth>VL)throw this.transitionDepth=0,Error(`Max transition depth (${VL}) exceeded in FSM "${this.id}". Likely an infinite _onEnter → transition loop.`);try{let i=this.states[r],a=this.states[t];if(i!=null&&i._onExit&&typeof i._onExit==`function`){let t=this.buildHandlerArgs(e,``,n);i._onExit(t)}n.state=t;let o={fromState:r,toState:t,client:e};this.emitter.emit(`transitioning`,o);let s;if(a!=null&&a._onEnter&&typeof a._onEnter==`function`){let t=this.buildHandlerArgs(e,``,n);s=a._onEnter(t)}this.emitter.emit(`transitioned`,o);let c=a?._child;c&&c.reset(e),this.processQueue(e,n),typeof s==`string`&&n.state===t&&this.transition(e,s)}finally{this.transitionDepth--}}}compositeState(e){let t=this.clients.get(e);if(!t)return``;let n=this.states[t.state]?._child;if(n){let r=n.compositeState(e);if(r)return`${t.state}.${r}`}return t.state}rehydrate(e,t){if(this.disposed)return;if(typeof t==`string`){this.rehydrateCompositePath(e,t);return}let n=this.planSnapshotWrites(e,t);for(let e of n)e()}dehydrate(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0,n=this.clients.get(e);if(!n)return;let r={state:n.state,deferred:n.deferredQueue.map(e=>this.snapshotDeferredInput(e))},i=this.collectChildSnapshots(e,n.state,t);return i&&(r.children=i),r}planSnapshotWrites(e,t){if(this.disposed)return[];let n=t.state,r=t.deferred,i=t.children;if(!Object.hasOwn(this.states,n))throw Error(`rehydrate: unknown state "${n}" in FSM "${this.id}". Valid states: ${Object.keys(this.states).join(`, `)}`);let a=[];if(i)for(let t of Object.keys(i)){if(!Object.hasOwn(this.states,t))throw Error(`rehydrate: unknown state "${t}" in FSM "${this.id}" referenced by snapshot.children.`);let n=this.states[t]?._child;if(!n)throw Error(`rehydrate: state "${t}" in FSM "${this.id}" has no _child, but the snapshot has a children["${t}"] entry.`);a.push(...n.planRehydrate(e,i[t]))}let o=r.map(e=>xO({inputName:e.inputName,args:zL(e.args)},e.untilState===void 0?{}:{untilState:e.untilState}));return a.push(()=>{this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:n,deferredQueue:o})}),a}rehydrateCompositePath(e,t){let n=TO(t.split(`.`)),r=n[0],i=mO(n).slice(1);if(!Object.hasOwn(this.states,r))throw Error(`rehydrate: unknown state "${r}" in FSM "${this.id}". Valid states: ${Object.keys(this.states).join(`, `)}`);if(i.length>0){let n=i.join(`.`),a=this.states[r]?._child;if(!a)throw Error(`rehydrate: state "${r}" in FSM "${this.id}" has no _child, but composite path "${t}" requires one.`);a.rehydrate(e,n)}this.clients.has(e)||this.knownClients.add(new WeakRef(e)),this.clients.set(e,{state:r,deferredQueue:[]})}collectChildSnapshots(e,t,n){let r=new Map;for(let e of Object.keys(this.states)){let t=this.states[e]?._child;if(!t)continue;let n=r.get(t.instance);n?n.stateNames.push(e):r.set(t.instance,{childLink:t,stateNames:[e]})}let i;for(let a of r.values()){let r=a.childLink,o=a.stateNames,s=n&&o.includes(t);if(r.instance[BL]===`Fsm`&&!s)continue;let c=r.dehydrate(e,s);if(c){i??={};for(let e of o)i[e]=c}}return i}snapshotDeferredInput(e){let t;try{t=FL(e.args,`args`)}catch(t){if(!(t instanceof PL))throw t;let n=e.untilState?` (until "${e.untilState}")`:``;throw Error(`dehydrate: deferred input "${e.inputName}"${n} in FSM "${this.id}" has a non-serializable value at ${t.path} (${t.label})`)}let n={inputName:e.inputName,args:t};return e.untilState!==void 0&&(n.untilState=e.untilState),n}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.emitter.emit(e,t)}dispose(e){this.disposed=!0;for(let e of this.childSubscriptions)e.off();if(!(e!=null&&e.preserveChildren)){let e=new Set;for(let t of Object.keys(this.states)){let n=this.states[t]?._child;n&&!e.has(n.instance)&&(e.add(n.instance),n.dispose())}}this.emitter.clear()}wrapChildLinks(){for(let e of Object.keys(this.states)){let t=this.states[e],n=t?._child;if(n){if(typeof n!=`object`)throw Error(`State "${e}"._child: expected an Fsm or BehavioralFsm instance, got ${String(n)}`);if(!(BL in n))throw Error(`State "${e}"._child: expected an Fsm or BehavioralFsm instance, got a plain object`);t._child=UL(n)}}}setupChildSubscriptions(){let e=new Set;for(let t of Object.keys(this.states)){let n=this.states[t]?._child;if(!n||e.has(n.instance))continue;e.add(n.instance);let r=n.onAny((e,t)=>{if(e===`nohandler`){let e=t;if(e.client!==void 0)this.bubbleNohandler(e.client,n,e.inputName,e.args??[]);else for(let t of this.knownClients){let r=t.deref();if(r===void 0){this.knownClients.delete(t);continue}this.bubbleNohandler(r,n,e.inputName,e.args??[])}return}let r=t;if(r&&typeof r==`object`&&`client`in r)this.isChildActiveForClient(r.client,n)&&this.emitter.emit(e,t);else for(let r of this.knownClients){let i=r.deref();if(!i){this.knownClients.delete(r);continue}if(this.isChildActiveForClient(i,n)){this.emitter.emit(e,t);break}}});this.childSubscriptions.push(r)}}bubbleNohandler(e,t,n,r){if(!this.isChildActiveForClient(e,t))return;let i=this.clients.get(e);i.currentActionArgs=r,this.handleLocally(e,n,r,i)}isChildActiveForClient(e,t){var n;let r=this.clients.get(e);return r?((n=this.states[r.state])==null||(n=n._child)==null?void 0:n.instance)===t.instance:!1}handleLocally(e,t,n,r){let i=this.states[r.state],a=i?.[t]??i?.[`*`];if(!a){this.emitter.emit(`nohandler`,{inputName:t,args:n,client:e}),r.currentActionArgs=void 0;return}try{this.emitter.emit(`handling`,{inputName:t,client:e});let i=this.buildHandlerArgs(e,t,r),o;typeof a==`string`?o=a:typeof a==`function`&&(o=a(i,...n)),this.emitter.emit(`handled`,{inputName:t,client:e}),typeof o==`string`&&this.transition(e,o)}finally{r.currentActionArgs=void 0}}getOrCreateClientMeta(e){let t=this.clients.get(e);return t||(t={state:void 0,deferredQueue:[]},this.clients.set(e,t),this.knownClients.add(new WeakRef(e)),this.transition(e,this.initialState),t)}buildHandlerArgs(e,t,n){return{ctx:e,inputName:t,defer:r=>{if(!n.currentActionArgs)return;let i={inputName:t,args:[...n.currentActionArgs],untilState:r?.until};n.deferredQueue.push(i),this.emitter.emit(`deferred`,{inputName:t,client:e})},emit:(e,t)=>{this.emitter.emit(e,t)}}}processQueue(e,t){let n=[],r=[];for(let e of t.deferredQueue)e.untilState===void 0||e.untilState===t.state?n.push(e):r.push(e);t.deferredQueue=r;for(let t of n)this.handle(e,t.inputName,...t.args)}};function UL(e){if(!e||typeof e!=`object`)throw Error(`createChildLink: expected an Fsm or BehavioralFsm instance, got ${String(e)}`);let t=e[BL];if(t===`BehavioralFsm`)return{instance:e,canHandle(t,n){return e.canHandle(t,n)},handle(t,n){var r=[...arguments].slice(2);e.handle(t,n,...r)},reset(t){e.transition(t,e.initialState)},onAny(t){return e.on(`*`,t)},compositeState(t){return e.compositeState(t)},rehydrate(t,n){e.rehydrate(t,n)},dehydrate(t,n){return e.dehydrate(t,n)},planRehydrate(t,n){return e.planSnapshotWrites(t,n)},dispose(){e.dispose()}};if(t===`Fsm`)return{instance:e,canHandle(t,n){return e.canHandle(n)},handle(t,n){var r=[...arguments].slice(2);e.handle(n,...r)},reset(t){e.reset()},onAny(t){return e.on(`*`,t)},compositeState(t){return e.compositeState()},rehydrate(e,t){throw Error(`rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.`)},dehydrate(e,t){throw Error(`dehydrate: cannot dehydrate an Fsm child. Fsm owns its own context; dehydrate is only valid for BehavioralFsm hierarchies.`)},planRehydrate(e,t){throw Error(`rehydrate: cannot rehydrate an Fsm child. Fsm owns its own context; rehydrate is only valid for BehavioralFsm hierarchies.`)},dispose(){e.dispose()}};throw Error(`createChildLink: expected an Fsm or BehavioralFsm instance, got [MACHINA_TYPE] = ${String(t??`undefined`)}`)}var WL=class{constructor(e){gO(this,`id`,void 0),gO(this,`initialState`,void 0),gO(this,BL,`Fsm`),gO(this,`states`,void 0),gO(this,`bfsm`,void 0),gO(this,`context`,void 0),gO(this,`emitter`,new NL),gO(this,`disposed`,!1),this.id=e.id,this.initialState=e.initialState,this.context=e.context??{},this.bfsm=new HL(e),this.states=e.states,this.bfsm.on(`*`,(e,t)=>{if(t&&typeof t==`object`&&`client`in t){t.client;let n=SO(t,ML);this.emitter.emit(e,n)}else this.emitter.emit(e,t)}),this.bfsm.transition(this.context,e.initialState)}handle(e){if(!this.disposed){var t=[...arguments].slice(1);this.bfsm.handle(this.context,e,...t)}}canHandle(e){return!this.disposed&&this.bfsm.canHandle(this.context,e)}reset(){this.disposed||this.bfsm.reset(this.context)}currentState(){return this.bfsm.currentState(this.context)}transition(e){this.disposed||this.bfsm.transition(this.context,e)}compositeState(){return this.bfsm.compositeState(this.context)}on(e,t){return this.disposed?{off(){}}:this.emitter.on(e,t)}emit(e,t){this.disposed||this.bfsm.emit(e,t)}dispose(e){this.disposed=!0,this.bfsm.dispose(e),this.emitter.clear()}};function GL(e){return new WL(e)}function KL(e){return e}function qL(e,t){return t.attemptId===e.attemptId}var JL=KL((e,t)=>{let n=e.ctx;if(qL(n,t))return`connected`}),YL=KL(e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,`connecting`}),XL=KL(e=>{let t=e.ctx;return t.attemptId+=1,t.lastError=void 0,`reconnecting`}),ZL=KL((e,t)=>{let n=e.ctx;return n.closeReason=t.reason,`disconnecting`}),QL={new:{connect:YL,close:ZL},connecting:{connectComplete:JL,connectFailed:KL((e,t)=>{let n=e.ctx;return n.lastError=t.error,`closed`}),close:ZL},connected:{reconnect:XL,transportFailed:KL((e,t)=>{let n=e.ctx;if(qL(n,t))return n.lastError=t.reason,`offline`}),close:ZL},offline:{connect:YL,reconnect:XL,close:ZL},reconnecting:{reconnectComplete:JL,reconnectFailed:KL((e,t)=>{let n=e.ctx;return n.lastError=t.error,t.recoverable?`offline`:`closed`}),close:ZL},disconnecting:{closeComplete:`closed`},closed:{connect:YL,reconnect:XL}};function $L(){return GL({id:`signal`,initialState:arguments.length>0&&arguments[0]!==void 0?arguments[0]:`new`,context:{attemptId:0},states:QL})}var eR=class{get readyState(){return this.ws.readyState}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};if(t.signal?.aborted)throw new DOMException(`This operation was aborted`,`AbortError`);this.url=e;let n=new WebSocket(e,t.protocols??[]);n.binaryType=`arraybuffer`,this.ws=n;let r=function(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{},t=e.closeCode,r=e.reason;return n.close(t,r)};this.opened=new aP((e,t)=>{let i=()=>{t(gP.websocket(`Encountered websocket error during connection establishment`))};n.onopen=()=>{e({readable:new ReadableStream({start(e){n.onmessage=t=>{let n=t.data;return e.enqueue(n)},n.onerror=t=>e.error(gP.websocket(LI(t,`websocket`))),n.onclose=t=>{t.wasClean||t.code===1e3?e.close():e.error(gP.websocket(`WS closed unexpectedly with code ${t.code}`))}},cancel:r}),writable:new WritableStream({write(e){n.send(e)},abort(){n.close()},close:r}),protocol:n.protocol,extensions:n.extensions}),n.removeEventListener(`error`,i)},n.addEventListener(`error`,i)}),this.closed=new aP((e,t)=>{let r=()=>J(this,void 0,void 0,function*(){let r=new aP(e=>{n.readyState!==WebSocket.CLOSED&&n.addEventListener(`close`,t=>{e(t)},{once:!0})}),i=yield aP.race([vF(250),r]);i?e(i):t(gP.websocket(`Encountered unspecified websocket error without a timely close event`))});n.addEventListener(`close`,t=>{let i=t.code,a=t.reason;e({closeCode:i,reason:a}),n.removeEventListener(`error`,r)}),n.addEventListener(`error`,r)}),t.signal&&(t.signal.onabort=()=>n.close()),this.close=r}},tR=[`syncState`,`trickle`,`offer`,`answer`,`simulate`,`leave`];function nR(e){return e instanceof gP?e.reason!==hP.LeaveRequest&&e.reason!==hP.NotAllowed:!0}function rR(e){let t=tR.indexOf(e.case)>=0;return DM.trace(`request allowed to bypass queue:`,{canPass:t,req:e}),t}var iR;(function(e){e[e.CONNECTING=0]=`CONNECTING`,e[e.CONNECTED=1]=`CONNECTED`,e[e.RECONNECTING=2]=`RECONNECTING`,e[e.DISCONNECTING=3]=`DISCONNECTING`,e[e.DISCONNECTED=4]=`DISCONNECTED`})(iR||={});function aR(e){switch(e){case`connected`:return iR.CONNECTED;case`connecting`:return iR.CONNECTING;case`reconnecting`:return iR.RECONNECTING;case`disconnecting`:return iR.DISCONNECTING;default:return iR.DISCONNECTED}}var oR=250,sR=5e3,cR=class{get currentState(){return aR(this.lifecycleState)}get isDisconnected(){let e=this.currentState;return e===iR.DISCONNECTING||e===iR.DISCONNECTED}get lifecycleState(){return this.machine.currentState()}get attemptId(){return this.machine.context.attemptId}sendLifecycleInput(e){let t=this.lifecycleState;return this.machine.handle(e.type,e),this.lifecycleState!==t}settleInFlightClose(){return J(this,void 0,void 0,function*(){this.log.debug(`waiting for an in-flight close to settle before establishing a session`),(yield this.closingLock.lock())()})}get isEstablishingConnection(){return this.lifecycleState===`connecting`||this.lifecycleState===`reconnecting`}getNextRequestId(){return this._requestId+=1,this._requestId}constructor(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0],t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};this.rtt=0,this.log=DM,this._requestId=0,this.useV0SignalPath=!1,this.resetCallbacks=()=>{this.onAnswer=void 0,this.onLeave=void 0,this.onLocalTrackPublished=void 0,this.onLocalTrackUnpublished=void 0,this.onNegotiateRequested=void 0,this.onOffer=void 0,this.onRemoteMuteChanged=void 0,this.onSubscribedQualityUpdate=void 0,this.onTokenRefresh=void 0,this.onTrickle=void 0,this.onClose=void 0,this.onMediaSectionsRequirement=void 0},this.loggerContextCb=t.loggerContextCb,this.log=OM(t.loggerName??EM.Signal,()=>this.logContext),this.useJSON=e,this.requestQueue=new jL,this.queuedRequests=[],this.closingLock=new jD,this.connectionLock=new jD,this.machine=$L(),this.machine.on(`transitioned`,e=>{let t=e.fromState,n=e.toState;this.log.debug(`signal lifecycle: ${t} -> ${n}`)}),this.machine.on(`nohandler`,e=>{let t=e.inputName;this.log.debug(`ignoring signal lifecycle input ${t} in state ${this.lifecycleState}`)}),this.machine}get logContext(){return this.loggerContextCb?.call(this)??{}}join(e,t,n,r){return J(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0&&arguments[4],o=arguments.length>5?arguments[5]:void 0;return function*(){if(i.lifecycleState===`disconnecting`&&(yield i.settleInFlightClose()),!i.sendLifecycleInput({type:`connect`}))throw gP.internal(`cannot establish a signal session from '${i.lifecycleState}', close the current one first`);i.options=n;try{return yield i.connect(e,t,n,r,a,o)}catch(e){throw i.sendLifecycleInput({type:`connectFailed`,error:e}),e}}()})}reconnect(e,t,n,r){return J(this,void 0,void 0,function*(){if(!this.options){this.log.warn(`attempted to reconnect without signal options being set, ignoring`);return}if(this.lifecycleState===`disconnecting`&&(yield this.settleInFlightClose()),!this.sendLifecycleInput({type:`reconnect`}))throw gP.internal(`cannot resume the signal session from '${this.lifecycleState}'`);this.clearPingInterval();try{return yield this.connect(e,t,Object.assign(Object.assign({},this.options),{reconnect:!0,sid:n,reconnectReason:r}),void 0,this.useV0SignalPath)}catch(e){throw this.sendLifecycleInput({type:`reconnectFailed`,error:e,recoverable:nR(e)}),e}})}connect(e,t,n,r){return J(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0&&arguments[4],o=arguments.length>5?arguments[5]:void 0;return function*(){let s=yield i.connectionLock.lock();i.connectOptions=n,i.useV0SignalPath=a;let c=eI(n.clientInfoCapabilities),l=AI(e,a?dR(t,c,n):yield fR(t,c,n,o),a).toString(),u=MI(l).toString();return new Promise((e,t)=>J(i,void 0,void 0,function*(){try{let i=!1,a=e=>J(this,void 0,void 0,function*(){if(i)return;i=!0;let n=II(e instanceof Event?e.currentTarget:e,`Abort handler called`);this.streamWriter&&!this.isDisconnected?this.sendLeave().then(()=>this.close(n)).catch(e=>{this.log.error(e),this.close()}):this.close(),o(),t(e instanceof gP?e:gP.cancelled(n))});r?.addEventListener(`abort`,a);let o=()=>{clearTimeout(s),r?.removeEventListener(`abort`,a)},s=setTimeout(()=>{a(gP.timeout(`room connection has timed out (signal)`))},n.websocketTimeout),c=new URL(l);if(c.searchParams.has(`access_token`)&&c.searchParams.set(`access_token`,`<redacted>`),this.ws){let e=performance.now();yield this.teardownTransport(`replaced by a new connection attempt`),this.log.debug(`closed previous ws connection in ${performance.now()-e}ms`)}let d=this.attemptId;this.log.info(`signal connecting to ${c}`,{reconnect:n.reconnect,reconnectReason:n.reconnectReason}),this.ws=new eR(l);let f=!1;this.ws.opened.catch(()=>{f=!0});try{this.ws.closed.then(e=>{this.isEstablishingConnection&&!f&&t(gP.internal(`Websocket got closed during a (re)connection attempt: ${e.reason}`)),this.log.debug(`websocket closed`,{reason:e.reason,code:e.closeCode,attemptId:d,state:this.lifecycleState}),this.handleOnClose(e.reason||(e.closeCode===1e3?`server closed the signal connection`:`Unexpected WS error`),d)}).catch(e=>{this.isEstablishingConnection&&!f&&t(gP.internal(`Websocket error during a (re)connection attempt: ${e}`))});let r=yield this.ws.opened.catch(e=>J(this,void 0,void 0,function*(){if(this.lifecycleState!==`connected`){clearTimeout(s),t(yield this.handleConnectionError(e,u));return}this.handleWSError(e),t(e)}));if(clearTimeout(s),!r)return;let i=r.readable.getReader();this.streamWriter=r.writable.getWriter();let a,o;try{a=yield Promise.race([i.read(),new Promise((e,t)=>{o=setTimeout(()=>{t(gP.timeout(`signal connection timed out while waiting for the first message`))},sR)})])}catch(e){i.releaseLock(),t(e),this.close();return}finally{clearTimeout(o)}if(i.releaseLock(),!a.value)throw gP.internal(`no message received as first message`);let c=FI(a.value),l=this.validateFirstMessage(c,n.reconnect??!1);if(!l.isValid){t(l.error);return}c.message?.case===`join`&&(this.pingTimeoutDuration=c.message.value.pingTimeout,this.pingIntervalDuration=c.message.value.pingInterval,this.pingTimeoutDuration&&this.pingTimeoutDuration>0&&this.log.debug(`ping config`,{timeout:this.pingTimeoutDuration,interval:this.pingIntervalDuration}),this.onJoined&&this.onJoined(c.message.value));let p=l.shouldProcessFirstMessage?c:void 0;this.handleSignalConnected(r,s,d,p),e(l.response)}catch(e){t(e)}finally{o()}}finally{s()}}))}()})}startReadingLoop(e,t){return J(this,void 0,void 0,function*(){t&&this.handleSignalResponse(t);let n=this.attemptId;for(;;){this.signalLatency&&(yield vF(this.signalLatency));try{let t=yield e.read(),n=t.done,r=t.value;if(n)break;let i=FI(r);this.handleSignalResponse(i)}catch(e){this.log.error(`error reading from signal stream`,{error:e}),yield this.handleOnClose(`error in reading loop`,n);break}}})}close(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:`Close method called on signal client`;return function*(){let r=t&&e.sendLifecycleInput({type:`close`,reason:n}),i=yield e.closingLock.lock();try{yield e.teardownTransport(n)}finally{r&&e.sendLifecycleInput({type:`closeComplete`}),i()}}()})}teardownTransport(e){return J(this,void 0,void 0,function*(){try{if(this.clearPingInterval(),this.ws){this.ws.close({closeCode:1e3,reason:e});let t=this.ws.closed;this.ws=void 0,this.streamWriter=void 0,yield Promise.race([t,vF(oR)])}}catch(e){this.log.debug(`websocket error while closing`,{error:e})}})}sendOffer(e,t){this.log.debug(`sending offer`,{offerSdp:e.sdp}),this.sendRequest({case:`offer`,value:uR(e,t)})}sendAnswer(e,t){return this.log.debug(`sending answer`,{answerSdp:e.sdp}),this.sendRequest({case:`answer`,value:uR(e,t)})}sendIceCandidate(e,t){return this.log.debug(`sending ice candidate`,{candidate:e}),this.sendRequest({case:`trickle`,value:new yj({candidateInit:JSON.stringify(e),target:t})})}sendMuteTrack(e,t){return this.sendRequest({case:`mute`,value:new bj({sid:e,muted:t})})}sendAddTrack(e){return this.sendRequest({case:`addTrack`,value:e})}sendUpdateLocalMetadata(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{};return function*(){let i=n.getNextRequestId();return yield n.sendRequest({case:`updateMetadata`,value:new Bj({requestId:i,metadata:e,name:t,attributes:r})}),i}()})}sendUpdateTrackSettings(e){this.sendRequest({case:`trackSetting`,value:e})}sendUpdateSubscription(e){return this.sendRequest({case:`subscription`,value:e})}sendSyncState(e){return this.sendRequest({case:`syncState`,value:e})}sendUpdateVideoLayers(e,t){return this.sendRequest({case:`updateLayers`,value:new zj({trackSid:e,layers:t})})}sendUpdateSubscriptionPermissions(e,t){return this.sendRequest({case:`subscriptionPermission`,value:new $j({allParticipants:e,trackPermissions:t})})}sendSimulateScenario(e){return this.sendRequest({case:`simulate`,value:e})}sendPing(){return Promise.all([this.sendRequest({case:`ping`,value:cO.parse(Date.now())}),this.sendRequest({case:`pingReq`,value:new oM({timestamp:cO.parse(Date.now()),rtt:cO.parse(this.rtt)})})])}sendUpdateLocalAudioTrack(e,t){return this.sendRequest({case:`updateAudioTrack`,value:new Fj({trackSid:e,features:t})})}sendLeave(){return this.sendRequest({case:`leave`,value:new Lj({reason:tA.CLIENT_INITIATED,action:Rj.DISCONNECT})})}sendPublishDataTrackRequest(e,t,n){return this.sendRequest({case:`publishDataTrackRequest`,value:new pj({pubHandle:e,name:t,encryption:n?pA.GCM:pA.NONE})})}sendUnPublishDataTrackRequest(e){return this.sendRequest({case:`unpublishDataTrackRequest`,value:new hj({pubHandle:e})})}sendUpdateDataSubscription(e,t){return this.sendRequest({case:`updateDataSubscription`,value:new Oj({updates:[new kj({trackSid:e,subscribe:t})]})})}sendRequest(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0&&arguments[1];return function*(){let r=!n&&!rR(e),i=t.lifecycleState===`reconnecting`||t.queuedRequests.length>0;if(r&&i){t.queuedRequests.push(()=>J(t,void 0,void 0,function*(){yield this.sendRequest(e,!0)}));return}n||(yield t.requestQueue.flush()),t.signalLatency&&(yield vF(t.signalLatency));let a=e.case===`leave`&&!!t.streamWriter;if(t.isDisconnected&&!a){t.log.debug(`skipping signal request (type: ${e.case}) - SignalClient disconnected`);return}if(!t.streamWriter){t.log.error(`cannot send signal request before connected, type: ${e?.case}`);return}let o=new lj({message:e});try{t.useJSON?yield t.streamWriter.write(o.toJsonString()):yield t.streamWriter.write(o.toBinary().buffer)}catch(e){t.log.error(`error sending signal message`,{error:e})}}()})}handleSignalResponse(e){let t=e.message;if(t==null){this.log.debug(`received unsupported message`);return}let n=!1;if(t.case===`answer`){let e=lR(t.value);this.onAnswer&&this.onAnswer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`offer`){let e=lR(t.value);this.onOffer&&this.onOffer(e,t.value.id,t.value.midToTrackId)}else if(t.case===`trickle`){let e=JSON.parse(t.value.candidateInit);this.onTrickle&&this.onTrickle(e,t.value.target)}else t.case===`update`?this.onParticipantUpdate&&this.onParticipantUpdate(t.value.participants??[]):t.case===`trackPublished`?this.onLocalTrackPublished&&this.onLocalTrackPublished(t.value):t.case===`speakersChanged`?this.onSpeakersChanged&&this.onSpeakersChanged(t.value.speakers??[]):t.case===`leave`?this.onLeave&&this.onLeave(t.value):t.case===`mute`?this.onRemoteMuteChanged&&this.onRemoteMuteChanged(t.value.sid,t.value.muted):t.case===`roomUpdate`?this.onRoomUpdate&&t.value.room&&this.onRoomUpdate(t.value.room):t.case===`connectionQuality`?this.onConnectionQuality&&this.onConnectionQuality(t.value):t.case===`streamStateUpdate`?this.onStreamStateUpdate&&this.onStreamStateUpdate(t.value):t.case===`subscribedQualityUpdate`?this.onSubscribedQualityUpdate&&this.onSubscribedQualityUpdate(t.value):t.case===`subscriptionPermissionUpdate`?this.onSubscriptionPermissionUpdate&&this.onSubscriptionPermissionUpdate(t.value):t.case===`refreshToken`?this.onTokenRefresh&&this.onTokenRefresh(t.value):t.case===`trackUnpublished`?this.onLocalTrackUnpublished&&this.onLocalTrackUnpublished(t.value):t.case===`subscriptionResponse`?this.onSubscriptionError&&this.onSubscriptionError(t.value):t.case===`pong`||(t.case===`pongResp`?(this.rtt=Date.now()-Number.parseInt(t.value.lastPingTimestamp.toString()),this.resetPingTimeout(),n=!0):t.case===`requestResponse`?this.onRequestResponse&&this.onRequestResponse(t.value):t.case===`trackSubscribed`?this.onLocalTrackSubscribed&&this.onLocalTrackSubscribed(t.value.trackSid):t.case===`roomMoved`?(this.onTokenRefresh&&this.onTokenRefresh(t.value.token),this.onRoomMoved&&this.onRoomMoved(t.value)):t.case===`mediaSectionsRequirement`?this.onMediaSectionsRequirement&&this.onMediaSectionsRequirement(t.value):t.case===`publishDataTrackResponse`?this.onPublishDataTrackResponse&&this.onPublishDataTrackResponse(t.value):t.case===`unpublishDataTrackResponse`?this.onUnPublishDataTrackResponse&&this.onUnPublishDataTrackResponse(t.value):t.case===`dataTrackSubscriberHandles`?this.onDataTrackSubscriberHandles&&this.onDataTrackSubscriberHandles(t.value):this.log.debug(`unsupported message`,{msgCase:t.case}));n||this.resetPingTimeout()}setReconnected(){for(;this.queuedRequests.length>0;){let e=this.queuedRequests.shift();e&&this.requestQueue.run(e)}}handleOnClose(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.attemptId;return function*(){let r=t.onClose;if(!t.sendLifecycleInput({type:`transportFailed`,attemptId:n,reason:e})){t.log.debug(`ignoring transport close in state ${t.lifecycleState}`,{reason:e,attemptId:n,currentAttemptId:t.attemptId});return}yield t.teardownTransport(e),t.log.info(`websocket connection closed: ${e}`,{reason:e}),r&&r(e)}()})}handleWSError(e){this.log.error(`websocket error`,{error:e})}resetPingTimeout(){if(this.clearPingTimeout(),!this.pingTimeoutDuration){this.log.warn(`ping timeout duration not set`);return}this.pingTimeout=kP.setTimeout(()=>{this.log.warn(`ping timeout triggered. last pong received at: ${new Date(Date.now()-this.pingTimeoutDuration*1e3).toUTCString()}`),this.handleOnClose(`ping timeout`)},this.pingTimeoutDuration*1e3)}clearPingTimeout(){this.pingTimeout&&kP.clearTimeout(this.pingTimeout)}startPingInterval(){if(this.clearPingInterval(),this.resetPingTimeout(),!this.pingIntervalDuration){this.log.warn(`ping interval duration not set`);return}this.log.debug(`start ping interval`),this.pingInterval=kP.setInterval(()=>{this.sendPing()},this.pingIntervalDuration*1e3)}clearPingInterval(){this.log.debug(`clearing ping interval`),this.clearPingTimeout(),this.pingInterval&&kP.clearInterval(this.pingInterval)}handleSignalConnected(e,t,n,r){if(clearTimeout(t),!this.sendLifecycleInput(this.lifecycleState===`reconnecting`?{type:`reconnectComplete`,attemptId:n}:{type:`connectComplete`,attemptId:n})){this.log.debug(`discarding a connection whose attempt no longer owns the session`,{attemptId:n,currentAttemptId:this.attemptId,state:this.lifecycleState});return}this.log.info(`signal connected`),this.startPingInterval(),this.startReadingLoop(e.readable.getReader(),r)}validateFirstMessage(e,t){return e.message?.case===`join`?{isValid:!0,response:e.message.value}:this.lifecycleState===`reconnecting`&&e.message?.case!==`leave`?e.message?.case===`reconnect`?{isValid:!0,response:e.message.value}:(this.log.debug(`declaring signal reconnected without reconnect response received`),{isValid:!0,response:void 0,shouldProcessFirstMessage:!0}):this.isEstablishingConnection&&e.message?.case===`leave`?{isValid:!1,error:gP.leaveRequest(`Received leave request while trying to (re)connect`,e.message.value.reason)}:t?{isValid:!1,error:gP.internal(`Unexpected first message`)}:{isValid:!1,error:gP.internal(`did not receive join response, got ${e.message?.case} instead`)}}handleConnectionError(e,t){return J(this,void 0,void 0,function*(){try{let n=yield fetch(t);switch(n.status){case 404:let e=yield n.text();return e.includes(`requested room does not exist`)?gP.notAllowed(e,n.status):gP.serviceNotFound(`v1 RTC path not found. Consider upgrading your LiveKit server version`,`v0-rtc`);case 401:case 403:let t=yield n.text();return gP.notAllowed(t,n.status)}return e instanceof gP?e:gP.internal(`Encountered unknown websocket error during connection: ${e}`,{status:n.status,statusText:n.statusText})}catch(e){return e instanceof gP?e:gP.serverUnreachable(e instanceof Error?e.message:`server was not reachable`)}})}};function lR(e){let t={type:`offer`,sdp:e.sdp};switch(e.type){case`answer`:case`offer`:case`pranswer`:case`rollback`:t.type=e.type}return t}function uR(e,t){return new Tj({sdp:e.sdp,type:e.type,id:t})}function dR(e,t,n){let r=new URLSearchParams;return r.set(`access_token`,e),n.reconnect&&(r.set(`reconnect`,`1`),n.sid&&r.set(`sid`,n.sid)),r.set(`auto_subscribe`,n.autoSubscribe?`1`:`0`),r.set(`sdk`,VF()?`reactnative`:`js`),r.set(`version`,t.version),r.set(`protocol`,t.protocol.toString()),r.set(`client_protocol`,t.clientProtocol.toString()),t.deviceModel&&r.set(`device_model`,t.deviceModel),t.os&&r.set(`os`,t.os),t.osVersion&&r.set(`os_version`,t.osVersion),t.browser&&r.set(`browser`,t.browser),t.browserVersion&&r.set(`browser_version`,t.browserVersion),n.adaptiveStream&&r.set(`adaptive_stream`,`1`),n.reconnectReason&&r.set(`reconnect_reason`,n.reconnectReason.toString()),navigator.connection?.type&&r.set(`network`,navigator.connection.type),r}function fR(e,t,n,r){return J(this,void 0,void 0,function*(){let i=new URLSearchParams;i.set(`access_token`,e);let a=new hM({clientInfo:t,connectionSettings:new mM({autoSubscribe:!!n.autoSubscribe,adaptiveStream:!!n.adaptiveStream}),reconnect:!!n.reconnect,participantSid:n.sid?n.sid:void 0,publisherOffer:r});n.reconnectReason&&(a.reconnectReason=n.reconnectReason);let o=a.toBinary(),s,c;if(DI()){let e=new CompressionStream(`gzip`),t=e.writable.getWriter();t.write(new Uint8Array(o)),t.close();let n=[],r=e.readable.getReader();for(;;){let e=yield r.read(),t=e.done,i=e.value;if(t)break;n.push(i)}let i=n.reduce((e,t)=>e+t.length,0),a=new Uint8Array(i),l=0;for(let e of n)a.set(e,l),l+=e.length;s=a,c=_M.GZIP}else s=o,c=_M.NONE;let l=new gM({joinRequest:s,compression:c}).toBinary();return i.set(`join_request`,(e=>{let t=Array.from(e,e=>String.fromCodePoint(e)).join(``);return btoa(t)})(l).replace(/\+/g,`-`).replace(/\//g,`_`)),i})}var pR=class{constructor(e){this._map=new Map,this._lastCleanup=0,this.ttl=e}set(e,t){let n=Date.now();n-this._lastCleanup>this.ttl/2&&this.cleanup();let r=n+this.ttl;return this._map.set(e,{value:t,expiresAt:r}),this}get(e){let t=this._map.get(e);if(t){if(t.expiresAt<Date.now()){this._map.delete(e);return}return t.value}}has(e){let t=this._map.get(e);return t?t.expiresAt<Date.now()?(this._map.delete(e),!1):!0:!1}delete(e){return this._map.delete(e)}clear(){this._map.clear()}cleanup(){let e=Date.now();for(let n of this._map.entries()){var t=wO(n,2);let r=t[0];t[1].expiresAt<e&&this._map.delete(r)}this._lastCleanup=e}get size(){return this.cleanup(),this._map.size}forEach(e){this.cleanup();for(let n of this._map.entries()){var t=wO(n,2);let r=t[0],i=t[1];i.expiresAt>=Date.now()&&e(i.value,r,this.asValueMap())}}map(e){this.cleanup();let t=[],n=this.asValueMap();for(let i of n.entries()){var r=wO(i,2);let a=r[0],o=r[1];t.push(e(o,a,n))}return t}asValueMap(){let e=new Map;for(let n of this._map.entries()){var t=wO(n,2);let r=t[0],i=t[1];i.expiresAt>=Date.now()&&e.set(r,i.value)}return e}},mR={},hR={},gR={exports:{}},_R;function vR(){if(_R)return gR.exports;_R=1;var e=gR.exports={v:[{name:`version`,reg:/^(\d*)$/}],o:[{name:`origin`,reg:/^(\S*) (\d*) (\d*) (\S*) IP(\d) (\S*)/,names:[`username`,`sessionId`,`sessionVersion`,`netType`,`ipVer`,`address`],format:`%s %s %d %s IP%d %s`}],s:[{name:`name`}],i:[{name:`description`}],u:[{name:`uri`}],e:[{name:`email`}],p:[{name:`phone`}],z:[{name:`timezones`}],r:[{name:`repeats`}],t:[{name:`timing`,reg:/^(\d*) (\d*)/,names:[`start`,`stop`],format:`%d %d`}],c:[{name:`connection`,reg:/^IN IP(\d) (\S*)/,names:[`version`,`ip`],format:`IN IP%d %s`}],b:[{push:`bandwidth`,reg:/^(TIAS|AS|CT|RR|RS):(\d*)/,names:[`type`,`limit`],format:`%s:%s`}],m:[{reg:/^(\w*) (\d*) ([\w/]*)(?: (.*))?/,names:[`type`,`port`,`protocol`,`payloads`],format:`%s %d %s %s`}],a:[{push:`rtp`,reg:/^rtpmap:(\d*) ([\w\-.]*)(?:\s*\/(\d*)(?:\s*\/(\S*))?)?/,names:[`payload`,`codec`,`rate`,`encoding`],format:function(e){return e.encoding?`rtpmap:%d %s/%s/%s`:e.rate?`rtpmap:%d %s/%s`:`rtpmap:%d %s`}},{push:`fmtp`,reg:/^fmtp:(\d*) ([\S| ]*)/,names:[`payload`,`config`],format:`fmtp:%d %s`},{name:`control`,reg:/^control:(.*)/,format:`control:%s`},{name:`rtcp`,reg:/^rtcp:(\d*)(?: (\S*) IP(\d) (\S*))?/,names:[`port`,`netType`,`ipVer`,`address`],format:function(e){return e.address==null?`rtcp:%d`:`rtcp:%d %s IP%d %s`}},{push:`rtcpFbTrrInt`,reg:/^rtcp-fb:(\*|\d*) trr-int (\d*)/,names:[`payload`,`value`],format:`rtcp-fb:%s trr-int %d`},{push:`rtcpFb`,reg:/^rtcp-fb:(\*|\d*) ([\w-_]*)(?: ([\w-_]*))?/,names:[`payload`,`type`,`subtype`],format:function(e){return e.subtype==null?`rtcp-fb:%s %s`:`rtcp-fb:%s %s %s`}},{push:`ext`,reg:/^extmap:(\d+)(?:\/(\w+))?(?: (urn:ietf:params:rtp-hdrext:encrypt))? (\S*)(?: (\S*))?/,names:[`value`,`direction`,`encrypt-uri`,`uri`,`config`],format:function(e){return`extmap:%d`+(e.direction?`/%s`:`%v`)+(e[`encrypt-uri`]?` %s`:`%v`)+` %s`+(e.config?` %s`:``)}},{name:`extmapAllowMixed`,reg:/^(extmap-allow-mixed)/},{push:`crypto`,reg:/^crypto:(\d*) ([\w_]*) (\S*)(?: (\S*))?/,names:[`id`,`suite`,`config`,`sessionConfig`],format:function(e){return e.sessionConfig==null?`crypto:%d %s %s`:`crypto:%d %s %s %s`}},{name:`setup`,reg:/^setup:(\w*)/,format:`setup:%s`},{name:`connectionType`,reg:/^connection:(new|existing)/,format:`connection:%s`},{name:`mid`,reg:/^mid:([^\s]*)/,format:`mid:%s`},{name:`msid`,reg:/^msid:(.*)/,format:`msid:%s`},{name:`ptime`,reg:/^ptime:(\d*(?:\.\d*)*)/,format:`ptime:%d`},{name:`maxptime`,reg:/^maxptime:(\d*(?:\.\d*)*)/,format:`maxptime:%d`},{name:`direction`,reg:/^(sendrecv|recvonly|sendonly|inactive)/},{name:`icelite`,reg:/^(ice-lite)/},{name:`iceUfrag`,reg:/^ice-ufrag:(\S*)/,format:`ice-ufrag:%s`},{name:`icePwd`,reg:/^ice-pwd:(\S*)/,format:`ice-pwd:%s`},{name:`fingerprint`,reg:/^fingerprint:(\S*) (\S*)/,names:[`type`,`hash`],format:`fingerprint:%s %s`},{push:`candidates`,reg:/^candidate:(\S*) (\d*) (\S*) (\d*) (\S*) (\d*) typ (\S*)(?: raddr (\S*) rport (\d*))?(?: tcptype (\S*))?(?: generation (\d*))?(?: network-id (\d*))?(?: network-cost (\d*))?/,names:[`foundation`,`component`,`transport`,`priority`,`ip`,`port`,`type`,`raddr`,`rport`,`tcptype`,`generation`,`network-id`,`network-cost`],format:function(e){var t=`candidate:%s %d %s %d %s %d typ %s`;return t+=e.raddr==null?`%v%v`:` raddr %s rport %d`,t+=e.tcptype==null?`%v`:` tcptype %s`,e.generation!=null&&(t+=` generation %d`),t+=e[`network-id`]==null?`%v`:` network-id %d`,t+=e[`network-cost`]==null?`%v`:` network-cost %d`,t}},{name:`endOfCandidates`,reg:/^(end-of-candidates)/},{name:`remoteCandidates`,reg:/^remote-candidates:(.*)/,format:`remote-candidates:%s`},{name:`iceOptions`,reg:/^ice-options:(\S*)/,format:`ice-options:%s`},{push:`ssrcs`,reg:/^ssrc:(\d*) ([\w_-]*)(?::(.*))?/,names:[`id`,`attribute`,`value`],format:function(e){var t=`ssrc:%d`;return e.attribute!=null&&(t+=` %s`,e.value!=null&&(t+=`:%s`)),t}},{push:`ssrcGroups`,reg:/^ssrc-group:([\x21\x23\x24\x25\x26\x27\x2A\x2B\x2D\x2E\w]*) (.*)/,names:[`semantics`,`ssrcs`],format:`ssrc-group:%s %s`},{name:`msidSemantic`,reg:/^msid-semantic:\s?(\w*) (\S*)/,names:[`semantic`,`token`],format:`msid-semantic: %s %s`},{push:`groups`,reg:/^group:(\w*) (.*)/,names:[`type`,`mids`],format:`group:%s %s`},{name:`rtcpMux`,reg:/^(rtcp-mux)/},{name:`rtcpRsize`,reg:/^(rtcp-rsize)/},{name:`sctpmap`,reg:/^sctpmap:([\w_/]*) (\S*)(?: (\S*))?/,names:[`sctpmapNumber`,`app`,`maxMessageSize`],format:function(e){return e.maxMessageSize==null?`sctpmap:%s %s`:`sctpmap:%s %s %s`}},{name:`xGoogleFlag`,reg:/^x-google-flag:([^\s]*)/,format:`x-google-flag:%s`},{push:`rids`,reg:/^rid:([\d\w]+) (\w+)(?: ([\S| ]*))?/,names:[`id`,`direction`,`params`],format:function(e){return e.params?`rid:%s %s %s`:`rid:%s %s`}},{push:`imageattrs`,reg:RegExp(`^imageattr:(\\d+|\\*)[\\s\\t]+(send|recv)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*)(?:[\\s\\t]+(recv|send)[\\s\\t]+(\\*|\\[\\S+\\](?:[\\s\\t]+\\[\\S+\\])*))?`),names:[`pt`,`dir1`,`attrs1`,`dir2`,`attrs2`],format:function(e){return`imageattr:%s %s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast`,reg:RegExp(`^simulcast:(send|recv) ([a-zA-Z0-9\\-_~;,]+)(?:\\s?(send|recv) ([a-zA-Z0-9\\-_~;,]+))?$`),names:[`dir1`,`list1`,`dir2`,`list2`],format:function(e){return`simulcast:%s %s`+(e.dir2?` %s %s`:``)}},{name:`simulcast_03`,reg:/^simulcast:[\s\t]+([\S+\s\t]+)$/,names:[`value`],format:`simulcast: %s`},{name:`framerate`,reg:/^framerate:(\d+(?:$|\.\d+))/,format:`framerate:%s`},{name:`sourceFilter`,reg:/^source-filter: *(excl|incl) (\S*) (IP4|IP6|\*) (\S*) (.*)/,names:[`filterMode`,`netType`,`addressTypes`,`destAddress`,`srcList`],format:`source-filter: %s %s %s %s %s`},{name:`bundleOnly`,reg:/^(bundle-only)/},{name:`label`,reg:/^label:(.+)/,format:`label:%s`},{name:`sctpPort`,reg:/^sctp-port:(\d+)$/,format:`sctp-port:%s`},{name:`maxMessageSize`,reg:/^max-message-size:(\d+)$/,format:`max-message-size:%s`},{push:`tsRefClocks`,reg:/^ts-refclk:([^\s=]*)(?:=(\S*))?/,names:[`clksrc`,`clksrcExt`],format:function(e){return`ts-refclk:%s`+(e.clksrcExt==null?``:`=%s`)}},{name:`mediaClk`,reg:/^mediaclk:(?:id=(\S*))? *([^\s=]*)(?:=(\S*))?(?: *rate=(\d+)\/(\d+))?/,names:[`id`,`mediaClockName`,`mediaClockValue`,`rateNumerator`,`rateDenominator`],format:function(e){var t=`mediaclk:`;return t+=e.id==null?`%v%s`:`id=%s %s`,t+=e.mediaClockValue==null?``:`=%s`,t+=e.rateNumerator==null?``:` rate=%s`,t+=e.rateDenominator==null?``:`/%s`,t}},{name:`keywords`,reg:/^keywds:(.+)$/,format:`keywds:%s`},{name:`content`,reg:/^content:(.+)/,format:`content:%s`},{name:`bfcpFloorCtrl`,reg:/^floorctrl:(c-only|s-only|c-s)/,format:`floorctrl:%s`},{name:`bfcpConfId`,reg:/^confid:(\d+)/,format:`confid:%s`},{name:`bfcpUserId`,reg:/^userid:(\d+)/,format:`userid:%s`},{name:`bfcpFloorId`,reg:/^floorid:(.+) (?:m-stream|mstrm):(.+)/,names:[`id`,`mStream`],format:`floorid:%s mstrm:%s`},{push:`invalid`,names:[`value`]}]};return Object.keys(e).forEach(function(t){e[t].forEach(function(e){e.reg||=/(.*)/,e.format||=`%s`})}),gR.exports}var yR;function bR(){return yR?hR:(yR=1,(function(e){var t=function(e){return String(Number(e))===e?Number(e):e},n=function(e,n,r,i){if(i&&!r)n[i]=t(e[1]);else for(var a=0;a<r.length;a+=1)e[a+1]!=null&&(n[r[a]]=t(e[a+1]))},r=function(e,t,r){var i=e.name&&e.names;e.push&&!t[e.push]?t[e.push]=[]:i&&!t[e.name]&&(t[e.name]={});var a=e.push?{}:i?t[e.name]:t;n(r.match(e.reg),a,e.names,e.name),e.push&&t[e.push].push(a)},i=vR(),a=RegExp.prototype.test.bind(/^([a-z])=(.*)/);e.parse=function(e){var t={},n=[],o=t;return e.split(/(\r\n|\r|\n)/).filter(a).forEach(function(e){var t=e[0],a=e.slice(2);t===`m`&&(n.push({rtp:[],fmtp:[]}),o=n[n.length-1]);for(var s=0;s<(i[t]||[]).length;s+=1){var c=i[t][s];if(c.reg.test(a))return r(c,o,a)}}),t.media=n,t};var o=function(e,n){var r=n.split(/=(.+)/,2);return r.length===2?e[r[0]]=t(r[1]):r.length===1&&n.length>1&&(e[r[0]]=void 0),e};e.parseParams=function(e){return e.split(/;\s?/).reduce(o,{})},e.parseFmtpConfig=e.parseParams,e.parsePayloads=function(e){return e.toString().split(` `).map(Number)},e.parseRemoteCandidates=function(e){for(var n=[],r=e.split(` `).map(t),i=0;i<r.length;i+=3)n.push({component:r[i],ip:r[i+1],port:r[i+2]});return n},e.parseImageAttributes=function(e){return e.split(` `).map(function(e){return e.substring(1,e.length-1).split(`,`).reduce(o,{})})},e.parseSimulcastStreamList=function(e){return e.split(`;`).map(function(e){return e.split(`,`).map(function(e){var n,r=!1;return e[0]===`~`?(n=t(e.substring(1,e.length)),r=!0):n=t(e),{scid:n,paused:r}})})}})(hR),hR)}var xR,SR;function CR(){if(SR)return xR;SR=1;var e=vR(),t=/%[sdv%]/g,n=function(e){var n=1,r=arguments,i=r.length;return e.replace(t,function(e){if(n>=i)return e;var t=r[n];switch(n+=1,e){case`%%`:return`%`;case`%s`:return String(t);case`%d`:return Number(t);case`%v`:return``}})},r=function(e,t,r){var i=t.format instanceof Function?t.format(t.push?r:r[t.name]):t.format,a=[e+`=`+i];if(t.names)for(var o=0;o<t.names.length;o+=1){var s=t.names[o];t.name?a.push(r[t.name][s]):a.push(r[t.names[o]])}else a.push(r[t.name]);return n.apply(null,a)},i=[`v`,`o`,`s`,`i`,`u`,`e`,`p`,`c`,`b`,`t`,`r`,`z`,`a`],a=[`i`,`c`,`b`,`a`];return xR=function(t,n){n||={},t.version??=0,t.name??=` `,t.media.forEach(function(e){e.payloads??=``});var o=n.outerOrder||i,s=n.innerOrder||a,c=[];return o.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})}),t.media.forEach(function(t){c.push(r(`m`,e.m[0],t)),s.forEach(function(n){e[n].forEach(function(e){e.name in t&&t[e.name]!=null?c.push(r(n,e,t)):e.push in t&&t[e.push]!=null&&t[e.push].forEach(function(t){c.push(r(n,e,t))})})})}),c.join(`\r
103
+ `)+`\r
104
+ `},xR}var wR;function TR(){if(wR)return mR;wR=1;var e=bR(),t=CR();return mR.grammar=vR(),mR.write=t,mR.parse=e.parse,mR.parseParams=e.parseParams,mR.parseFmtpConfig=e.parseFmtpConfig,mR.parsePayloads=e.parsePayloads,mR.parseRemoteCandidates=e.parseRemoteCandidates,mR.parseImageAttributes=e.parseImageAttributes,mR.parseSimulcastStreamList=e.parseSimulcastStreamList,mR}var ER=TR(),DR=.9,OR=1e3,kR=20;function AR(e,t,n,r){let i=arguments.length>4&&arguments[4]!==void 0&&arguments[4];if(!e.msid?.includes(t))return;let a=e.rtp.find(e=>e.codec.toUpperCase()===n.toUpperCase())?.payload??0;if(a===0)return 0;let o=Math.round(r*DR),s=i?o:Math.min(o,OR),c=e.fmtp.find(e=>e.payload===a);return c?c.config.includes(`x-google-start-bitrate`)||(c.config+=`;x-google-start-bitrate=${s}`):e.fmtp.push({payload:a,config:`x-google-start-bitrate=${s}`}),a}var jR={NegotiationStarted:`negotiationStarted`,NegotiationComplete:`negotiationComplete`,OfferAnswered:`offerAnswered`,RTPVideoPayloadTypes:`rtpVideoPayloadTypes`},MR=class extends KM.EventEmitter{get pc(){return this._pc||=this.createPC(),this._pc}constructor(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};super(),this.log=DM,this.iceLog=DM,this.ddExtID=0,this.latestOfferId=0,this.latestAcknowledgedOfferId=0,this.pendingCandidates=[],this.restartingIce=!1,this.renegotiate=!1,this.trackBitrates=[],this.remoteStereoMids=[],this.remoteNackMids=[],this.negotiate=tL(e=>J(this,void 0,void 0,function*(){this.emit(jR.NegotiationStarted);try{yield this.createAndSendOffer()}catch(t){if(e)e(t);else throw t}}),kR),this.close=()=>{this._pc&&=(this.log.debug(`closing peer connection`),this.pendingInitialOffer=void 0,this._pc.close(),this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.ondatachannel=null,this._pc.onnegotiationneeded=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ondatachannel=null,this._pc.ontrack=null,this._pc.onconnectionstatechange=null,this._pc.oniceconnectionstatechange=null,null)},this.loggerOptions=t,this.log=OM(t.loggerName??EM.PCTransport,()=>this.logContext),this.iceLog=OM(EM.ICE,()=>this.logContext),this.config=e,this._pc=this.createPC(),this.offerLock=new jD}createPC(){let e=new RTCPeerConnection(this.config);return e.onicecandidate=e=>{var t;e.candidate&&(this.iceLog.debug(`local ICE candidate gathered`,{candidate:e.candidate.candidate}),(t=this.onIceCandidate)==null||t.call(this,e.candidate))},e.onicecandidateerror=e=>{var t;this.iceLog.debug(`ICE candidate error`,{event:e}),(t=this.onIceCandidateError)==null||t.call(this,e)},e.oniceconnectionstatechange=()=>{var t;this.iceLog.debug(`ICE connection state: ${e.iceConnectionState}`),(t=this.onIceConnectionStateChange)==null||t.call(this,e.iceConnectionState)},e.onsignalingstatechange=()=>{var t;this.log.debug(`signaling state: ${e.signalingState}`),(t=this.onSignalingStatechange)==null||t.call(this,e.signalingState)},e.onconnectionstatechange=()=>{var t;this.log.debug(`connection state: ${e.connectionState}`),(t=this.onConnectionStateChange)==null||t.call(this,e.connectionState)},e.ondatachannel=e=>{var t;this.log.debug(`data channel opened by peer`,{label:e.channel.label,id:e.channel.id}),(t=this.onDataChannel)==null||t.call(this,e)},e.ontrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},e}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}get isICEConnected(){return this._pc!==null&&(this.pc.iceConnectionState===`connected`||this.pc.iceConnectionState===`completed`)}addIceCandidate(e){return J(this,void 0,void 0,function*(){if(this.pc.remoteDescription&&!this.restartingIce)return this.pc.addIceCandidate(e);this.iceLog.debug(`queuing remote ICE candidate until remote description applied`,{pendingCount:this.pendingCandidates.length+1}),this.pendingCandidates.push(e)})}setRemoteDescription(e,t){return J(this,void 0,void 0,function*(){if(e.type===`answer`&&this.latestOfferId>0&&t>0&&t!==this.latestOfferId)return this.log.warn(`ignoring answer for old offer`,{offerId:t,latestOfferId:this.latestOfferId}),!1;let n;if(e.type===`offer`){let t=HR(e),n=t.stereoMids,r=t.nackMids;this.remoteStereoMids=n,this.remoteNackMids=r}else if(e.type===`answer`){if(this.pendingInitialOffer&&this._pc){let e=this.pendingInitialOffer;this.pendingInitialOffer=void 0;let t=ER.parse(e.sdp??``);t.media.forEach(e=>{UR(e)}),this.log.debug(`setting pending initial offer before processing answer`),yield this.setMungedSDP(e,ER.write(t))}let t=ER.parse(e.sdp??``);t.media.forEach(e=>{let t=WR(e.mid);e.type===`audio`&&this.trackBitrates.some(n=>{if(!n.transceiver||t!=n.transceiver.mid)return!1;let r=0;if(e.rtp.some(e=>e.codec.toUpperCase()===n.codec.toUpperCase()&&(r=e.payload,!0)),r===0)return!0;let i=!1;for(let t of e.fmtp)if(t.payload===r){t.config=t.config.split(`;`).filter(e=>!e.includes(`maxaveragebitrate`)).join(`;`),n.maxbr>0&&(t.config+=`;maxaveragebitrate=${n.maxbr*1e3}`),i=!0;break}return i||n.maxbr>0&&e.fmtp.push({payload:r,config:`maxaveragebitrate=${n.maxbr*1e3}`}),!0})});let r=this.getPlaceholderMids();r.size>0&&VR(t.media,e=>r.has(WR(e.mid))),n=ER.write(t)}return yield this.setMungedSDP(e,n,!0),this.pendingCandidates.length>0&&this.iceLog.debug(`flushing queued ICE candidates`,{count:this.pendingCandidates.length}),this.pendingCandidates.forEach(e=>{this.pc.addIceCandidate(e)}),this.pendingCandidates=[],this.restartingIce=!1,e.type===`answer`&&(this.latestAcknowledgedOfferId=t,this.emit(jR.OfferAnswered,t)),this.renegotiate?(this.renegotiate=!1,yield this.createAndSendOffer()):e.type===`answer`&&(this.emit(jR.NegotiationComplete),e.sdp&&ER.parse(e.sdp).media.forEach(e=>{e.type===`video`&&this.emit(jR.RTPVideoPayloadTypes,e.rtp)})),!0})}createInitialOffer(){return J(this,void 0,void 0,function*(){let e=yield this.offerLock.lock();try{if(this.pc.signalingState!==`stable`){this.log.warn(`signaling state is not stable, cannot create initial offer`);return}let e=this.latestOfferId+1;this.latestOfferId=e;let t=yield this.pc.createOffer();this.pendingInitialOffer={sdp:t.sdp,type:t.type};let n=ER.parse(t.sdp??``);return n.media.forEach(e=>{UR(e)}),t.sdp=ER.write(n),{offer:t,offerId:e}}finally{e()}})}createAndSendOffer(e){return J(this,void 0,void 0,function*(){let t=yield this.offerLock.lock();try{if(this.onOffer===void 0)return;if(e?.iceRestart&&(this.iceLog.debug(`restarting ICE`),this.restartingIce=!0),this._pc&&(this._pc.signalingState===`have-local-offer`||this.pendingInitialOffer)){let t=this._pc.remoteDescription;if(e?.iceRestart&&t)yield this._pc.setRemoteDescription(t);else if(e?.iceRestart)throw new xP(`ICE restart requested without a remote description, peer connection must be recreated`);else{this.renegotiate=!0,this.log.debug(`requesting renegotiation`);return}}else if(!this._pc||this._pc.signalingState===`closed`){this.log.warn(`could not createOffer with closed peer connection`);return}this.log.debug(`starting to negotiate`);let t=this.latestOfferId+1;this.latestOfferId=t;let n=yield this.pc.createOffer(e);this.log.debug(`original offer`,{sdp:n.sdp});let r=ER.parse(n.sdp??``);r.media.forEach(e=>{UR(e),e.type===`audio`?zR(e,[`all`],[]):e.type===`video`&&this.trackBitrates.some(t=>{if(!t.cid)return!1;let n=AR(e,t.cid,t.codec,t.maxbr,t.isScreenShare);return n!==void 0&&(n>0&&CF(t.codec)&&!PF()&&(this.ddExtID=NR(e,r,this.ddExtID)),!0)})});let i=this.getPlaceholderMids();if(i.size>0&&VR(r.media,e=>i.has(WR(e.mid))),this.latestOfferId>t){this.log.warn(`latestOfferId mismatch`,{latestOfferId:this.latestOfferId,offerId:t});return}yield this.setMungedSDP(n,ER.write(r)),this.onOffer(n,this.latestOfferId)}finally{t()}})}createAndSetAnswer(){return J(this,void 0,void 0,function*(){let e=yield this.pc.createAnswer(),t=ER.parse(e.sdp??``);return t.media.forEach(e=>{UR(e),e.type===`audio`&&zR(e,this.remoteStereoMids,this.remoteNackMids)}),yield this.setMungedSDP(e,ER.write(t)),e})}getPlaceholderMids(){return BR(this._pc?.getTransceivers()??[])}createDataChannel(e,t){return this.pc.createDataChannel(e,t)}addTransceiver(e,t){return this.pc.addTransceiver(e,t)}addTransceiverOfKind(e,t){return this.pc.addTransceiver(e,t)}addTrack(e){if(!this._pc)throw new bP(`PC closed, cannot add track`);return this._pc.addTrack(e)}setTrackCodecBitrate(e){this.trackBitrates.push(e)}setConfiguration(e){if(!this._pc)throw new bP(`PC closed, cannot configure`);return this._pc?.setConfiguration(e)}canRemoveTrack(){return!!this._pc?.removeTrack}removeTrack(e){return this._pc?.removeTrack(e)}getConnectionState(){return this._pc?.connectionState??`closed`}getICEConnectionState(){return this._pc?.iceConnectionState??`closed`}getSignallingState(){return this._pc?.signalingState??`closed`}getTransceivers(){return this._pc?.getTransceivers()??[]}getSenders(){return this._pc?.getSenders()??[]}getLocalDescription(){return this._pc?.localDescription}getRemoteDescription(){return this.pc?.remoteDescription}getStats(){return this._pc?.getStats()}getMaxMessageSize(){return this._pc?.sctp?.maxMessageSize}getConnectedAddress(){return J(this,void 0,void 0,function*(){if(!this._pc)return;let e=``,t=new Map,n=new Map;if((yield this._pc.getStats()).forEach(r=>{switch(r.type){case`transport`:e=r.selectedCandidatePairId;break;case`candidate-pair`:e===``&&r.selected&&(e=r.id),t.set(r.id,r);break;case`remote-candidate`:n.set(r.id,`${r.address}:${r.port}`)}}),e===``)return;let r=t.get(e)?.remoteCandidateId;if(r!==void 0)return n.get(r)})}setMungedSDP(e,t,n){return J(this,void 0,void 0,function*(){let r=e.sdp;if(t){e.sdp=t;try{this.log.debug(`setting munged ${n?`remote`:`local`} description`),n?yield this.pc.setRemoteDescription(e):yield this.pc.setLocalDescription(e);return}catch(n){this.log.warn(`not able to set ${e.type}, falling back to unmodified sdp`,{error:n,mungedSdp:t,originalSdp:r}),e.sdp=r}}try{n?yield this._pc?.setRemoteDescription(e):yield this._pc?.setLocalDescription(e)}catch(i){let a=`unknown error`;i instanceof Error?a=i.message:typeof i==`string`&&(a=i);let o={error:a,sdp:e.sdp};throw t&&t!==r&&(o.mungedSdp=t),!n&&this.pc.remoteDescription&&(o.remoteSdp=this.pc.remoteDescription),this.log.error(`unable to set ${e.type}`,{fields:o}),new xP(a)}})}};function NR(e,t,n){let r=PR(t,n);return r===void 0?n:(e.ext?.some(e=>e.uri===gF)||(e.ext??=[],e.ext.push({value:r,uri:gF})),r)}function PR(e,t){let n=FR(e,gF);return n===void 0?t!==0&&!IR(e,t,gF)?t:LR(e):IR(e,n,gF)?void 0:n}function FR(e,t){for(let n of e.media){let e=n.ext?.find(e=>e.uri===t);if(e)return e.value}}function IR(e,t,n){return e.media.some(e=>e.ext?.some(e=>e.value===t&&e.uri!==n))}function LR(e){let t=0;return e.media.forEach(e=>{var n;(n=e.ext)==null||n.forEach(e=>{e.value>t&&(t=e.value)})}),t+1===15?16:t+1}function RR(e,t){return e.split(`;`).some(e=>e.trim()===t)}function zR(e,t,n){let r=WR(e.mid),i=0;e.rtp.some(e=>e.codec.toLowerCase()===`opus`&&(i=e.payload,!0)),i>0&&(e.rtcpFb||=[],n.includes(r)&&!e.rtcpFb.some(e=>e.payload===i&&e.type===`nack`)&&e.rtcpFb.push({payload:i,type:`nack`}),(t.includes(r)||t.length===1&&t[0]===`all`)&&e.fmtp.some(e=>e.payload===i&&(RR(e.config,`stereo=1`)||(e.config+=`;stereo=1`),!0)))}function BR(e){let t=new Set;for(let n of e)n.mid&&!n.sender.track&&t.add(n.mid);return t}function VR(e,t){let n=new Map,r=new Set;for(let i of e){let e=t(i);for(let t of i.fmtp??[])e?n.has(t.payload)||n.set(t.payload,t.config):(n.set(t.payload,t.config),r.add(t.payload))}if(n.size!==0){for(let r of e)if(t(r))for(let e of r.fmtp??[]){let t=n.get(e.payload);t!==void 0&&e.config!==t&&(e.config=t)}}}function HR(e){let t=[],n=[],r=ER.parse(e.sdp??``),i=0;return r.media.forEach(e=>{let r=WR(e.mid);e.type===`audio`&&(e.rtp.some(e=>e.codec.toLowerCase()===`opus`&&(i=e.payload,!0)),e.rtcpFb?.some(e=>e.payload===i&&e.type===`nack`)&&n.push(r),e.fmtp.some(e=>e.payload===i&&(RR(e.config,`sprop-stereo=1`)&&t.push(r),!0)))}),{stereoMids:t,nackMids:n}}function UR(e){if(e.connection){let t=e.connection.ip.indexOf(`:`)>=0;(e.connection.version===4&&t||e.connection.version===6&&!t)&&(e.connection.ip=`0.0.0.0`,e.connection.version=4)}}function WR(e){return typeof e==`number`?e.toFixed(0):e}var GR=`vp8`,KR={audioPreset:UP.music,dtx:!0,red:!0,forceStereo:!1,simulcast:!0,screenShareEncoding:KP.h1080fps15.encoding,stopMicTrackOnMute:!1,videoCodec:GR,backupCodec:!0,preConnectBuffer:!1},qR={deviceId:{ideal:`default`},autoGainControl:!0,echoCancellation:!0,noiseSuppression:!0,voiceIsolation:!0},JR={deviceId:{ideal:`default`},resolution:WP.h720.resolution},YR={adaptiveStream:!1,dynacast:!1,stopLocalTrackOnUnpublish:!0,reconnectPolicy:new IM,disconnectOnPageLeave:!0,webAudioMix:!1,singlePeerConnection:!0},XR={autoSubscribe:!0,maxRetries:1,peerConnectionTimeout:15e3,websocketTimeout:15e3},ZR;(function(e){e[e.NEW=0]=`NEW`,e[e.CONNECTING=1]=`CONNECTING`,e[e.CONNECTED=2]=`CONNECTED`,e[e.FAILED=3]=`FAILED`,e[e.CLOSING=4]=`CLOSING`,e[e.CLOSED=5]=`CLOSED`})(ZR||={});var QR=class{get needsPublisher(){return this.isPublisherConnectionRequired}get needsSubscriber(){return this.isSubscriberConnectionRequired}get currentState(){return this.state}get mode(){return this._mode}constructor(e,t,n){this.peerConnectionTimeout=XR.peerConnectionTimeout,this.log=DM,this.iceLog=DM,this.updateState=()=>{var e;let t=this.state,n=this.requiredTransports.map(e=>e.getConnectionState());n.every(e=>e===`connected`)?this.state=ZR.CONNECTED:n.some(e=>e===`failed`)?this.state=ZR.FAILED:n.some(e=>e===`connecting`)?this.state=ZR.CONNECTING:n.every(e=>e===`closed`)?this.state=ZR.CLOSED:n.some(e=>e===`closed`)?this.state=ZR.CLOSING:n.every(e=>e===`new`)&&(this.state=ZR.NEW),t!==this.state&&(this.log.debug(`pc state change: from ${ZR[t]} to ${ZR[this.state]}`),(e=this.onStateChange)==null||e.call(this,this.state,this.publisher.getConnectionState(),this.subscriber?.getConnectionState()))},this.loggerOptions=t,this.log=OM(t.loggerName??EM.PCManager,()=>this.logContext),this.iceLog=OM(EM.ICE,()=>this.logContext),this.isPublisherConnectionRequired=e!==`subscriber-primary`,this.isSubscriberConnectionRequired=e===`subscriber-primary`,this.publisher=new MR(n,t),this._mode=e,e!==`publisher-only`&&(this.subscriber=new MR(n,t),this.subscriber.onConnectionStateChange=this.updateState,this.subscriber.onIceConnectionStateChange=this.updateState,this.subscriber.onSignalingStatechange=this.updateState,this.subscriber.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,oj.SUBSCRIBER)},this.subscriber.onDataChannel=e=>{var t;(t=this.onDataChannel)==null||t.call(this,e)},this.subscriber.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)}),this.publisher.onConnectionStateChange=this.updateState,this.publisher.onIceConnectionStateChange=this.updateState,this.publisher.onSignalingStatechange=this.updateState,this.publisher.onIceCandidate=e=>{var t;(t=this.onIceCandidate)==null||t.call(this,e,oj.PUBLISHER)},this.publisher.onTrack=e=>{var t;(t=this.onTrack)==null||t.call(this,e)},this.publisher.onOffer=(e,t)=>{var n;(n=this.onPublisherOffer)==null||n.call(this,e,t)},this.state=ZR.NEW,this.connectionLock=new jD,this.remoteOfferLock=new jD}get logContext(){var e;return Object.assign({},(e=this.loggerOptions).loggerContextCb?.call(e))}requirePublisher(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;this.isPublisherConnectionRequired=e,this.updateState()}createAndSendPublisherOffer(e){return this.publisher.createAndSendOffer(e)}setPublisherAnswer(e,t){return this.publisher.setRemoteDescription(e,t)}removeTrack(e){return this.publisher.removeTrack(e)}close(){return J(this,void 0,void 0,function*(){if(this.publisher&&this.publisher.getSignallingState()!==`closed`){let e=this.publisher;for(let t of e.getSenders())try{e.canRemoveTrack()&&e.removeTrack(t)}catch(e){this.log.warn(`could not removeTrack`,{error:e})}}yield Promise.all([this.publisher.close(),this.subscriber?.close()]),this.updateState()})}triggerIceRestart(){return J(this,void 0,void 0,function*(){this.iceLog.warn(`triggering ICE restart`),this.needsPublisher&&(yield this.createAndSendPublisherOffer({iceRestart:!0}))})}addIceCandidate(e,t){return J(this,void 0,void 0,function*(){this.iceLog.debug(`adding remote ICE candidate`,{target:t,candidate:e}),t===oj.PUBLISHER?yield this.publisher.addIceCandidate(e):yield this.subscriber?.addIceCandidate(e)})}createSubscriberAnswerFromOffer(e,t){return J(this,void 0,void 0,function*(){this.log.debug(`received server offer`,{RTCSdpType:e.type,sdp:e.sdp,signalingState:this.subscriber?.getSignallingState().toString()});let n=yield this.remoteOfferLock.lock();try{return(yield this.subscriber?.setRemoteDescription(e,t))?yield this.subscriber?.createAndSetAnswer():void 0}finally{n()}})}updateConfiguration(e,t){var n;this.log.debug(`updating rtc configuration`,{iceRestart:t}),this.publisher.setConfiguration(e),(n=this.subscriber)==null||n.setConfiguration(e),t&&this.triggerIceRestart()}ensurePCTransportConnection(e,t){return J(this,void 0,void 0,function*(){let n=yield this.connectionLock.lock();try{this.isPublisherConnectionRequired&&this.publisher.getConnectionState()!==`connected`&&this.publisher.getConnectionState()!==`connecting`&&(this.log.debug(`negotiation required, start negotiating`),this.publisher.negotiate()),yield Promise.all(this.requiredTransports?.map(n=>this.ensureTransportConnected(n,e,t)))}finally{n()}})}negotiate(e){return J(this,void 0,void 0,function*(){return new aP((t,n)=>{let r=this.publisher.latestOfferId;if(this.publisher.latestAcknowledgedOfferId>r){this.log.debug(`negotiation already handled in more recent acknowledged offer`,this.logContext),t();return}let i=!1,a=()=>{i||(i=!0,clearTimeout(c),this.publisher.off(jR.OfferAnswered,o),e.signal.removeEventListener(`abort`,s))},o=e=>{e>r&&(a(),t())},s=()=>{a(),n(new xP(`negotiation aborted`))},c=setTimeout(()=>{a(),n(new xP(`negotiation timed out`))},this.peerConnectionTimeout);e.signal.addEventListener(`abort`,s),this.publisher.on(jR.OfferAnswered,o),this.publisher.negotiate(e=>{a(),e instanceof Error?n(e):n(Error(String(e)))})})})}addPublisherTransceiver(e,t){return this.publisher.addTransceiver(e,t)}addPublisherTransceiverOfKind(e,t){return this.publisher.addTransceiverOfKind(e,t)}getMidForReceiver(e){return(this.subscriber?this.subscriber.getTransceivers():this.publisher.getTransceivers()).find(t=>t.receiver===e)?.mid}getMaxPublisherMessageSize(){return this.publisher.getMaxMessageSize()}addPublisherTrack(e){return this.publisher.addTrack(e)}createPublisherDataChannel(e,t){return this.publisher.createDataChannel(e,t)}getConnectedAddress(e){return e===oj.PUBLISHER||e===oj.SUBSCRIBER?this.publisher.getConnectedAddress():this.requiredTransports[0].getConnectedAddress()}get requiredTransports(){let e=[];return this.isPublisherConnectionRequired&&e.push(this.publisher),this.isSubscriberConnectionRequired&&this.subscriber&&e.push(this.subscriber),e}ensureTransportConnected(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:this.peerConnectionTimeout;return function*(){if(e.getConnectionState()!==`connected`)return new Promise((e,i)=>J(n,void 0,void 0,function*(){let n=()=>{this.log.warn(`abort transport connection`),kP.clearTimeout(a),i(gP.cancelled(`room connection has been cancelled`))};t?.signal.aborted&&n(),t?.signal.addEventListener(`abort`,n);let a=kP.setTimeout(()=>{t?.signal.removeEventListener(`abort`,n),i(gP.internal(`could not establish pc connection`))},r);for(;this.state!==ZR.CONNECTED;)if(yield vF(50),t?.signal.aborted){i(gP.cancelled(`room connection has been cancelled`));return}kP.clearTimeout(a),t?.signal.removeEventListener(`abort`,n),e()}))}()})}},$R=class{constructor(e){this.bufferStatusLow=!0,this.headroomLock=new jD,this.waiterAbortController=new AbortController,this.kind=e.kind,this.lowWaterMark=e.lowWaterMark,this.highWaterMark=e.highWaterMark,this.isEngineClosed=e.isEngineClosed,this.onBufferStatusChanged=e.onBufferStatusChanged}get channelHandle(){return this.handle}attach(e){this.handle&&this.handle!==e&&this.invalidateWaiters(`data channel replaced`),this.handle=e}detach(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`data channel torn down`;this.handle&&this.invalidateWaiters(e),this.handle=void 0}getChannel(){return this.handle}isBelowHighWaterMark(e){return e.bufferedAmount<=this.highWaterMark}isBelowLowWaterMark(e){return e.bufferedAmount<=e.bufferedAmountLowThreshold}lockHeadroom(){return this.headroomLock.lock()}waitForHeadroomWithLock(){return J(this,void 0,void 0,function*(){let e=yield this.lockHeadroom();try{yield this.waitForHeadroomWithoutLock()}finally{e()}})}waitForHeadroomWithoutLock(){return J(this,void 0,void 0,function*(){if(this.isEngineClosed())throw new bP(`engine closed`);let e=this.getChannel();if(!e)throw new bP(`DataChannel not found, kind: ${this.kind}`);if(this.isBelowHighWaterMark(e))return;let t=this.waiterAbortController.signal;yield new aP((n,r)=>{let i=()=>{s(),n()},a=()=>{s(),r(new bP(`DataChannel ${this.kind} closed while draining the buffer`))},o=()=>{s(),r(new bP(`DataChannel ${this.kind} was replaced or torn down while waiting for headroom`))},s=()=>{e.removeEventListener(`bufferedamountlow`,i),e.removeEventListener(`close`,a),t.removeEventListener(`abort`,o)};if(t.aborted){o();return}e.addEventListener(`bufferedamountlow`,i),e.addEventListener(`close`,a),t.addEventListener(`abort`,o)})})}invalidateWaiters(e){this.waiterAbortController.abort(e),this.waiterAbortController=new AbortController}refreshBufferStatus(){var e;let t=this.getChannel();if(!t)return;let n=this.isBelowLowWaterMark(t);n!==this.bufferStatusLow&&(this.bufferStatusLow=n,(e=this.onBufferStatusChanged)==null||e.call(this,n))}},ez=class extends $R{constructor(e){super(e),this.statCurrentBytes=0,this.statByterate=0,this.dropCount=0,this.bufferFullBehavior=e.bufferFullBehavior,this.shouldSkipSends=e.shouldSkipSends}send(e){return J(this,void 0,void 0,function*(){let t=this.getChannel();if(t){switch(this.bufferFullBehavior){case`wait`:this.isBelowHighWaterMark(t)||(yield this.waitForHeadroomWithLock());break;case`drop`:if(!this.isBelowLowWaterMark(t)){this.dropCount+=1,this.dropCount%100==0&&DM.warn(`dropping lossy data channel messages, total dropped: ${this.dropCount}`);return}}if(this.statCurrentBytes+=e.byteLength,!this.shouldSkipSends())try{t.send(e),this.refreshBufferStatus()}catch(e){if(e instanceof TypeError)DM.error(e);else throw e}}})}startThresholdTuning(){this.stopThresholdTuning(),this.statInterval=kP.setInterval(()=>{this.statByterate=this.statCurrentBytes,this.statCurrentBytes=0;let e=this.getChannel();if(e){let t=this.statByterate/10;e.bufferedAmountLowThreshold=Math.min(Math.max(t,this.lowWaterMark),this.highWaterMark)}},1e3)}stopThresholdTuning(){this.statByterate=0,this.statCurrentBytes=0,this.statInterval&&=(kP.clearInterval(this.statInterval),void 0),this.dropCount=0}},tz=class{constructor(){this.buffer=[],this._totalSize=0,this._sentSize=0}push(e){this.buffer.push(e),this._totalSize+=e.data.byteLength,e.sent&&(this._sentSize+=e.data.byteLength)}pop(){let e=this.buffer.shift();return e&&(this._totalSize-=e.data.byteLength,e.sent&&(this._sentSize-=e.data.byteLength)),e}getAll(){return this.buffer.slice()}getUnsent(){return this.buffer.filter(e=>!e.sent)}markSent(e){e.sent||(e.sent=!0,this._sentSize+=e.data.byteLength)}markAllUnsent(){for(let e of this.buffer)e.sent=!1;this._sentSize=0}popToSequence(e){for(;this.buffer.length>0&&this.buffer[0].sequence<=e;)this.pop()}alignBufferedAmount(e){for(;this.buffer.length>0;){let t=this.buffer[0];if(!t.sent||this._sentSize-t.data.byteLength<=e)break;this.pop()}}get length(){return this.buffer.length}},nz=class extends $R{constructor(e){super(e),this.messageBuffer=new tz,this.sequence=1,this.isDeferringSends=e.isDeferringSends}nextSequence(){let e=this.sequence;return this.sequence+=1,e}send(e,t){return J(this,void 0,void 0,function*(){if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}let n=this.getChannel();if(n){try{yield this.waitForHeadroomWithLock()}catch(n){if(this.isEngineClosed())throw n;this.messageBuffer.push({data:e,sequence:t,sent:!1});return}if(this.isDeferringSends()){this.messageBuffer.push({data:e,sequence:t,sent:!1});return}this.messageBuffer.push({data:e,sequence:t,sent:!0}),n.send(e),this.refreshBufferStatus()}})}replay(e){return J(this,void 0,void 0,function*(){let t=this.getChannel();if(!t)return;this.messageBuffer.popToSequence(e);let n=yield this.lockHeadroom();try{this.messageBuffer.markAllUnsent();for(let e=this.messageBuffer.getUnsent();e.length>0;e=this.messageBuffer.getUnsent())for(let n of e)yield this.waitForHeadroomWithoutLock(),t.send(n.data),this.messageBuffer.markSent(n)}finally{n()}this.refreshBufferStatus()})}refreshBufferStatus(){let e=this.channelHandle;e&&this.messageBuffer.alignBufferedAmount(e.bufferedAmount),super.refreshBufferStatus()}reset(){this.messageBuffer=new tz,this.sequence=1}},rz;(function(e){e[e.RELIABLE=0]=`RELIABLE`,e[e.LOSSY=1]=`LOSSY`,e[e.DATA_TRACK_LOSSY=2]=`DATA_TRACK_LOSSY`})(rz||={});var iz=65536,az=1048576,oz=8192,sz=262144;function cz(e){return e===rz.RELIABLE?iz:oz}function lz(e){return e===rz.RELIABLE?az:sz}var uz=`_lossy`,dz=`_reliable`,fz=`_data_track`,pz=class{constructor(e){this.opts=e;let t=t=>({kind:t,lowWaterMark:cz(t),highWaterMark:lz(t),isEngineClosed:e.isEngineClosed,onBufferStatusChanged:n=>e.onBufferStatusChanged(t,n)});this.reliable=new nz(Object.assign(Object.assign({},t(rz.RELIABLE)),{isDeferringSends:e.isReconnecting})),this.lossy=new ez(Object.assign(Object.assign({},t(rz.LOSSY)),{bufferFullBehavior:`drop`,shouldSkipSends:e.isReconnecting})),this.dataTrack=new ez(Object.assign(Object.assign({},t(rz.DATA_TRACK_LOSSY)),{bufferFullBehavior:`wait`,shouldSkipSends:e.isReconnecting}))}channelFor(e){switch(e){case rz.RELIABLE:return this.reliable;case rz.LOSSY:return this.lossy;case rz.DATA_TRACK_LOSSY:return this.dataTrack}}getHandle(e){if(!(arguments.length>1&&arguments[1]!==void 0&&arguments[1]))return this.channelFor(e).channelHandle;switch(e){case rz.RELIABLE:return this.reliableSub;case rz.LOSSY:return this.lossySub;case rz.DATA_TRACK_LOSSY:return this.dataTrackSub}}get hasPublisherChannels(){return!!(this.reliable.channelHandle||this.lossy.channelHandle||this.dataTrack.channelHandle)}createPublisherChannels(e){for(let e of[this.lossy,this.reliable,this.dataTrack]){let t=e.channelHandle;t&&(t.onmessage=null,t.onerror=null,t.onclose=null)}let t=(e,t,n)=>{t.onmessage=n,t.onerror=this.opts.onDataError,t.onclose=()=>this.opts.onChannelClose(e.kind),t.bufferedAmountLowThreshold=e.lowWaterMark,t.onbufferedamountlow=()=>e.refreshBufferStatus(),e.attach(t)};t(this.lossy,e.createPublisherDataChannel(uz,{ordered:!1,maxRetransmits:0}),this.opts.onDataMessage),t(this.reliable,e.createPublisherDataChannel(dz,{ordered:!0}),this.opts.onDataMessage),t(this.dataTrack,e.createPublisherDataChannel(fz,{ordered:!1,maxRetransmits:0}),this.opts.onDataTrackMessage),this.lossy.startThresholdTuning()}adoptSubscriberChannel(e){let t;if(e.label===dz)this.reliableSub=e,t=this.opts.onDataMessage;else if(e.label===uz)this.lossySub=e,t=this.opts.onDataMessage;else if(e.label===fz)this.dataTrackSub=e,t=this.opts.onDataTrackMessage;else return!1;return e.onmessage=t,!0}teardown(){let e=e=>{e&&(e.onbufferedamountlow=null,e.onclose=null,e.onclosing=null,e.onerror=null,e.onmessage=null,e.onopen=null,e.close())};for(let t of[this.lossy,this.reliable,this.dataTrack]){let n=t.channelHandle;t.detach(`peer connections cleaned up`),e(n)}e(this.lossySub),e(this.reliableSub),e(this.dataTrackSub),this.lossySub=void 0,this.reliableSub=void 0,this.dataTrackSub=void 0,this.reliable.reset()}},mz=typeof MediaRecorder<`u`,hz=mz?MediaRecorder:class{constructor(){throw Error(`MediaRecorder is not available in this environment`)}},gz=class extends hz{constructor(e,t){if(!mz)throw Error(`MediaRecorder is not available in this environment`);super(new MediaStream([e.mediaStreamTrack]),t);let n,r,i=()=>r===void 0,a=()=>{this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r?.close(),r=void 0},o=e=>{r?.error(e),this.removeEventListener(`dataavailable`,n),this.removeEventListener(`stop`,a),this.removeEventListener(`error`,o),r=void 0};this.byteStream=new ReadableStream({start:e=>{r=e,n=t=>J(this,void 0,void 0,function*(){let n;if(t.data.arrayBuffer){let e=yield t.data.arrayBuffer();n=new Uint8Array(e)}else if(t.data.byteArray)n=t.data.byteArray;else throw Error(`no data available!`);i()||e.enqueue(n)}),this.addEventListener(`dataavailable`,n)},cancel:()=>{a()}}),this.addEventListener(`stop`,a),this.addEventListener(`error`,o)}};function _z(){return mz}var vz=1e3,yz=1e4,bz=class extends ${get sender(){return this._sender}set sender(e){this._sender=e}get constraints(){return this._constraints}get hasPreConnectBuffer(){return!!this.localTrackRecorder}constructor(e,t,n){let r=arguments.length>3&&arguments[3]!==void 0&&arguments[3],i=arguments.length>4?arguments[4]:void 0;super(e,t,i),this.manuallyStopped=!1,this.pendingDeviceChange=!1,this._isUpstreamPaused=!1,this.handleTrackMuteEvent=()=>this.debouncedTrackMuteHandler().catch(()=>this.log.debug(`track mute bounce got cancelled by an unmute event`,this.logContext)),this.debouncedTrackMuteHandler=tL(()=>J(this,void 0,void 0,function*(){yield this.pauseUpstream()}),5e3),this.handleTrackUnmuteEvent=()=>J(this,void 0,void 0,function*(){this.debouncedTrackMuteHandler.cancel(`unmute`),yield this.resumeUpstream()}),this.handleEnded=()=>{this.isInBackground&&(this.reacquireTrack=!0),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),this.emit(Q.Ended,this)},this.reacquireTrack=!1,this.providedByUser=r,this.muteLock=new jD,this.pauseUpstreamLock=new jD,this.trackChangeLock=new jD,this.trackChangeLock.lock().then(t=>J(this,void 0,void 0,function*(){try{yield this.setMediaStreamTrack(e,!0)}finally{t()}})),this._constraints=e.getConstraints(),n&&(this._constraints=n)}get id(){return this._mediaStreamTrack.id}get dimensions(){if(this.kind!==$.Kind.Video)return;let e=this._mediaStreamTrack.getSettings(),t=e.width,n=e.height;if(t&&n)return{width:t,height:n}}get isUpstreamPaused(){return this._isUpstreamPaused}get isUserProvided(){return this.providedByUser}get mediaStreamTrack(){return this.processor?.processedTrack??this._mediaStreamTrack}get isLocal(){return!0}getSourceTrackSettings(){return this._mediaStreamTrack.getSettings()}setMediaStreamTrack(e,t,n){return J(this,void 0,void 0,function*(){if(e===this._mediaStreamTrack&&!t)return;this._mediaStreamTrack&&(this.attachedElements.forEach(e=>{mF(this._mediaStreamTrack,e)}),this.debouncedTrackMuteHandler.cancel(`new-track`),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent)),this.mediaStream=new MediaStream([e]),e&&(e.addEventListener(`ended`,this.handleEnded),e.addEventListener(`mute`,this.handleTrackMuteEvent),e.addEventListener(`unmute`,this.handleTrackUnmuteEvent),this._constraints=e.getConstraints());let r;if(this.processor&&e){if(this.log.debug(`restarting processor`,this.logContext),this.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);this.processorElement&&(pF(e,this.processorElement),this.processorElement.muted=!0),yield this.processor.restart({track:e,kind:this.kind,element:this.processorElement,localTrack:this}),r=this.processor.processedTrack}this.sender&&this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(r??e)),!this.providedByUser&&this._mediaStreamTrack!==e&&this._mediaStreamTrack.stop(),this._mediaStreamTrack=e,e&&(this._mediaStreamTrack.enabled=n?!0:!this.isMuted,yield this.resumeUpstream(),this.attachedElements.forEach(t=>{pF(r??e,t)}))})}waitForDimensions(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:vz;return function*(){if(e.kind===$.Kind.Audio)throw Error(`cannot get dimensions for audio tracks`);cP()?.os===`iOS`&&(yield vF(10));let n=Date.now();for(;Date.now()-n<t;){let t=e.dimensions;if(t)return t;yield vF(50)}throw new vP(`unable to get track dimensions after timeout`)}()})}setDeviceId(e){return J(this,void 0,void 0,function*(){return this._constraints.deviceId===e&&this._mediaStreamTrack.getSettings().deviceId===oI(e)||(this._constraints.deviceId=e,this.isMuted?(this.pendingDeviceChange=!0,!0):(yield this.restartTrack(),oI(e)===this._mediaStreamTrack.getSettings().deviceId))})}getDeviceId(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){if(e.source===$.Source.ScreenShare)return;let n=e._mediaStreamTrack.getSettings(),r=n.deviceId,i=n.groupId,a=e.kind===$.Kind.Audio?`audioinput`:`videoinput`;return t?vL.getInstance().normalizeDeviceId(a,r,i):r}()})}mute(){return J(this,void 0,void 0,function*(){return this.setTrackMuted(!0),this})}unmute(){return J(this,void 0,void 0,function*(){return this.setTrackMuted(!1),this})}replaceTrack(e,t){return J(this,void 0,void 0,function*(){let n=yield this.trackChangeLock.lock();try{if(!this.sender)throw new vP(`unable to replace an unpublished track`);let n,r;typeof t==`boolean`?n=t:t!==void 0&&(n=t.userProvidedTrack,r=t.stopProcessor),this.providedByUser=n??!0,this.log.debug(`replace MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(e),r&&this.processor&&(yield this.internalStopProcessor())}finally{n()}return yield this.onSenderTrackSwapped(),this})}onSenderTrackSwapped(){return J(this,void 0,void 0,function*(){})}restart(e,t){return J(this,void 0,void 0,function*(){this.manuallyStopped=!1;let n=yield this.trackChangeLock.lock();try{e||=this._constraints;let n=e,r=n.deviceId,i=n.facingMode,a=LM(e,[`deviceId`,`facingMode`]);this.log.debug(`restarting track with constraints`,Object.assign(Object.assign({},this.logContext),{constraints:e}));let o={audio:!1,video:!1};this.kind===$.Kind.Video?o.video=r||i?{deviceId:r,facingMode:i}:!0:o.audio=!r||Object.assign({deviceId:r},a),this.attachedElements.forEach(e=>{mF(this.mediaStreamTrack,e)}),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.stop();let s=(yield navigator.mediaDevices.getUserMedia(o)).getTracks()[0];return this.kind===$.Kind.Video&&(yield s.applyConstraints(a)),s.addEventListener(`ended`,this.handleEnded),this.log.debug(`re-acquired MediaStreamTrack`,this.logContext),yield this.setMediaStreamTrack(s,!1,t),this._constraints=e,this.pendingDeviceChange=!1,this.emit(Q.Restarted,this),this.manuallyStopped&&(this.log.warn(`track was stopped during a restart, stopping restarted track`,this.logContext),this.stop()),this}finally{n()}})}setTrackMuted(e){this.log.debug(`setting ${this.kind} track ${e?`muted`:`unmuted`}`,this.logContext),(this.isMuted!==e||this._mediaStreamTrack.enabled===e)&&(this.isMuted=e,this._mediaStreamTrack.enabled=!e,this.emit(e?Q.Muted:Q.Unmuted,this))}get needsReAcquisition(){return this._mediaStreamTrack.readyState!==`live`||this._mediaStreamTrack.muted||!this._mediaStreamTrack.enabled||this.reacquireTrack}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return J(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),RF()&&(this.log.debug(`visibility changed, is in Background: ${this.isInBackground}`,this.logContext),!this.isInBackground&&this.needsReAcquisition&&!this.isUserProvided&&!this.isMuted&&(this.log.debug(`track needs to be reacquired, restarting ${this.source}`,this.logContext),yield this.restart(),this.reacquireTrack=!1))})}stop(){var e;this.manuallyStopped=!0,super.stop(),this._mediaStreamTrack.removeEventListener(`ended`,this.handleEnded),this._mediaStreamTrack.removeEventListener(`mute`,this.handleTrackMuteEvent),this._mediaStreamTrack.removeEventListener(`unmute`,this.handleTrackUnmuteEvent),(e=this.processor)==null||e.destroy(),this.processor=void 0}pauseUpstream(){return J(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!0)return;if(!this.sender){this.log.warn(`unable to pause upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!0,this.emit(Q.UpstreamPaused,this);let e=cP();if(e?.name===`Safari`&&qF(e.version,`12.0`)<0)throw new _P(`pauseUpstream is not supported on Safari < 12.`);this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(null))}finally{e()}})}resumeUpstream(){return J(this,void 0,void 0,function*(){let e=yield this.pauseUpstreamLock.lock();try{if(this._isUpstreamPaused===!1)return;if(!this.sender){this.log.warn(`unable to resume upstream for an unpublished track`,this.logContext);return}this._isUpstreamPaused=!1,this.emit(Q.UpstreamResumed,this),this.sender.transport?.state!==`closed`&&(yield this.sender.replaceTrack(this.mediaStreamTrack))}finally{e()}})}getRTCStatsReport(){return J(this,void 0,void 0,function*(){if(this.sender?.getStats)return yield this.sender.getStats()})}setProcessor(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){let r=yield t.trackChangeLock.lock();try{t.log.debug(`setting up processor`,t.logContext);let r=document.createElement(t.kind),i={kind:t.kind,track:t._mediaStreamTrack,element:r,audioContext:t.audioContext,localTrack:t};if(yield e.init(i),t.log.debug(`processor initialized`,t.logContext),t.processor&&(yield t.internalStopProcessor()),t.kind===`unknown`)throw TypeError(`cannot set processor on track of unknown kind`);if(pF(t._mediaStreamTrack,r),r.muted=!0,r.play().catch(e=>{e instanceof DOMException&&e.name===`AbortError`?(t.log.warn(`failed to play processor element, retrying`,Object.assign(Object.assign({},t.logContext),{error:e})),setTimeout(()=>{r.play().catch(e=>{t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{err:e}))})},100)):t.log.error(`failed to play processor element`,Object.assign(Object.assign({},t.logContext),{error:e}))}),t.processor=e,t.processorElement=r,t.processor.processedTrack){for(let e of t.attachedElements)e!==t.processorElement&&n&&(mF(t._mediaStreamTrack,e),pF(t.processor.processedTrack,e));yield t.sender?.replaceTrack(t.processor.processedTrack)}t.emit(Q.TrackProcessorUpdate,t.processor)}finally{r()}yield t.onSenderTrackSwapped()}()})}getProcessor(){return this.processor}stopProcessor(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){let n=yield e.trackChangeLock.lock();try{yield e.internalStopProcessor(t)}finally{n()}yield e.onSenderTrackSwapped()}()})}internalStopProcessor(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r;e.processor&&(e.log.debug(`stopping processor`,e.logContext),(n=e.processor.processedTrack)==null||n.stop(),yield e.processor.destroy(),e.processor=void 0,t||((r=e.processorElement)==null||r.remove(),e.processorElement=void 0),yield e._mediaStreamTrack.applyConstraints(e._constraints),yield e.setMediaStreamTrack(e._mediaStreamTrack,!0),e.emit(Q.TrackProcessorUpdate))}()})}startPreConnectBuffer(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:100;if(!_z()){this.log.warn(`MediaRecorder is not available, cannot start preconnect buffer`,this.logContext);return}if(this.localTrackRecorder){this.log.warn(`preconnect buffer already started`);return}{let e=`audio/webm;codecs=opus`;MediaRecorder.isTypeSupported(e)||(e=`video/mp4`),this.localTrackRecorder=new gz(this,{mimeType:e})}this.localTrackRecorder.start(e),this.autoStopPreConnectBuffer=setTimeout(()=>{this.log.warn(`preconnect buffer timed out, stopping recording automatically`,this.logContext),this.stopPreConnectBuffer()},yz)}stopPreConnectBuffer(){clearTimeout(this.autoStopPreConnectBuffer),this.localTrackRecorder&&=(this.localTrackRecorder.stop(),void 0)}getPreConnectBuffer(){return this.localTrackRecorder?.byteStream}getPreConnectBufferMimeType(){return this.localTrackRecorder?.mimeType}},xz=class extends bz{get enhancedNoiseCancellation(){return this.isKrispNoiseFilterEnabled}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0,i=arguments.length>4?arguments[4]:void 0;super(e,$.Kind.Audio,t,n,i),this.stopOnMute=!1,this.isKrispNoiseFilterEnabled=!1,this.monitorSender=()=>J(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get audio sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}e&&this.prevStats&&(this._currentBitrate=rL(e,this.prevStats)),this.prevStats=e}),this.handleKrispNoiseFilterEnable=()=>{this.isKrispNoiseFilterEnabled=!0,this.log.debug(`Krisp noise filter enabled`,this.logContext),this.emit(Q.AudioTrackFeatureUpdate,this,iA.TF_ENHANCED_NOISE_CANCELLATION,!0)},this.handleKrispNoiseFilterDisable=()=>{this.isKrispNoiseFilterEnabled=!1,this.log.debug(`Krisp noise filter disabled`,this.logContext),this.emit(Q.AudioTrackFeatureUpdate,this,iA.TF_ENHANCED_NOISE_CANCELLATION,!1)},this.audioContext=r,this.checkForSilence()}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===$.Source.Microphone&&this.stopOnMute&&!this.isUserProvided&&(this.log.debug(`stopping mic track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===$.Source.Microphone&&(this.stopOnMute||this._mediaStreamTrack.readyState===`ended`||this.pendingDeviceChange)&&!this.isUserProvided&&(this.log.debug(`reacquiring mic track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}restartTrack(e){return J(this,void 0,void 0,function*(){let t;if(e){let n=YP({audio:e});typeof n.audio!=`boolean`&&(t=n.audio)}yield this.restart(t)})}applyConstraints(e){return J(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{let t=yield this._mediaStreamTrack.applyConstraints(e);return this._constraints=Object.assign(Object.assign({},this._constraints),e),t}finally{t()}})}restart(e,t){let n=Object.create(null,{restart:{get:()=>super.restart}});return J(this,void 0,void 0,function*(){let r=yield n.restart.call(this,e,t);return this.checkForSilence(),r})}startMonitor(){BF()&&(this.monitorInterval||=setInterval(()=>{this.monitorSender()},nL))}setProcessor(e){return J(this,void 0,void 0,function*(){let t=yield this.trackChangeLock.lock();try{if(!VF()&&!this.audioContext)throw Error(`Audio context needs to be set on LocalAudioTrack in order to enable processors`);this.processor&&(yield this.internalStopProcessor());let t={kind:this.kind,track:this._mediaStreamTrack,audioContext:this.audioContext,localTrack:this};this.log.debug(`setting up audio processor ${e.name}`,this.logContext),yield e.init(t),this.processor=e,this.processor.processedTrack&&(yield this.sender?.replaceTrack(this.processor.processedTrack),this.processor.processedTrack.addEventListener(`enable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterEnable),this.processor.processedTrack.addEventListener(`disable-lk-krisp-noise-filter`,this.handleKrispNoiseFilterDisable)),this.emit(Q.TrackProcessorUpdate,this.processor)}finally{t()}})}setAudioContext(e){this.audioContext=e}getSenderStats(){return J(this,void 0,void 0,function*(){if(!this.sender?.getStats)return;let e=yield this.sender.getStats(),t;return e.forEach(n=>{if(n.type===`outbound-rtp`){t={type:`audio`,streamId:n.id,packetsSent:n.packetsSent,bytesSent:n.bytesSent,timestamp:n.timestamp};let r=e.get(n.remoteId);r&&(t.packetsLost=r.packetsLost,t.jitter=r.jitter,t.roundTripTime=r.roundTripTime)}}),t})}checkForSilence(){return J(this,void 0,void 0,function*(){let e=yield XP(this);return e&&(this.isMuted||this.log.debug(`silence detected on local audio track`,this.logContext),this.emit(Q.AudioSilenceDetected)),e})}};function Sz(e,t,n){switch(e.kind){case`audio`:return new xz(e,t,!1,void 0,n);case`video`:return new Vz(e,t,!1,n);default:throw new vP(`unsupported track type: ${e.kind}`)}}var Cz=Object.values(WP),wz=Object.values(GP),Tz=Object.values(KP),Ez=[WP.h180,WP.h360],Dz=[GP.h180,GP.h360],Oz=e=>[{scaleResolutionDownBy:2,fps:e.encoding.maxFramerate}].map(t=>new LP(Math.floor(e.width/t.scaleResolutionDownBy),Math.floor(e.height/t.scaleResolutionDownBy),Math.max(15e4,Math.floor(e.encoding.maxBitrate/(t.scaleResolutionDownBy**2*((e.encoding.maxFramerate??30)/(t.fps??30))))),t.fps,e.encoding.priority)),kz=[`q`,`h`,`f`];function Az(e,t,n,r){let i=r?.videoEncoding;e&&(i=r?.screenShareEncoding);let a=r?.simulcast,o=r?.scalabilityMode,s=r?.videoCodec,c=TF(s,r);if(!i&&!a&&!o||!t||!n)return[{}];i||(i=Nz(e,t,n,s),DM.debug(`using video encoding`,i));let l=i.maxFramerate,u=new LP(t,n,i.maxBitrate,i.maxFramerate,i.priority);if(o&&CF(s)&&!c){let e=new Rz(o),t=[];if(e.spatial>3)throw Error(`unsupported scalabilityMode: ${o}`);let n=cP();if(EF()){let r=e.suffix==`h`?2:3,a=LF(n);for(let n=0;n<e.spatial;n+=1)t.push({rid:kz[2-n],maxBitrate:i.maxBitrate/r**+n,maxFramerate:u.encoding.maxFramerate,scaleResolutionDownBy:a?2**n:void 0});t[0].scalabilityMode=o}else t.push({maxBitrate:i.maxBitrate,maxFramerate:u.encoding.maxFramerate,scalabilityMode:o});return u.encoding.priority&&(t[0].priority=u.encoding.priority,t[0].networkPriority=u.encoding.priority),DM.debug(`using svc encoding`,{encodings:t}),t}if(!a)return[i];let d=e=>(c&&e.forEach(e=>{e.scalabilityMode=o}),e),f;f=e?Lz(r?.screenShareSimulcastLayers)??Fz(e,u):Lz(r?.videoSimulcastLayers)??Fz(e,u);let p;if(f.length>0){let e=f[0];f.length>1&&(p=wO(f,2)[1]);let r=Math.max(t,n);if(r>=960&&p)return d(Iz(t,n,[e,p,u],l));if(r>=480)return d(Iz(t,n,[e,u],l))}return d(Iz(t,n,[u]))}function jz(e,t,n){return CF(e)&&!TF(e,t)?n[0]?.maxBitrate??0:n.reduce((e,t)=>e+(t.maxBitrate??0),0)}function Mz(e,t,n){if(!n.backupCodec||n.backupCodec===!0||n.backupCodec.codec===n.videoCodec)return;t!==n.backupCodec.codec&&DM.warn(`requested a different codec than specified as backup`,{serverRequested:t,backup:n.backupCodec.codec}),n.videoCodec=t,n.videoEncoding=n.backupCodec.encoding;let r=e.mediaStreamTrack.getSettings(),i=r.width??e.dimensions?.width,a=r.height??e.dimensions?.height;return e.source===$.Source.ScreenShare&&n.simulcast&&(n.simulcast=!1),Az(e.source===$.Source.ScreenShare,i,a,n)}function Nz(e,t,n,r){let i=Pz(e,t,n),a=i[0].encoding,o=Math.max(t,n);for(let e=0;e<i.length;e+=1){let t=i[e];if(a=t.encoding,t.width>=o)break}if(r)switch(r){case`av1`:case`h265`:a=Object.assign({},a),a.maxBitrate*=.7;break;case`vp9`:a=Object.assign({},a),a.maxBitrate*=.85}return a}function Pz(e,t,n){if(e)return Tz;let r=t>n?t/n:n/t;return Math.abs(r-16/9)<Math.abs(r-4/3)?Cz:wz}function Fz(e,t){if(e)return Oz(t);let n=t.width,r=t.height,i=n>r?n/r:r/n;return Math.abs(i-16/9)<Math.abs(i-4/3)?Ez:Dz}function Iz(e,t,n,r){let i=[];if(n.forEach((n,a)=>{if(a>=kz.length)return;let o=Math.min(e,t),s={rid:kz[a],scaleResolutionDownBy:Math.max(1,o/Math.min(n.width,n.height)),maxBitrate:n.encoding.maxBitrate},c=r&&n.encoding.maxFramerate?Math.min(r,n.encoding.maxFramerate):n.encoding.maxFramerate;c&&(s.maxFramerate=c);let l=cP(),u=l?.name===`Firefox`&&l.os!==`iOS`||a===0;n.encoding.priority&&u&&(s.priority=n.encoding.priority,s.networkPriority=n.encoding.priority),i.push(s)}),VF()&&GF()===`ios`){let e;i.forEach(t=>{e?t.maxFramerate&&t.maxFramerate>e&&(e=t.maxFramerate):e=t.maxFramerate});let t=!0;i.forEach(n=>{n.maxFramerate!=e&&(t&&(t=!1,DM.info(`Simulcast on iOS React-Native requires all encodings to share the same framerate.`)),DM.info(`Setting framerate of encoding "${n.rid??``}" to ${e}`),n.maxFramerate=e)})}return i}function Lz(e){if(e)return e.slice().sort((e,t)=>{let n=e.encoding,r=t.encoding;return n.maxBitrate>r.maxBitrate?1:n.maxBitrate<r.maxBitrate?-1:n.maxBitrate===r.maxBitrate&&n.maxFramerate&&r.maxFramerate?n.maxFramerate>r.maxFramerate?1:-1:0})}var Rz=class{constructor(e){let t=e.match(/^L(\d)T(\d)(h|_KEY|_KEY_SHIFT){0,1}$/);if(!t)throw Error(`invalid scalability mode`);if(this.spatial=parseInt(t[1]),this.temporal=parseInt(t[2]),t.length>3)switch(t[3]){case`h`:case`_KEY`:case`_KEY_SHIFT`:this.suffix=t[3]}}toString(){return`L${this.spatial}T${this.temporal}${this.suffix??``}`}};function zz(e){switch(e.source){case $.Source.Camera:return`maintain-framerate`;case $.Source.ScreenShare:return`maintain-resolution`;default:return`balanced`}}var Bz=5e3,Vz=class extends bz{get sender(){return this._sender}set sender(e){this._sender=e,this.degradationPreference&&this.setDegradationPreference(this.degradationPreference)}constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0,r=arguments.length>3?arguments[3]:void 0;super(e,$.Kind.Video,t,n,r),this.simulcastCodecs=new Map,this.degradationPreference=`balanced`,this.isCpuConstrained=!1,this.optimizeForPerformance=!1,this.monitorSender=()=>J(this,void 0,void 0,function*(){if(!this.sender){this._currentBitrate=0;return}let e;try{e=yield this.getSenderStats()}catch(e){this.log.error(`could not get video sender stats`,Object.assign(Object.assign({},this.logContext),{error:e}));return}let t=new Map(e.map(e=>[e.rid,e])),n=e.some(e=>e.qualityLimitationReason===`cpu`);if(n!==this.isCpuConstrained&&(this.isCpuConstrained=n,this.isCpuConstrained&&this.emit(Q.CpuConstrained)),this.prevStats){let e=0;t.forEach((t,n)=>{let r=this.prevStats?.get(n);e+=rL(t,r)}),this._currentBitrate=e}this.prevStats=t}),this.senderLock=new jD}get isSimulcast(){return!!(this.sender&&this.sender.getParameters().encodings.length>1)}startMonitor(e){if(this.signalClient=e,!BF())return;let t=this.sender?.getParameters();t&&(this.encodings=t.encodings),!this.monitorInterval&&(this.monitorInterval=setInterval(()=>{this.monitorSender()},nL))}stop(){this._mediaStreamTrack.getConstraints(),this.simulcastCodecs.forEach(e=>{e.mediaStreamTrack.stop()}),super.stop()}pauseUpstream(){let e=Object.create(null,{pauseUpstream:{get:()=>super.pauseUpstream}});return J(this,void 0,void 0,function*(){var t,n,r,i;yield e.pauseUpstream.call(this);try{for(var a=!0,o=HM(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0)i=s.value,a=!1,yield i.sender?.replaceTrack(null)}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}resumeUpstream(){let e=Object.create(null,{resumeUpstream:{get:()=>super.resumeUpstream}});return J(this,void 0,void 0,function*(){var t,n,r,i;yield e.resumeUpstream.call(this);try{for(var a=!0,o=HM(this.simulcastCodecs.values()),s;s=yield o.next(),t=s.done,!t;a=!0){i=s.value,a=!1;let e=i;yield e.sender?.replaceTrack(e.mediaStreamTrack)}}catch(e){n={error:e}}finally{try{!a&&!t&&(r=o.return)&&(yield r.call(o))}finally{if(n)throw n.error}}})}mute(){let e=Object.create(null,{mute:{get:()=>super.mute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.log.debug(`Track already muted`,this.logContext),this):(this.source===$.Source.Camera&&!this.isUserProvided&&(this.log.debug(`stopping camera track`,this.logContext),this._mediaStreamTrack.stop()),yield e.mute.call(this),this)}finally{t()}})}unmute(){let e=Object.create(null,{unmute:{get:()=>super.unmute}});return J(this,void 0,void 0,function*(){let t=yield this.muteLock.lock();try{return this.isMuted?(this.source===$.Source.Camera&&!this.isUserProvided&&(this.log.debug(`reacquiring camera track`,this.logContext),yield this.restart(void 0,!0)),yield e.unmute.call(this),this):(this.log.debug(`Track already unmuted`,this.logContext),this)}finally{t()}})}setTrackMuted(e){super.setTrackMuted(e);for(let t of this.simulcastCodecs.values())t.mediaStreamTrack.enabled=!e}getSenderStats(){return J(this,void 0,void 0,function*(){if(!this.sender?.getStats)return[];let e=[],t=yield this.sender.getStats();return t.forEach(n=>{if(n.type===`outbound-rtp`){let r={type:`video`,streamId:n.id,frameHeight:n.frameHeight,frameWidth:n.frameWidth,framesPerSecond:n.framesPerSecond,framesSent:n.framesSent,firCount:n.firCount,pliCount:n.pliCount,nackCount:n.nackCount,packetsSent:n.packetsSent,bytesSent:n.bytesSent,qualityLimitationReason:n.qualityLimitationReason,qualityLimitationDurations:n.qualityLimitationDurations,qualityLimitationResolutionChanges:n.qualityLimitationResolutionChanges,rid:n.rid??n.id,retransmittedPacketsSent:n.retransmittedPacketsSent,targetBitrate:n.targetBitrate,timestamp:n.timestamp},i=t.get(n.remoteId);i&&(r.jitter=i.jitter,r.packetsLost=i.packetsLost,r.roundTripTime=i.roundTripTime),e.push(r)}}),e.sort((e,t)=>(t.frameWidth??0)-(e.frameWidth??0)),e})}isSvcPublish(e){return CF(e)&&!TF(e,this.publishOptions)}setPublishingQuality(e){let t=[];for(let n=fF.LOW;n<=fF.HIGH;n+=1)t.push(new Jj({quality:n,enabled:n<=e}));this.log.debug(`setting publishing quality. max quality ${e}`,this.logContext),this.setPublishingLayers(this.isSvcPublish(this.codec),t)}restartTrack(e){return J(this,void 0,void 0,function*(){var t,n,r,i;let a;if(e){let t=YP({video:e});typeof t.video!=`boolean`&&(a=t.video)}yield this.restart(a),this.isCpuConstrained=!1;try{for(var o=!0,s=HM(this.simulcastCodecs.values()),c;c=yield s.next(),t=c.done,!t;o=!0){i=c.value,o=!1;let e=i;e.sender&&e.sender.transport?.state!==`closed`&&(e.mediaStreamTrack=this.mediaStreamTrack.clone(),yield e.sender.replaceTrack(e.mediaStreamTrack))}}catch(e){n={error:e}}finally{try{!o&&!t&&(r=s.return)&&(yield r.call(s))}finally{if(n)throw n.error}}yield this.onSenderTrackSwapped()})}onSenderTrackSwapped(){return J(this,void 0,void 0,function*(){yield this.refreshSenderEncodings()})}refreshSenderEncodings(){return J(this,void 0,void 0,function*(){if(!this.sender||!this.publishOptions||this.optimizeForPerformance)return;let e=yield this.senderLock.lock();try{let e;try{e=yield this.waitForDimensions()}catch(e){this.log.warn(`could not determine new track dimensions, skipping encoding recompute`,Object.assign(Object.assign({},this.logContext),{error:e}));return}if(this.lastEncodedDimensions&&this.lastEncodedDimensions.width===e.width&&this.lastEncodedDimensions.height===e.height)return;let n=Az(this.source===$.Source.ScreenShare,e.width,e.height,Object.assign({},this.publishOptions));yield this.applyEncodingsToSender(this.sender,n),this.encodings=n,this.lastEncodedDimensions=e;for(let e of this.simulcastCodecs){var t=wO(e,2);let n=t[0],r=t[1];if(!r.sender||r.sender.transport?.state===`closed`||!BP(n))continue;let i=Object.assign({},this.publishOptions),a=Mz(this,n,i);a&&(yield this.applyEncodingsToSender(r.sender,a),r.encodings=a)}}catch(e){this.log.warn(`failed to apply recomputed encodings`,Object.assign(Object.assign({},this.logContext),{error:e}))}finally{e()}})}applyEncodingsToSender(e,t){return J(this,void 0,void 0,function*(){let n=e.getParameters();n.encodings&&n.encodings.length===t.length&&(n.encodings.forEach((e,n)=>{if(e.active===!1)return;let r=t[n];r.scaleResolutionDownBy!==void 0&&(e.scaleResolutionDownBy=r.scaleResolutionDownBy),r.maxBitrate!==void 0&&(e.maxBitrate=r.maxBitrate),r.maxFramerate!==void 0&&(e.maxFramerate=r.maxFramerate),r.priority!==void 0&&(e.priority=r.priority,e.networkPriority=r.priority)}),this.log.debug(`updating sender encodings after track restart`,Object.assign(Object.assign({},this.logContext),{encodings:n.encodings})),yield e.setParameters(n))})}setProcessor(e){let t=Object.create(null,{setProcessor:{get:()=>super.setProcessor}});return J(this,arguments,void 0,function(e){var n=this;let r=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){var i,a,o,s;if(yield t.setProcessor.call(n,e,r),n.processor?.processedTrack)try{for(var c=!0,l=HM(n.simulcastCodecs.values()),u;u=yield l.next(),i=u.done,!i;c=!0)s=u.value,c=!1,yield s.sender?.replaceTrack(n.processor.processedTrack)}catch(e){a={error:e}}finally{try{!c&&!i&&(o=l.return)&&(yield o.call(l))}finally{if(a)throw a.error}}}()})}setDegradationPreference(e){return J(this,void 0,void 0,function*(){this.degradationPreference=e,yield this.applyDegradationPreference(this.sender);for(let e of this.simulcastCodecs.values())yield this.applyDegradationPreference(e.sender)})}applyDegradationPreference(e){return J(this,void 0,void 0,function*(){if(e)try{this.log.debug(`setting degradationPreference to ${this.degradationPreference}`,this.logContext);let t=e.getParameters();t.degradationPreference=this.degradationPreference,yield e.setParameters(t)}catch(e){this.log.warn(`failed to set degradationPreference`,Object.assign({error:e},this.logContext))}})}addSimulcastTrack(e,t){if(this.simulcastCodecs.has(e)){this.log.error(`${e} already added, skipping adding simulcast codec`,this.logContext);return}let n={codec:e,mediaStreamTrack:this.mediaStreamTrack.clone(),sender:void 0,encodings:t};return this.simulcastCodecs.set(e,n),n}setSimulcastTrackSender(e,t){return J(this,void 0,void 0,function*(){let n=this.simulcastCodecs.get(e);n&&(n.sender=t,yield this.applyDegradationPreference(t),setTimeout(()=>{this.subscribedCodecs&&this.setPublishingCodecs(this.subscribedCodecs)},Bz))})}setPublishingCodecs(e){return J(this,void 0,void 0,function*(){var t,n,r,i,a,o,s;if(this.log.debug(`setting publishing codecs`,Object.assign(Object.assign({},this.logContext),{codecs:e,currentCodec:this.codec})),!this.codec&&e.length>0)return yield this.setPublishingLayers(this.isSvcPublish(e[0].codec),e[0].qualities),[];this.subscribedCodecs=e;let c=[];try{for(t=!0,n=HM(e);r=yield n.next(),i=r.done,!i;t=!0){s=r.value,t=!1;let e=s;if(!this.codec||this.codec===e.codec)yield this.setPublishingLayers(this.isSvcPublish(e.codec),e.qualities);else{let t=this.simulcastCodecs.get(e.codec);if(this.log.debug(`try setPublishingCodec for ${e.codec}`,Object.assign(Object.assign({},this.logContext),{simulcastCodecInfo:t})),!t||!t.sender){for(let t of e.qualities)if(t.enabled){c.push(e.codec);break}}else t.encodings&&(this.log.debug(`try setPublishingLayersForSender ${e.codec}`,this.logContext),yield Hz(t.sender,t.encodings,e.qualities,this.senderLock,this.isSvcPublish(e.codec),this.log,this.logContext))}}}catch(e){a={error:e}}finally{try{!t&&!i&&(o=n.return)&&(yield o.call(n))}finally{if(a)throw a.error}}return c})}setPublishingLayers(e,t){return J(this,void 0,void 0,function*(){if(this.optimizeForPerformance){this.log.info(`skipping setPublishingLayers due to optimized publishing performance`,Object.assign(Object.assign({},this.logContext),{qualities:t}));return}this.log.debug(`setting publishing layers`,Object.assign(Object.assign({},this.logContext),{qualities:t})),this.sender&&this.encodings&&(yield Hz(this.sender,this.encodings,t,this.senderLock,e,this.log,this.logContext))})}prioritizePerformance(){return J(this,void 0,void 0,function*(){if(!this.sender)throw Error(`sender not found`);let e=yield this.senderLock.lock();try{this.optimizeForPerformance=!0;let e=this.sender.getParameters();e.encodings=e.encodings.map((e,t)=>Object.assign(Object.assign({},e),{active:t===0,scaleResolutionDownBy:Math.max(1,Math.ceil((this.mediaStreamTrack.getSettings().height??360)/360)),scalabilityMode:t===0&&CF(this.codec)?`L1T3`:void 0,maxFramerate:t===0?15:0,maxBitrate:t===0?e.maxBitrate:0})),this.log.debug(`setting performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{encodings:e.encodings})),this.encodings=e.encodings,yield this.sender.setParameters(e)}catch(e){this.log.error(`failed to set performance optimised encodings`,Object.assign(Object.assign({},this.logContext),{error:e})),this.optimizeForPerformance=!1}finally{e()}})}handleAppVisibilityChanged(){let e=Object.create(null,{handleAppVisibilityChanged:{get:()=>super.handleAppVisibilityChanged}});return J(this,void 0,void 0,function*(){yield e.handleAppVisibilityChanged.call(this),RF()&&this.isInBackground&&this.source===$.Source.Camera&&(this._mediaStreamTrack.enabled=!1)})}};function Hz(e,t,n,r,i,a,o){return J(this,void 0,void 0,function*(){let s=yield r.lock();a.debug(`setPublishingLayersForSender`,Object.assign(Object.assign({},o),{sender:e,qualities:n,senderEncodings:t}));try{let r=e.getParameters(),s=r.encodings;if(!s)return;if(s.length!==t.length){a.warn(`cannot set publishing layers, encodings mismatch`,Object.assign(Object.assign({},o),{encodings:s,senderEncodings:t}));return}let c=!1;i&&n.some(e=>e.enabled)&&n.forEach(e=>e.enabled=!0),s.forEach((e,r)=>{let i=e.rid??``;i===``&&(i=`q`);let s=Uz(i),l=n.find(e=>e.quality===s);l&&e.active!==l.enabled&&(c=!0,e.active=l.enabled,a.debug(`setting layer ${l.quality} to ${e.active?`enabled`:`disabled`}`,o),jF()&&(l.enabled?(e.scaleResolutionDownBy=t[r].scaleResolutionDownBy,e.maxBitrate=t[r].maxBitrate,e.maxFrameRate=t[r].maxFrameRate):(e.scaleResolutionDownBy=4,e.maxBitrate=10,e.maxFrameRate=2)))}),c&&(r.encodings=s,a.debug(`setting encodings`,Object.assign(Object.assign({},o),{encodings:r.encodings})),yield e.setParameters(r))}finally{s()}})}function Uz(e){switch(e){case`f`:return fF.HIGH;case`h`:return fF.MEDIUM;case`q`:return fF.LOW;default:return fF.HIGH}}function Wz(e,t,n,r){if(!n)return[new TA({quality:fF.HIGH,width:e,height:t,bitrate:0,ssrc:0})];if(r){let r=n[0].scalabilityMode,i=new Rz(r),a=[],o=i.suffix==`h`?1.5:2,s=i.suffix==`h`?2:3;for(let r=0;r<i.spatial;r+=1)a.push(new TA({quality:Math.min(fF.HIGH,i.spatial-1)-r,width:Math.ceil(e/o**+r),height:Math.ceil(t/o**+r),bitrate:n[0].maxBitrate?Math.ceil(n[0].maxBitrate/s**+r):0,ssrc:0}));return a}return n.map(n=>{let r=n.scaleResolutionDownBy??1;return new TA({quality:Uz(n.rid??``),width:Math.ceil(e/r),height:Math.ceil(t/r),bitrate:n.maxBitrate??0,ssrc:0})})}var Gz=2e3,Kz=`leave-reconnect`,qz=1e4,Jz=3e4,Yz=3,Xz=3,Zz;(function(e){e[e.New=0]=`New`,e[e.Connected=1]=`Connected`,e[e.Disconnected=2]=`Disconnected`,e[e.Reconnecting=3]=`Reconnecting`,e[e.Closed=4]=`Closed`})(Zz||={});var Qz=64e3,$z=class extends KM.EventEmitter{get isClosed(){return this._isClosed}get isNewlyCreated(){return this._isNewlyCreated}get pendingReconnect(){return!!this.reconnectTimeout}get serverVersion(){return this.latestJoinResponse?.serverInfo?.version||this.latestJoinResponse?.serverVersion||void 0}get reliableChannel(){return this.dataChannels.reliable}get lossyChannel(){return this.dataChannels.lossy}get dataTrackChannel(){return this.dataChannels.dataTrack}constructor(e){super(),this.options=e,this.rtcConfig={},this.peerConnectionTimeout=XR.peerConnectionTimeout,this.fullReconnectOnNext=!1,this.latestRemoteOfferId=0,this.subscriberPrimary=!1,this.pcState=Zz.New,this._isClosed=!0,this._isNewlyCreated=!0,this.pendingTrackResolvers={},this.reconnectAttempts=0,this.reconnectStart=0,this.attemptingReconnect=!1,this.joinAttempts=0,this.maxJoinAttempts=1,this.shouldFailNext=!1,this.shouldFailOnV1Path=!1,this.log=DM,this.reliableReceivedState=new pR(Jz),this.midToTrackId={},this.isWaitingForNetworkReconnect=!1,this.handleDataChannel=e=>J(this,[e],void 0,function(e){var t=this;let n=e.channel;return function*(){n&&t.dataChannels.adoptSubscriberChannel(n)&&t.log.debug(`on data channel ${n.id}, ${n.label}`)}()}),this.handleDataMessage=e=>J(this,void 0,void 0,function*(){let t=yield this.dataProcessLock.lock();try{let t=yield this.decodeDataMessage(e);if(!t)return;let n=DA.fromBinary(t);if(n.sequence>0&&n.participantSid!==``){let e=this.reliableReceivedState.get(n.participantSid);if(e&&n.sequence<=e)return;this.reliableReceivedState.set(n.participantSid,n.sequence)}if(n.value?.case===`speaker`)this.emit(Z.ActiveSpeakersUpdate,n.value.value.speakers);else if(n.value?.case===`encryptedPacket`){if(!this.e2eeManager){this.log.error(`Received encrypted packet but E2EE not set up`);return}let e;try{e=yield this.e2eeManager.handleEncryptedData(n.value.value.encryptedValue,n.value.value.iv,n.participantIdentity,n.value.value.keyIndex)}catch(e){this.log.debug(`failed to decrypt data packet`,{error:e,participantIdentity:n.participantIdentity});return}let t=new DA({value:AA.fromBinary(e.payload).value,participantIdentity:n.participantIdentity,participantSid:n.participantSid});t.value?.case===`user`&&eB(t,t.value.value),this.emit(Z.DataPacketReceived,t,n.value.value.encryptionType)}else n.value?.case===`user`&&eB(n,n.value.value),this.emit(Z.DataPacketReceived,n,pA.NONE)}finally{t()}}),this.handleDataTrackMessage=e=>J(this,void 0,void 0,function*(){let t=yield this.decodeDataMessage(e);t&&this.emit(`dataTrackPacketReceived`,t)}),this.handleDataError=e=>{if(this._isClosed)return;let t=e.currentTarget.maxRetransmits===0?`lossy`:`reliable`;if(typeof RTCErrorEvent<`u`&&e instanceof RTCErrorEvent&&e.error){let n=e.error;this.log.error(`DataChannel error on ${t}: ${n.message}`,{error:n,errorDetail:n.errorDetail,sctpCauseCode:n.sctpCauseCode})}else this.log.error(`Unknown DataChannel error on ${t}`,{event:e})},this.handleDataChannelClose=e=>()=>{!this._isClosed&&this.pcManager?.publisher.getConnectionState()===`connected`&&this.log.error(`publisher data channel '${rz[e]}' closed unexpectedly`,this.logContext)},this.handleDisconnect=(e,t)=>{if(this._isClosed)return;this.log.warn(`${e} disconnected`),this.reconnectAttempts===0&&(this.reconnectStart=Date.now());let n=e=>{this.log.warn(`could not recover connection after ${this.reconnectAttempts} attempts, ${e}ms. giving up`),this.emit(Z.Disconnected),this.close(`gave up reconnecting after ${this.reconnectAttempts} attempts, ${e}ms`)},r=Date.now()-this.reconnectStart,i=this.getNextRetryDelay({elapsedMs:r,retryCount:this.reconnectAttempts});if(i===null){n(r);return}e===Kz&&(i=0),this.log.debug(`reconnecting in ${i}ms`),this.clearReconnectTimeout(),this.token&&this.emit(Z.TokenRefreshed,this.token),this.reconnectTimeout=kP.setTimeout(()=>this.attemptReconnect(t).finally(()=>this.reconnectTimeout=void 0),i)},this.waitForRestarted=()=>new Promise((e,t)=>{this.pcState===Zz.Connected&&e();let n=()=>{this.off(Z.Disconnected,r),e()},r=()=>{this.off(Z.Restarted,n),t()};this.once(Z.Restarted,n),this.once(Z.Disconnected,r)}),this.onRtpMapAvailable=e=>{let t=new Map;e.forEach(e=>{let n=e.codec.toLowerCase();aI(n)&&t.set(e.payload,n)}),this.emit(Z.RTPVideoMapUpdate,t)},this.handleBrowserOnLine=()=>J(this,void 0,void 0,function*(){this.url&&(yield fetch(cI(this.url),{method:`HEAD`}).then(e=>e.ok).catch(()=>!1))&&(this.log.info(`detected network reconnected`),(this.client.currentState===iR.RECONNECTING||this.isWaitingForNetworkReconnect&&this.client.currentState===iR.CONNECTED)&&(this.clearReconnectTimeout(),this.attemptReconnect(nA.RR_SIGNAL_DISCONNECTED),this.isWaitingForNetworkReconnect=!1))}),this.handleBrowserOffline=()=>J(this,void 0,void 0,function*(){if(this.url)try{yield Promise.race([fetch(cI(this.url),{method:`HEAD`}),vF(4e3).then(()=>Promise.reject())])}catch{window.navigator.onLine===!1&&(this.log.info(`detected network interruption`),this.isWaitingForNetworkReconnect=!0)}}),this.log=OM(e.loggerName??EM.Engine,()=>this.logContext),this.loggerOptions={loggerName:e.loggerName,loggerContextCb:()=>this.logContext},this.client=new cR(void 0,this.loggerOptions),this.client.signalLatency=this.options.expSignalLatency,this.reconnectPolicy=this.options.reconnectPolicy,this.closingLock=new jD,this.dataProcessLock=new jD,this.dataChannels=new pz({isEngineClosed:()=>this.isClosed,isReconnecting:()=>this.attemptingReconnect,onDataMessage:e=>this.handleDataMessage(e),onDataTrackMessage:e=>this.handleDataTrackMessage(e),onDataError:e=>this.handleDataError(e),onChannelClose:e=>this.handleDataChannelClose(e)(),onBufferStatusChanged:(e,t)=>this.emit(Z.DCBufferStatusChanged,t,e)}),this.client.onParticipantUpdate=e=>this.emit(Z.ParticipantUpdate,e),this.client.onConnectionQuality=e=>{this.handleLocalConnectionQuality(e),this.emit(Z.ConnectionQualityUpdate,e)},this.client.onRoomUpdate=e=>this.emit(Z.RoomUpdate,e),this.client.onSubscriptionError=e=>this.emit(Z.SubscriptionError,e),this.client.onSubscriptionPermissionUpdate=e=>this.emit(Z.SubscriptionPermissionUpdate,e),this.client.onSpeakersChanged=e=>this.emit(Z.SpeakersChanged,e),this.client.onStreamStateUpdate=e=>this.emit(Z.StreamStateChanged,e),this.client.onRequestResponse=e=>this.emit(Z.SignalRequestResponse,e),this.client.onParticipantUpdate=e=>this.emit(Z.ParticipantUpdate,e),this.client.onJoined=e=>this.emit(Z.Joined,e)}get logContext(){return{room:this.latestJoinResponse?.room?.name,roomID:this.latestJoinResponse?.room?.sid,participant:this.latestJoinResponse?.participant?.identity,participantID:this.participantSid}}join(e,t,n,r){return J(this,arguments,void 0,function(e,t,n,r){var i=this;let a=arguments.length>4&&arguments[4]!==void 0&&arguments[4];return function*(){var o;i._isNewlyCreated=!1,i.url=e,i.token=t,i.signalOpts=n,i.maxJoinAttempts=n.maxRetries;try{i.joinAttempts+=1,i.setupSignalClientCallbacks();let s=!a&&OI(),c;if(s){i.pcManager||(yield i.configure(),i.applyInitialPublisherLayout());let e=yield i.pcManager?.publisher.createInitialOffer();e&&(c=uR(e.offer,e.offerId))}if(r?.aborted)throw gP.cancelled(`Connection aborted`);if(!a&&i.shouldFailOnV1Path)throw i.shouldFailOnV1Path=!1,gP.serviceNotFound(`Simulated v1 path failure`,`v0-rtc`);let l=yield i.client.join(e,t,n,r,a,c);i._isClosed=!1,i.latestJoinResponse=l,i.participantSid=l.participant?.sid,i.subscriberPrimary=l.subscriberPrimary,s?(o=i.pcManager)==null||o.updateConfiguration(i.makeRTCConfiguration(l)):(i.pcManager||(yield i.configure(l,!a),a||i.applyInitialPublisherLayout()),(!i.subscriberPrimary||l.fastPublish)&&i.negotiate().catch(e=>{i.log.error(e)})),i.registerOnLineListener(),i.clientConfiguration=l.clientConfiguration,i.emit(Z.SignalConnected,l);let u=l.serverInfo;return u||={version:l.serverVersion,region:l.serverRegion},i.log.info(`connected to Livekit Server ${Object.entries(u).map(e=>{let t=wO(e,2);return`${t[0]}: ${t[1]}`}).join(`, `)}`),{joinResponse:l,serverInfo:u}}catch(o){if(o instanceof gP){if(o.reason===hP.ServerUnreachable){if(i.log.warn(`Couldn't connect to server, attempt ${i.joinAttempts} of ${i.maxJoinAttempts}`),i.joinAttempts<i.maxJoinAttempts)return i.join(e,t,n,r,a)}else if(o.reason===hP.ServiceNotFound)return i.log.warn(`Initial connection failed: ${o.message} – Retrying`),i.pcManager&&(i.pcManager.onStateChange=void 0,yield i.cleanupPeerConnections()),i.join(e,t,n,r,!0)}throw o}}()})}close(e){return J(this,void 0,void 0,function*(){let t=yield this.closingLock.lock();if(this.isClosed){t();return}try{this._isClosed=!0,this.joinAttempts=0,this.emit(Z.Closing),this.removeAllListeners(),this.deregisterOnLineListener(),this.clearPendingReconnect(),this.clearLostQualityTimeout(),this.cleanupLossyDataStats(),yield this.cleanupPeerConnections(),yield this.cleanupClient(e)}finally{t()}})}cleanupPeerConnections(){return J(this,void 0,void 0,function*(){this.dataChannels.teardown(),yield this.pcManager?.close(),this.pcManager=void 0,this.transportConnectingSince=void 0,this.reliableReceivedState.clear()})}cleanupLossyDataStats(){this.lossyChannel.stopThresholdTuning()}cleanupClient(e){return J(this,void 0,void 0,function*(){yield this.client.close(!0,e),this.client.resetCallbacks();for(let e of Object.keys(this.pendingTrackResolvers))this.pendingTrackResolvers[e].reject();this.pendingTrackResolvers={}})}addTrack(e){if(this.pendingTrackResolvers[e.cid])throw new vP(`a track with the same ID has already been published`);return new Promise((t,n)=>{let r=kP.setTimeout(()=>{delete this.pendingTrackResolvers[e.cid],n(gP.timeout(`publication of local track timed out, no response from server`))},1e4);this.pendingTrackResolvers[e.cid]={resolve:e=>{kP.clearTimeout(r),t(e)},reject:()=>{kP.clearTimeout(r),n(Error(`Cancelled publication by calling unpublish`))}},this.client.sendAddTrack(e)})}removeTrack(e){if(e.track&&this.pendingTrackResolvers[e.track.id]){let t=this.pendingTrackResolvers[e.track.id].reject;t&&t(),delete this.pendingTrackResolvers[e.track.id]}try{return this.pcManager.removeTrack(e),!0}catch(e){this.log.warn(`failed to remove track`,{error:e})}return!1}updateMuteStatus(e,t){this.client.sendMuteTrack(e,t)}get dataSubscriberReadyState(){return this.dataChannelForKind(rz.RELIABLE,!0)?.readyState}getConnectedServerAddress(){return J(this,void 0,void 0,function*(){return this.pcManager?.getConnectedAddress()})}setRegionStrategy(e){this.regionStrategy=e}configure(e,t){return J(this,void 0,void 0,function*(){if(!(this.pcManager&&this.pcManager.currentState!==ZR.NEW)){if(e){this.participantSid=e.participant?.sid;let n=this.makeRTCConfiguration(e);this.pcManager=new QR(t?`publisher-only`:e.subscriberPrimary?`subscriber-primary`:`publisher-primary`,this.loggerOptions,n)}else{let e=this.makeRTCConfiguration();this.pcManager=new QR(`publisher-only`,this.loggerOptions,e)}this.emit(Z.TransportsCreated,this.pcManager.publisher,this.pcManager.subscriber),this.pcManager.onIceCandidate=(e,t)=>{this.client.sendIceCandidate(e,t)},this.pcManager.onPublisherOffer=(e,t)=>{this.client.sendOffer(e,t)},this.pcManager.onDataChannel=this.handleDataChannel,this.pcManager.onStateChange=(e,t,n)=>J(this,void 0,void 0,function*(){if(this.log.debug(`primary PC state changed ${e}`),this.transportConnectingSince=e===ZR.CONNECTING?Date.now():void 0,[`closed`,`disconnected`,`failed`].includes(t)&&(this.publisherConnectionPromise=void 0),e===ZR.CONNECTED){let e=this.pcState===Zz.New;this.pcState=Zz.Connected,e&&this.emit(Z.Connected,this.latestJoinResponse)}else e===ZR.FAILED&&(this.pcState===Zz.Connected||this.pcState===Zz.Reconnecting)&&(this.pcState=Zz.Disconnected,this.handleDisconnect(`peerconnection failed`,n===`failed`?nA.RR_SUBSCRIBER_FAILED:nA.RR_PUBLISHER_FAILED));let r=this.client.isDisconnected||this.client.currentState===iR.RECONNECTING,i=[ZR.FAILED,ZR.CLOSING,ZR.CLOSED].includes(e);r&&i&&!this._isClosed&&this.emit(Z.Offline)}),this.pcManager.onTrack=e=>{e.streams.length!==0&&this.emit(Z.MediaTrackAdded,e.track,e.streams[0],e.receiver)}}})}setupSignalClientCallbacks(){this.client.onAnswer=(e,t,n)=>J(this,void 0,void 0,function*(){this.pcManager&&(this.log.debug(`received server answer`,{RTCSdpType:e.type,sdp:e.sdp,midToTrackId:n}),this.pcManager.mode===`publisher-only`&&(this.midToTrackId=n),yield this.pcManager.setPublisherAnswer(e,t))}),this.client.onTrickle=(e,t)=>{this.pcManager&&(this.log.debug(`got ICE candidate from peer`,{candidate:e,target:t}),this.pcManager.addIceCandidate(e,t))},this.client.onOffer=(e,t,n)=>J(this,void 0,void 0,function*(){if(this.latestRemoteOfferId=t,!this.pcManager)return;this.midToTrackId=n;let r=yield this.pcManager.createSubscriberAnswerFromOffer(e,t);r&&this.client.sendAnswer(r,t)}),this.client.onLocalTrackPublished=e=>{if(this.log.debug(`received trackPublishedResponse`,{cid:e.cid,track:e.track?.sid}),!this.pendingTrackResolvers[e.cid]){this.log.error(`missing track resolver for ${e.cid}`,{cid:e.cid});return}let t=this.pendingTrackResolvers[e.cid].resolve;delete this.pendingTrackResolvers[e.cid],t(e.track)},this.client.onLocalTrackUnpublished=e=>{this.emit(Z.LocalTrackUnpublished,e)},this.client.onLocalTrackSubscribed=e=>{this.emit(Z.LocalTrackSubscribed,e)},this.client.onTokenRefresh=e=>{this.token=e,this.emit(Z.TokenRefreshed,e)},this.client.onRemoteMuteChanged=(e,t)=>{this.emit(Z.RemoteMute,e,t)},this.client.onSubscribedQualityUpdate=e=>{this.emit(Z.SubscribedQualityUpdate,e)},this.client.onRoomMoved=e=>{this.participantSid=e.participant?.sid,this.latestJoinResponse&&(this.latestJoinResponse.room=e.room),this.emit(Z.RoomMoved,e)},this.client.onMediaSectionsRequirement=e=>{this.addMediaSections(e.numAudios,e.numVideos),this.negotiate()},this.client.onPublishDataTrackResponse=e=>{this.emit(Z.PublishDataTrackResponse,e)},this.client.onUnPublishDataTrackResponse=e=>{this.emit(Z.UnPublishDataTrackResponse,e)},this.client.onDataTrackSubscriberHandles=e=>{this.emit(Z.DataTrackSubscriberHandles,e)},this.client.onClose=()=>{this.handleDisconnect(`signal`,nA.RR_SIGNAL_DISCONNECTED)},this.client.onLeave=e=>{switch(this.log.info(`client leave request received (action=${e?.action})`,{reason:e?.reason}),e.regions&&(this.log.debug(`updating regions`),this.emit(Z.ServerRegionsReported,e.regions)),e.action){case Rj.DISCONNECT:this.emit(Z.Disconnected,e?.reason),this.close(`server leave: ${tA[e.reason]??e.reason}`);break;case Rj.RECONNECT:this.fullReconnectOnNext=!0,this.handleDisconnect(Kz);break;case Rj.RESUME:this.handleDisconnect(Kz)}}}makeRTCConfiguration(e){let t=Object.assign({},this.rtcConfig);if((this.signalOpts?.e2eeEnabled||this.frameMetadataWorker&&!XI())&&KI()&&(this.log.debug(`E2EE - setting up transports with insertable streams`),t.encodedInsertableStreams=!0),t.sdpSemantics=`unified-plan`,t.continualGatheringPolicy=`gather_continually`,!e)return t;if(e.iceServers&&!t.iceServers){let n=[];e.iceServers.forEach(e=>{let t={urls:e.urls};e.username&&(t.username=e.username),e.credential&&(t.credential=e.credential),n.push(t)}),t.iceServers=n}return e.clientConfiguration&&e.clientConfiguration.forceRelay===eA.ENABLED&&(t.iceTransportPolicy=`relay`),t}applyInitialPublisherLayout(){this.createDataChannels(),VF()||this.addMediaSections(Yz,Xz)}addMediaSections(e,t){var n;let r={direction:`recvonly`};for(let t=0;t<e;t++)(n=this.pcManager)==null||n.addPublisherTransceiverOfKind(`audio`,r);let i=this.pcManager?.mode===`publisher-only`;for(let e=0;e<t;e++){let e=this.pcManager?.addPublisherTransceiverOfKind(`video`,r);if(i&&e){let t=wF(e);this.log.debug(`dependency descriptor negotiated for received video`,{negotiated:t})}}}createDataChannels(){this.pcManager&&this.dataChannels.createPublisherChannels(this.pcManager)}decodeDataMessage(e){return J(this,void 0,void 0,function*(){if(e.data instanceof ArrayBuffer)return new Uint8Array(e.data);if(e.data instanceof Blob)return new Uint8Array(yield e.data.arrayBuffer());this.log.error(`unsupported data type`,{data:e.data})})}createSender(e,t,n){return J(this,void 0,void 0,function*(){let r;if(yF())r=yield this.createTransceiverRTCRtpSender(e,t,n);else if(bF())this.log.warn(`using add-track fallback`),r=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new bP(`Required webRTC APIs not supported on this device`);return this.setupFrameMetadataSender(r,t),r})}createSimulcastSender(e,t,n,r){return J(this,void 0,void 0,function*(){let i;if(yF())i=yield this.createSimulcastTransceiverSender(e,t,n,r);else if(bF())this.log.debug(`using add-track fallback`),i=yield this.createRTCRtpSender(e.mediaStreamTrack);else throw new bP(`Cannot stream on this device`);return i&&this.setupFrameMetadataSender(i,n),i})}get frameMetadataWorker(){return(this.options.frameMetadata??this.options.packetTrailer)?.worker}setupFrameMetadataSender(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=this.frameMetadataWorker;if(!n||this.signalOpts?.e2eeEnabled)return;let r=t.frameMetadata??t.packetTrailer,i=QI(r);if(XI()){i&&(e.transform=new RTCRtpScriptTransform(n,{kind:`encode`,packetTrailer:r}));return}if(!ZI(this.options.frameMetadata??this.options.packetTrailer)||!(`createEncodedStreams`in e)){i&&this.log.warn(`frame metadata transform not supported; skipping write`,this.logContext);return}let a=e.createEncodedStreams(),o=a.readable,s=a.writable;i?n.postMessage({kind:`encode`,data:{readableStream:o,writableStream:s,packetTrailer:r}},[o,s]):o.pipeTo(s)}createTransceiverRTCRtpSender(e,t,n){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new bP(`publisher is closed`);let r=[];e.mediaStream&&r.push(e.mediaStream),gI(e)&&(e.codec=t.videoCodec);let i={direction:`sendonly`,streams:r};return n&&(i.sendEncodings=n),(yield this.pcManager.addPublisherTransceiver(e.mediaStreamTrack,i)).sender})}createSimulcastTransceiverSender(e,t,n,r){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new bP(`publisher is closed`);let i={direction:`sendonly`};r&&(i.sendEncodings=r);let a=yield this.pcManager.addPublisherTransceiver(t.mediaStreamTrack,i);if(n.videoCodec)return yield e.setSimulcastTrackSender(n.videoCodec,a.sender),a.sender})}createRTCRtpSender(e){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new bP(`publisher is closed`);return this.pcManager.addPublisherTrack(e)})}handleLocalConnectionQuality(e){if(!this.participantSid)return;let t=e.updates.find(e=>e.participantSid===this.participantSid);t&&(t.quality===$k.LOST?this.scheduleLostQualityReconnect():this.clearLostQualityTimeout())}scheduleLostQualityReconnect(){this.lostQualityTimeout||=kP.setTimeout(()=>{this.lostQualityTimeout=void 0,!(this._isClosed||this.pcState!==Zz.Connected||this.attemptingReconnect)&&this.hasActivePublisherSenders()&&(this.log.warn(`local connection quality lost while publishing, triggering full reconnect`,this.logContext),this.fullReconnectOnNext=!0,this.handleDisconnect(`connection quality lost`,nA.RR_PUBLISHER_FAILED))},qz)}clearLostQualityTimeout(){this.lostQualityTimeout&&=(kP.clearTimeout(this.lostQualityTimeout),void 0)}hasActivePublisherSenders(){return this.pcManager?.publisher.getSenders().some(e=>!!e.track&&e.track.readyState===`live`)??!1}reconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:nA.RR_UNKNOWN;this.fullReconnectOnNext=!0,this.handleDisconnect(`reconcile`,e)}attemptReconnect(e){return J(this,void 0,void 0,function*(){if(this._isClosed)return;if(this.attemptingReconnect){this.log.warn(`already attempting reconnect, returning early`);return}this.clearLostQualityTimeout(),(this.clientConfiguration?.resumeConnection===eA.DISABLED||(this.pcManager?.currentState??ZR.NEW)===ZR.NEW)&&(this.fullReconnectOnNext=!0);let t=this.fullReconnectOnNext;this.fullReconnectOnNext=!1;let n=!1;try{this.attemptingReconnect=!0,t?yield this.restartConnection():yield this.resumeConnection(e),this.clearPendingReconnect(),n=!0}catch(e){this.reconnectAttempts+=1;let n=!0;e instanceof bP?(this.log.debug(`received unrecoverable error`,{error:e}),n=!1):(t||!(e instanceof DP))&&(this.fullReconnectOnNext=!0),n?this.handleDisconnect(`reconnect`,nA.RR_UNKNOWN):(this.log.info(`could not recover connection after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms. giving up`),this.emit(Z.Disconnected),yield this.close(`gave up reconnecting after ${this.reconnectAttempts} attempts, ${Date.now()-this.reconnectStart}ms`))}finally{this.attemptingReconnect=!1,n&&this.fullReconnectOnNext&&!this._isClosed&&(this.log.debug(`full reconnect requested during in-progress attempt, dispatching`),this.handleDisconnect(`reconnect`))}})}getNextRetryDelay(e){try{return this.reconnectPolicy.nextRetryDelayInMs(e)}catch(e){this.log.warn(`encountered error in reconnect policy`,{error:e})}return null}restartConnection(e){return J(this,void 0,void 0,function*(){var t,n;try{if(!this.url||!this.token)throw new bP(`could not reconnect, url or token not saved`);this.log.info(`reconnecting, attempt: ${this.reconnectAttempts}`),this.emit(Z.Restarting),this.client.isDisconnected||(yield this.client.sendLeave()),yield this.cleanupPeerConnections(),yield this.cleanupClient();let n;try{if(!this.signalOpts)throw this.log.warn(`attempted connection restart, without signal options present`),new DP;n=(yield this.join(e??this.url,this.token,this.signalOpts,void 0,!this.options.singlePeerConnection)).joinResponse}catch(e){throw e instanceof gP&&e.reason===hP.NotAllowed?new bP(`could not reconnect, token might be expired`):new DP}if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(this.client.setReconnected(),this.emit(Z.SignalRestarted,n),yield this.waitForPCReconnected(),this.client.currentState!==iR.CONNECTED)throw new DP(`Signal connection got severed during reconnect`);(t=this.regionStrategy)==null||t.resetAttempts(),this.emit(Z.Restarted)}catch(e){let t=yield this.regionStrategy?.getNextUrl();if(t){yield this.restartConnection(t);return}throw(n=this.regionStrategy)==null||n.resetAttempts(),e}})}resumeConnection(e){return J(this,void 0,void 0,function*(){if(!this.url||!this.token)throw new bP(`could not reconnect, url or token not saved`);if(!this.pcManager)throw new bP(`publisher and subscriber connections unset`);this.log.info(`resuming signal connection, attempt ${this.reconnectAttempts}`),this.emit(Z.Resuming);let t;try{this.setupSignalClientCallbacks(),t=yield this.client.reconnect(this.url,this.token,this.participantSid,e)}catch(e){let t=``;throw e instanceof Error&&(t=e.message,this.log.error(e.message,{error:e})),e instanceof gP&&e.reason===hP.NotAllowed?new bP(`could not reconnect, token might be expired`):e instanceof gP&&e.reason===hP.LeaveRequest?e:new DP(t)}if(this.emit(Z.SignalResumed),t){let e=this.makeRTCConfiguration(t);this.pcManager.updateConfiguration(e),this.latestJoinResponse&&(this.latestJoinResponse.serverInfo=t.serverInfo)}else this.log.warn(`Did not receive reconnect response`);if(this.shouldFailNext)throw this.shouldFailNext=!1,Error(`simulated failure`);if(yield this.pcManager.triggerIceRestart(),yield this.waitForPCReconnected(),this.client.currentState!==iR.CONNECTED)throw new DP(`Signal connection got severed during reconnect`);this.client.setReconnected();let n=this.dataChannelForKind(rz.RELIABLE);n?.readyState===`open`&&n.id===null&&this.createDataChannels(),t?.lastMessageSeq&&this.resendReliableMessagesForResume(t.lastMessageSeq).catch(e=>{this.log.warn(`failed to resend reliable messages after resume`,Object.assign(Object.assign({},this.logContext),{error:e}))}),this.emit(Z.Resumed)})}waitForPCInitialConnection(e,t){return J(this,void 0,void 0,function*(){if(!this.pcManager)throw new bP(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(t,e)})}waitForPCReconnected(){return J(this,void 0,void 0,function*(){this.pcState=Zz.Reconnecting,this.log.debug(`waiting for peer connection to reconnect`);try{if(yield vF(Gz),!this.pcManager)throw new bP(`PC manager is closed`);yield this.pcManager.ensurePCTransportConnection(void 0,this.peerConnectionTimeout),this.pcState=Zz.Connected}catch(e){throw this.pcState=Zz.Disconnected,gP.internal(`could not establish PC connection, ${e.message}`)}})}publishRpcAck(e,t){return J(this,void 0,void 0,function*(){let n=new DA({destinationIdentities:[e],kind:OA.RELIABLE,value:{case:`rpcAck`,value:new zA({requestId:t})}});yield this.sendDataPacket(n,rz.RELIABLE)})}sendDataPacket(e,t){return J(this,void 0,void 0,function*(){if(yield this.ensurePublisherConnected(t),this.e2eeManager&&this.e2eeManager.isDataChannelEncryptionEnabled){let t=qI(e);if(t){let n=yield this.e2eeManager.encryptData(t.toBinary());e.value={case:`encryptedPacket`,value:new kA({encryptedValue:n.payload,iv:n.iv,keyIndex:n.keyIndex})}}}t===rz.RELIABLE&&(e.sequence=this.reliableChannel.nextSequence());let n=e.toBinary(),r=Math.min(this.pcManager?.getMaxPublisherMessageSize()??Qz,Qz);if(r!==void 0&&r!==0&&n.byteLength>r)throw new SP(`cannot publish data packet larger than ${r} bytes (got ${n.byteLength})`);t===rz.RELIABLE?yield this.reliableChannel.send(n,e.sequence):yield this.lossyChannel.send(n)})}sendDataTrackFrame(e){return J(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(rz.DATA_TRACK_LOSSY),yield this.dataTrackChannel.send(e)})}resendReliableMessagesForResume(e){return J(this,void 0,void 0,function*(){yield this.ensurePublisherConnected(rz.RELIABLE),yield this.reliableChannel.replay(e)})}flowControlFor(e){return this.dataChannels.channelFor(e)}waitForBufferHeadroom(e){return J(this,void 0,void 0,function*(){return this.flowControlFor(e).waitForHeadroomWithLock()})}ensureDataTransportConnected(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:this.subscriberPrimary;return function*(){if(!t.pcManager)throw new bP(`PC manager is closed`);let r=n?t.pcManager.subscriber:t.pcManager.publisher,i=n?`Subscriber`:`Publisher`;if(!r)throw gP.internal(`${i} connection not set`);let a=!1;if(!n&&!t.dataChannelForKind(e,n)&&(t.createDataChannels(),a=!0),!a&&!n&&!t.pcManager.publisher.isICEConnected&&t.pcManager.publisher.getICEConnectionState()!==`checking`&&(a=!0),a&&t.negotiate().catch(e=>{t.log.error(e)}),t.dataChannelForKind(e,n)?.readyState===`open`)return;let o=new Date().getTime()+t.peerConnectionTimeout;for(;new Date().getTime()<o;){if(r.isICEConnected&&t.dataChannelForKind(e,n)?.readyState===`open`)return;yield vF(50)}throw gP.internal(`could not establish ${i} connection, state: ${r.getICEConnectionState()}`)}()})}ensurePublisherConnected(e){return J(this,void 0,void 0,function*(){this.publisherConnectionPromise||=this.ensureDataTransportConnected(e,!1),yield this.publisherConnectionPromise})}verifyTransport(){if(!this.pcManager)return!1;let e=this.pcManager.currentState;return![ZR.CONNECTING,ZR.CONNECTED].includes(e)||!this.client.ws||this.client.ws.readyState===WebSocket.CLOSED?!1:e===ZR.CONNECTING&&this.transportConnectingSince!==void 0&&Date.now()-this.transportConnectingSince>this.peerConnectionTimeout?(this.log.warn(`transport stuck in connecting state`,this.logContext),!1):!0}negotiate(){return J(this,void 0,void 0,function*(){return new aP((e,t)=>J(this,void 0,void 0,function*(){if(!this.pcManager){t(new xP(`PC manager is closed`));return}this.pcManager.requirePublisher(),this.pcManager.publisher.getTransceivers().length==0&&!this.dataChannels.hasPublisherChannels&&this.createDataChannels();let n=new AbortController,r=()=>{n.abort(),this.log.debug(`engine disconnected while negotiation was ongoing`),e()};this.isClosed&&t(new xP(`cannot negotiate on closed engine`)),this.on(Z.Closing,r),this.on(Z.Restarting,r),this.pcManager.publisher.off(jR.RTPVideoPayloadTypes,this.onRtpMapAvailable),this.pcManager.publisher.once(jR.RTPVideoPayloadTypes,this.onRtpMapAvailable);try{yield this.pcManager.negotiate(n),e()}catch(r){if(n.signal.aborted){e();return}r instanceof xP&&(this.fullReconnectOnNext=!0),this.handleDisconnect(`negotiation`,nA.RR_UNKNOWN),r instanceof Error?t(r):t(Error(String(r)))}finally{this.off(Z.Closing,r),this.off(Z.Restarting,r)}}))})}dataChannelForKind(e,t){return this.dataChannels.getHandle(e,t)}sendSyncState(e,t,n){if(!this.pcManager){this.log.warn(`sync state cannot be sent without peer connection setup`);return}let r=this.pcManager.publisher.getLocalDescription(),i=this.pcManager.publisher.getRemoteDescription(),a=this.pcManager.subscriber?.getRemoteDescription(),o=this.pcManager.subscriber?.getLocalDescription(),s=this.signalOpts?.autoSubscribe??!0,c=[],l=[];e.forEach(e=>{e.isDesired!==s&&c.push(e.trackSid),e.isEnabled||l.push(e.trackSid)}),this.client.sendSyncState(new nM({answer:this.pcManager.mode===`publisher-only`?i?uR({sdp:i.sdp,type:i.type}):void 0:o?uR({sdp:o.sdp,type:o.type}):void 0,offer:this.pcManager.mode===`publisher-only`?r?uR({sdp:r.sdp,type:r.type}):void 0:a?uR({sdp:a.sdp,type:a.type}):void 0,subscription:new Dj({trackSids:c,subscribe:!s,participantTracks:[]}),publishTracks:nF(t),dataChannels:this.dataChannelsInfo(),trackSidsDisabled:l,datachannelReceiveStates:this.reliableReceivedState.map((e,t)=>new rM({publisherSid:t,lastSeq:e})),publishDataTracks:n.map(e=>new mj({info:kL.toProtobuf(e)}))}))}failNext(){this.shouldFailNext=!0}failNextV1Path(){this.shouldFailOnV1Path=!0}dataChannelsInfo(){let e=[],t=(t,n)=>{t?.id!==void 0&&t.id!==null&&e.push(new iM({label:t.label,id:t.id,target:n}))};return t(this.dataChannelForKind(rz.LOSSY),oj.PUBLISHER),t(this.dataChannelForKind(rz.RELIABLE),oj.PUBLISHER),t(this.dataChannelForKind(rz.LOSSY,!0),oj.SUBSCRIBER),t(this.dataChannelForKind(rz.RELIABLE,!0),oj.SUBSCRIBER),e}clearReconnectTimeout(){this.reconnectTimeout&&kP.clearTimeout(this.reconnectTimeout)}clearPendingReconnect(){this.clearReconnectTimeout(),this.reconnectAttempts=0}registerOnLineListener(){BF()&&(window.addEventListener(`online`,this.handleBrowserOnLine),window.addEventListener(`offline`,this.handleBrowserOffline))}deregisterOnLineListener(){BF()&&(window.removeEventListener(`online`,this.handleBrowserOnLine),window.removeEventListener(`offline`,this.handleBrowserOffline))}getTrackIdForReceiver(e){let t=this.pcManager?.getMidForReceiver(e);if(t){let e=Object.entries(this.midToTrackId).find(e=>wO(e,1)[0]===t);if(e)return e[1]}}};function eB(e,t){let n=e.participantIdentity?e.participantIdentity:t.participantIdentity;e.participantIdentity=n,t.participantIdentity=n;let r=e.destinationIdentities.length===0?t.destinationIdentities:e.destinationIdentities;e.destinationIdentities=r,t.destinationIdentities=r}var tB=OM(EM.Region),nB=5e3,rB=3e4,iB=class e{static fetchRegionSettings(t,n,r){return J(this,void 0,void 0,function*(){let i=yield e.fetchLock.lock();try{let e=yield fetch(`${aB(t)}/regions`,{headers:{authorization:`Bearer ${n}`},signal:r});if(e.ok){let t=EI(e.headers),n=t?t*1e3:nB;return{regionSettings:yield e.json(),updatedAtInMs:Date.now(),maxAgeInMs:n}}throw e.status===401?gP.notAllowed(`Could not fetch region settings: ${e.statusText}`,e.status):gP.internal(`Could not fetch region settings: ${e.statusText}`)}catch(e){throw e instanceof gP?e:r?.aborted?gP.cancelled(`Region fetching was aborted`):gP.serverUnreachable(`Could not fetch region settings, ${e instanceof Error?`${e.name}: ${e.message}`:e}`)}finally{i()}})}static scheduleRefetch(t,n,r){return J(this,void 0,void 0,function*(){let i=e.settingsTimeouts.get(t.hostname);clearTimeout(i),e.settingsTimeouts.set(t.hostname,setTimeout(()=>J(this,void 0,void 0,function*(){try{let r=yield e.fetchRegionSettings(t,n);e.updateCachedRegionSettings(t,n,r)}catch(i){if(i instanceof gP&&i.reason===hP.NotAllowed){tB.debug(`token is not valid, cancelling auto region refresh`);return}tB.debug(`auto refetching of region settings failed`,{error:i}),e.scheduleRefetch(t,n,r)}}),r))})}static updateCachedRegionSettings(t,n,r){e.cache.set(t.hostname,r),e.scheduleRefetch(t,n,r.maxAgeInMs)}static stopRefetch(t){let n=e.settingsTimeouts.get(t);n&&(clearTimeout(n),e.settingsTimeouts.delete(t))}static scheduleCleanup(t){let n=e.connectionTrackers.get(t);n&&(n.cleanupTimeout&&clearTimeout(n.cleanupTimeout),n.cleanupTimeout=setTimeout(()=>{let n=e.connectionTrackers.get(t);n&&n.connectionCount===0&&(tB.debug(`stopping region refetch after disconnect delay`,{hostname:t}),e.stopRefetch(t)),n&&(n.cleanupTimeout=void 0)},rB))}static cancelCleanup(t){let n=e.connectionTrackers.get(t);n?.cleanupTimeout&&(clearTimeout(n.cleanupTimeout),n.cleanupTimeout=void 0)}notifyConnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n||(n={connectionCount:0},e.connectionTrackers.set(t,n)),n.connectionCount++,e.cancelCleanup(t)}notifyDisconnected(){let t=this.serverUrl.hostname,n=e.connectionTrackers.get(t);n&&(n.connectionCount=Math.max(0,n.connectionCount-1),n.connectionCount===0&&e.scheduleCleanup(t))}constructor(e,t){this.attemptedRegions=[],this.serverUrl=new URL(e),this.token=t}updateToken(t){this.token=t;let n=this.getServerUrl(),r=e.cache.get(n.hostname);e.scheduleRefetch(this.serverUrl,this.token,r?.maxAgeInMs??nB)}isCloud(){return HF(this.serverUrl)}getServerUrl(){return this.serverUrl}fetchRegionSettings(t){return J(this,void 0,void 0,function*(){return e.fetchRegionSettings(this.serverUrl,this.token,t)})}getNextBestRegionUrl(t){return J(this,void 0,void 0,function*(){if(!this.isCloud())throw Error(`region availability is only supported for LiveKit Cloud domains`);let n=e.cache.get(this.serverUrl.hostname);(!n||Date.now()-n.updatedAtInMs>n.maxAgeInMs)&&(n=yield this.fetchRegionSettings(t),e.updateCachedRegionSettings(this.serverUrl,this.token,n));let r=n.regionSettings.regions.filter(e=>!this.attemptedRegions.find(t=>t.url===e.url));if(r.length>0){let e=r[0];return this.attemptedRegions.push(e),tB.info(`switching to region: ${e.region}`,{region:e.region}),e.url}return null})}resetAttempts(){this.attemptedRegions=[]}setServerReportedRegions(t){e.updateCachedRegionSettings(this.serverUrl,this.token,t)}};iB.cache=new Map,iB.settingsTimeouts=new Map,iB.connectionTrackers=new Map,iB.fetchLock=new jD;function aB(e){return`${e.protocol.replace(`ws`,`http`)}//${e.host}/settings`}function oB(){return new CompressionStream(`deflate-raw`)}function sB(){return new DecompressionStream(`deflate-raw`)}function cB(e,t){return J(this,void 0,void 0,function*(){let n=new DecompressionStream(`deflate-raw`),r=n.writable.getWriter();return r.write(e).catch(()=>{}),r.close().catch(()=>{}),lB(n.readable,t)})}function lB(e,t){return J(this,void 0,void 0,function*(){let n=e.getReader(),r=[],i=0;for(;;){let e=yield n.read(),a=e.done,o=e.value;if(a)break;if(r.push(o),i+=o.byteLength,typeof t==`number`&&i>t)throw yield n.cancel(),new EP(`Decompressed payload exceeds the maximum payload size of ${t} bytes`,TP.PayloadTooLarge)}let a=new Uint8Array(i),o=0;for(let e of r)a.set(e,o),o+=e.byteLength;return a})}var uB=15e3,dB=5e9,fB=class{get info(){return this._info}validateBytesReceived(){let e=arguments.length>0&&arguments[0]!==void 0&&arguments[0];if(typeof this.totalByteSize==`number`&&this.totalByteSize!==0){if(e&&this.bytesReceived<this.totalByteSize)throw new EP(`Not enough chunk(s) received - expected ${this.totalByteSize} bytes of data total, only received ${this.bytesReceived} bytes`,TP.Incomplete);if(this.bytesReceived>this.totalByteSize)throw new EP(`Extra chunk(s) received - expected ${this.totalByteSize} bytes of data total, received ${this.bytesReceived} bytes`,TP.LengthExceeded)}}constructor(e,t,n){this.reader=t,this.totalByteSize=n,this._info=e,this.bytesReceived=0}handleChunkReceived(e){var t;this.bytesReceived+=e.content.byteLength,this.validateBytesReceived();let n=this.totalByteSize?this.bytesReceived/this.totalByteSize:void 0;(t=this.onProgress)==null||t.call(this,n)}},pB=class extends fB{[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>J(this,void 0,void 0,function*(){var n;try{let t=this.signal;if(t?.aborted)throw t.reason;let r=yield new Promise((n,r)=>{if(t){let i=()=>r(t.reason);t.addEventListener(`abort`,i,{once:!0}),e.read().then(n,r).finally(()=>{t.removeEventListener(`abort`,i)})}else e.read().then(n,r)});return r.done?(this.validateBytesReceived(!0),typeof this.totalByteSize==`number`&&((n=this.onProgress)==null||n.call(this,1)),{done:!0,value:void 0}):(this.handleChunkReceived(r.value),{done:!1,value:r.value.content})}catch(e){throw t(),e}}),return(){return J(this,void 0,void 0,function*(){return t(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=new Set,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=HM(s),u;u=yield l.next(),n=u.done,!n;c=!0){a=u.value,c=!1;let e=a;o.add(e)}}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return Array.from(o)}()})}},mB=class extends fB{[Symbol.asyncIterator](){let e=this.reader.getReader();e.closed.catch(()=>{});let t=new TextDecoder(`utf-8`),n=this.signal,r=()=>{e.releaseLock(),this.signal=void 0};return{next:()=>J(this,void 0,void 0,function*(){var i;try{if(n?.aborted)throw n.reason;let r=yield new Promise((t,r)=>{if(n){let i=()=>r(n.reason);n.addEventListener(`abort`,i,{once:!0}),e.read().then(t,r).finally(()=>{n.removeEventListener(`abort`,i)})}else e.read().then(t,r)});if(r.done)return this.validateBytesReceived(!0),typeof this.totalByteSize==`number`&&((i=this.onProgress)==null||i.call(this,1)),{done:!0,value:void 0};{this.handleChunkReceived(r.value);let e;try{e=t.decode(r.value.content)}catch(e){throw new EP(`Cannot decode datastream chunk ${r.value.chunkIndex} as text: ${e}`,TP.DecodeFailed)}return{done:!1,value:e}}}catch(e){throw r(),e}}),return(){return J(this,void 0,void 0,function*(){return r(),{done:!0,value:void 0}})}}}withAbortSignal(e){return this.signal=e,this}readAll(){return J(this,arguments,void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};return function*(){var n,r,i,a;let o=``,s=t.signal?e.withAbortSignal(t.signal):e;try{for(var c=!0,l=HM(s),u;u=yield l.next(),n=u.done,!n;c=!0)a=u.value,c=!1,o+=a}catch(e){r={error:e}}finally{try{!c&&!n&&(i=l.return)&&(yield i.call(l))}finally{if(r)throw r.error}}return o}()})}},hB=class{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:dB;this.log=DM,this.byteStreamControllers=new Map,this.textStreamControllers=new Map,this.byteStreamHandlers=new Map,this.textStreamHandlers=new Map,this.isConnected=!1,this.bufferedPackets=[],this.maxPayloadByteLength=e}setConnected(e){this.isConnected=e,e&&this.flushBufferedPackets()}flushBufferedPackets(){let e=this.bufferedPackets;this.bufferedPackets=[];for(let t of e){let e=t.packet,n=t.encryptionType;this.handleDataStreamPacket(e,n)}}registerTextStreamHandler(e,t){if(this.textStreamHandlers.has(e))throw new EP(`A text stream handler for topic "${e}" has already been set.`,TP.HandlerAlreadyRegistered);this.textStreamHandlers.set(e,t)}unregisterTextStreamHandler(e){this.textStreamHandlers.delete(e)}registerByteStreamHandler(e,t){if(this.byteStreamHandlers.has(e))throw new EP(`A byte stream handler for topic "${e}" has already been set.`,TP.HandlerAlreadyRegistered);this.byteStreamHandlers.set(e,t)}unregisterByteStreamHandler(e){this.byteStreamHandlers.delete(e)}clearControllers(){this.byteStreamControllers.clear(),this.textStreamControllers.clear(),this.bufferedPackets=[]}validateParticipantHasNoActiveDataStreams(e){let t=Array.from(this.textStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e),n=Array.from(this.byteStreamControllers.entries()).filter(t=>t[1].sendingParticipantIdentity===e);if(t.length>0||n.length>0){let a=new EP(`Participant ${e} unexpectedly disconnected in the middle of sending data`,TP.AbnormalEnd);for(let e of n){var r=wO(e,2);let t=r[0];r[1].controller.error(a),this.byteStreamControllers.delete(t)}for(let e of t){var i=wO(e,2);let t=i[0];i[1].controller.error(a),this.textStreamControllers.delete(t)}}}handleDataStreamPacket(e,t){if(!this.isConnected){this.bufferedPackets.push({packet:e,encryptionType:t});return}switch(e.value.case){case`streamHeader`:return this.handleStreamHeader(e.value.value,e.participantIdentity,t);case`streamChunk`:return this.handleStreamChunk(e.value.value,t);case`streamTrailer`:return this.handleStreamTrailer(e.value.value,t);default:throw Error(`DataPacket of value "${e.value.case}" is not data stream related!`)}}handleStreamHeader(e,t,n){switch(e.contentHeader.case){case`byteHeader`:{let r=this.byteStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming byte stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,name:e.contentHeader.value.name??`unknown`,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:fI(e.timestamp),attributes:e.attributes,encryptionType:n},o;switch(e.compression){case $A.DEFLATE_RAW:if(!DI()){DM.warn(`Data stream ${e.streamId} received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping...`);return}o=!0;break;case $A.NONE:o=!1;break;default:DM.warn(`Data stream ${e.streamId} received with unknown compression type ${e.compression}, dropping...`);return}let s=e.inlineContent;if(s!==void 0){r(new pB(a,gB(e.streamId,o?cB(s,this.maxPayloadByteLength):s),fI(e.totalLength)),{identity:t});return}let c=new ReadableStream({start:n=>{if(i=n,this.byteStreamControllers.has(e.streamId))throw new EP(`A data stream read is already in progress for a stream with id ${e.streamId}.`,TP.AlreadyOpened);this.byteStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new pB(a,o?xB(c,e.streamId,this.maxPayloadByteLength):c.pipeThrough(_B(e.streamId)),fI(e.totalLength)),{identity:t});return}case`textHeader`:{let r=this.textStreamHandlers.get(e.topic);if(!r){this.log.debug(`ignoring incoming text stream due to no handler for topic`,e.topic);return}let i,a={id:e.streamId,mimeType:e.mimeType,size:e.totalLength?Number(e.totalLength):void 0,topic:e.topic,timestamp:Number(e.timestamp),attributes:e.attributes,encryptionType:n,attachedStreamIds:e.contentHeader.value.attachedStreamIds},o;switch(e.compression){case $A.DEFLATE_RAW:if(!DI()){DM.warn(`Data stream ${e.streamId} received with deflate-raw compression, but this browser does not have support for DecompressionStream. Dropping...`);return}o=!0;break;case $A.NONE:o=!1;break;default:DM.warn(`Data stream ${e.streamId} received with unknown compression type ${e.compression}, dropping...`);return}let s=e.inlineContent;if(s!==void 0){let n=o?cB(s,this.maxPayloadByteLength):s;r(new mB(a,gB(e.streamId,n),fI(e.totalLength)),{identity:t});return}let c=new ReadableStream({start:n=>{if(i=n,this.textStreamControllers.has(e.streamId))throw new EP(`A data stream read is already in progress for a stream with id ${e.streamId}.`,TP.AlreadyOpened);this.textStreamControllers.set(e.streamId,{info:a,controller:i,startTime:Date.now(),sendingParticipantIdentity:t})}});r(new mB(a,o?SB(c,e.streamId,this.maxPayloadByteLength):c.pipeThrough(_B(e.streamId)),fI(e.totalLength)),{identity:t});return}}}handleStreamChunk(e,t){let n=this.byteStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?n.controller.enqueue(e):(n.controller.error(new EP(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,TP.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId)));let r=this.textStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?r.controller.enqueue(e):(r.controller.error(new EP(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,TP.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId)))}handleStreamTrailer(e,t){let n=this.textStreamControllers.get(e.streamId);n&&(n.info.encryptionType===t?(n.info.attributes=Object.assign(Object.assign({},n.info.attributes),e.attributes),e.reason?n.controller.error(new EP(`Data stream ${e.streamId} closed abnormally: ${e.reason}`,TP.AbnormalEnd)):n.controller.close()):n.controller.error(new EP(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${n.info.encryptionType}`,TP.EncryptionTypeMismatch)),this.textStreamControllers.delete(e.streamId));let r=this.byteStreamControllers.get(e.streamId);r&&(r.info.encryptionType===t?(r.info.attributes=Object.assign(Object.assign({},r.info.attributes),e.attributes),e.reason?r.controller.error(new EP(`Data stream ${e.streamId} closed abnormally: ${e.reason}`,TP.AbnormalEnd)):r.controller.close()):r.controller.error(new EP(`Encryption type mismatch for stream ${e.streamId}. Expected ${t}, got ${r.info.encryptionType}`,TP.EncryptionTypeMismatch)),this.byteStreamControllers.delete(e.streamId))}};function gB(e,t){return new ReadableStream({start:n=>J(this,void 0,void 0,function*(){let r=yield t;n.enqueue(new rj({streamId:e,chunkIndex:BigInt(0),content:r})),n.close()})})}function _B(e){let t=-1;return new TransformStream({transform:(n,r)=>{let i=fI(n.chunkIndex);if(i<=t){DM.warn(`ignoring duplicate chunk ${i} ${n.version>0?`(version ${n.version})`:``} for data stream ${e} (last processed: ${t})`);return}if(i>t+1)throw new EP(`Missing chunk(s) ${t+1}..${i-1} for data stream ${e} - cannot reassemble payload`,TP.Incomplete);t=i,n.content.length!==0&&r.enqueue(n)}})}function vB(){return new TransformStream({transform:(e,t)=>{t.enqueue(e.content)}})}function yB(e){let t=0;return new TransformStream({transform:(n,r)=>{n.byteLength>0&&(r.enqueue(new rj({streamId:e,chunkIndex:pI(t),content:n})),t+=1)}})}function bB(e){let t=new TextDecoder(`utf-8`),n=new TextEncoder,r=0,i=n=>{try{return n?t.decode(n,{stream:!0}):t.decode()}catch(t){throw new EP(`Cannot decode compressed data stream ${e} as text: ${t}`,TP.DecodeFailed)}};return new TransformStream({transform:(t,a)=>{let o=i(t);o.length>0&&(a.enqueue(new rj({streamId:e,chunkIndex:pI(r),content:n.encode(o)})),r+=1)},flush:t=>{let a=i();a.length>0&&(t.enqueue(new rj({streamId:e,chunkIndex:pI(r),content:n.encode(a)})),r+=1)}})}function xB(e,t,n){return e.pipeThrough(_B(t)).pipeThrough(vB()).pipeThrough(sB()).pipeThrough(CB(t,n)).pipeThrough(yB(t))}function SB(e,t,n){return e.pipeThrough(_B(t)).pipeThrough(vB()).pipeThrough(sB()).pipeThrough(CB(t,n)).pipeThrough(bB(t))}function CB(e,t){let n=0;return new TransformStream({transform:(r,i)=>{if(n+=r.byteLength,n>t)throw new EP(`Data stream ${e} exceeds the maximum payload size of ${t} bytes`,TP.PayloadTooLarge);i.enqueue(r)}})}var wB=class{constructor(e,t,n){this.writableStream=e,this.defaultWriter=e.getWriter(),this.onClose=n,this.info=t}write(e){return this.defaultWriter.write(e)}close(){return J(this,void 0,void 0,function*(){var e;yield this.defaultWriter.close(),this.defaultWriter.releaseLock(),(e=this.onClose)==null||e.call(this)})}},TB=class extends wB{},EB=class extends wB{};function DB(e,t,n){return new nj({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:pI(e.timestamp),totalLength:pI(e.size),attributes:e.attributes,compression:n?.compression??$A.NONE,inlineContent:n?.inlineContent,contentHeader:{case:`textHeader`,value:new ej({version:t?.version,attachedStreamIds:e.attachedStreamIds,replyToStreamId:t?.replyToStreamId,operationType:t?.type===`update`?QA.UPDATE:QA.CREATE})}})}function OB(e,t){return new nj({streamId:e.id,mimeType:e.mimeType,topic:e.topic,timestamp:pI(e.timestamp),totalLength:pI(e.size),attributes:e.attributes,compression:t?.compression??$A.NONE,inlineContent:t?.inlineContent,contentHeader:{case:`byteHeader`,value:new tj({name:e.name})}})}function kB(e,t){return new DA({destinationIdentities:t,value:{case:`streamHeader`,value:e}})}var AB=new TextEncoder,jB=class{constructor(e,t,n,r,i){this.engine=e,this.log=t,this.getRemoteParticipantClientProtocol=n,this.getRemoteParticipantCapabilities=r,this.getAllRemoteParticipantIdentities=i}setupEngine(e){this.engine=e}sendText(e,t){return J(this,void 0,void 0,function*(){var n;let r=crypto.randomUUID(),i=AB.encode(e),a=i.byteLength,o=t?.compress??!0,s={id:r,mimeType:`text/plain`,timestamp:Date.now(),topic:t?.topic??``,size:a,attributes:t?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?pA.GCM:pA.NONE},c=o&&DI()&&this.allRecipientsSupportV2(t?.destinationIdentities)&&this.allRecipientsSupportCompression(t?.destinationIdentities)?MB.fromStream(wI(i).pipeThrough(oB())):null;if((!t?.attachments||t.attachments.length===0)&&this.allRecipientsSupportV2(t?.destinationIdentities)){let e=i,r=$A.NONE;if(c){let t=yield c.collect();t.byteLength<i.byteLength&&(e=t,r=$A.DEFLATE_RAW)}let a=kB(DB(s,void 0,{compression:r,inlineContent:e}),t?.destinationIdentities);if(a.toBinary().byteLength<=uB)return yield this.engine.sendDataPacket(a,rz.RELIABLE),(n=t?.onProgress)==null||n.call(t,1),s}let l=(t?.attachments)?.map(()=>crypto.randomUUID()),u=l?l.length+1:1,d=Array(u).fill(0),f=(e,n)=>{var r;d[n]=e,(r=t?.onProgress)==null||r.call(t,d.reduce((e,t)=>e+t,0)/u)};if(c){s.attachedStreamIds=l;let e=kB(DB(s,void 0,{compression:$A.DEFLATE_RAW}),t?.destinationIdentities);yield this.sendChunkedByteStream(e,r,t?.destinationIdentities,c.stream().pipeThrough(NB(i.length,e=>f(e,0)))),i.length===0&&f(1,0)}else{let n=yield this.streamText({streamId:r,totalSize:a,destinationIdentities:t?.destinationIdentities,topic:t?.topic,attachedStreamIds:l,attributes:t?.attributes});yield n.write(e),f(1,0),yield n.close(),s=n.info}return t?.attachments&&l&&(yield Promise.all(t.attachments.map((e,n)=>J(this,void 0,void 0,function*(){return this._sendFile(l[n],e,{topic:t.topic,mimeType:e.type,destinationIdentities:t.destinationIdentities,compress:t.compress,onProgress:e=>{f(e,n+1)}})})))),s})}sendBytes(e,t){return J(this,void 0,void 0,function*(){var n,r;let i=crypto.randomUUID(),a=t?.destinationIdentities,o=t?.compress??!0,s={id:i,name:t?.name??`unknown`,mimeType:t?.mimeType??`application/octet-stream`,timestamp:Date.now(),topic:t?.topic??``,size:e.byteLength,attributes:t?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?pA.GCM:pA.NONE},c=NB(e.length,t?.onProgress),l=o&&DI()&&this.allRecipientsSupportV2(a)&&this.allRecipientsSupportCompression(a)?MB.fromStream(wI(e).pipeThrough(c).pipeThrough(oB())):null;if(this.allRecipientsSupportV2(a)){let r=e,i=$A.NONE;if(l){let t=yield l.collect();t.byteLength<e.byteLength&&(r=t,i=$A.DEFLATE_RAW)}let o=kB(OB(s,{compression:i,inlineContent:r}),a);if(o.toBinary().byteLength<=uB)return yield this.engine.sendDataPacket(o,rz.RELIABLE),(n=t?.onProgress)==null||n.call(t,1),s}let u=kB(OB(s,{compression:l?$A.DEFLATE_RAW:$A.NONE}),a),d=l?l.stream():wI(e).pipeThrough(c);return yield this.sendChunkedByteStream(u,i,a,d),e.length===0&&((r=t?.onProgress)==null||r.call(t,1)),s})}allRecipientsSupportV2(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(e=>this.getRemoteParticipantClientProtocol(e)>=2)}allRecipientsSupportCompression(e){return(e&&e.length>0?e:this.getAllRemoteParticipantIdentities()).every(e=>this.getRemoteParticipantCapabilities(e).includes(qA.CAP_COMPRESSION_DEFLATE_RAW))}sendChunkedByteStream(e,t,n,r){return J(this,void 0,void 0,function*(){var i,a,o,s;let c=this.engine;yield PB(c,e);let l=0;try{for(var u=!0,d=HM(TI(r,uB)),f;f=yield d.next(),i=f.done,!i;u=!0){s=f.value,u=!1;let e=new DA({destinationIdentities:n,value:{case:`streamChunk`,value:new rj({content:s,streamId:t,chunkIndex:pI(l)})}});yield c.sendDataPacket(e,rz.RELIABLE),l+=1}}catch(e){a={error:e}}finally{try{!u&&!i&&(o=d.return)&&(yield o.call(d))}finally{if(a)throw a.error}}yield FB(t,n,c)})}streamText(e){return J(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:`text/plain`,timestamp:Date.now(),topic:e?.topic??``,size:e?.totalSize,attributes:e?.attributes,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?pA.GCM:pA.NONE,attachedStreamIds:e?.attachedStreamIds},i=kB(DB(r,e),n);yield PB(this.engine,i);let a=0,o=this.engine,s=new WritableStream({write(e){return J(this,void 0,void 0,function*(){for(let r of CI(e,uB)){let e=new rj({content:r,streamId:t,chunkIndex:pI(a)}),i=new DA({destinationIdentities:n,value:{case:`streamChunk`,value:e}});yield o.sendDataPacket(i,rz.RELIABLE),a+=1}})},close(){return J(this,void 0,void 0,function*(){yield FB(t,n,o)})},abort(e){console.log(`Sink error:`,e)}}),c=()=>J(this,void 0,void 0,function*(){yield l.close()});o.once(Z.Closing,c);let l=new TB(s,r,()=>this.engine.off(Z.Closing,c));return l})}sendFile(e,t){return J(this,void 0,void 0,function*(){let n=crypto.randomUUID();return yield this._sendFile(n,e,t),{id:n}})}_sendFile(e,t,n){return J(this,void 0,void 0,function*(){var r;let i=n?.destinationIdentities,a=(n?.compress??!0)&&DI()&&this.allRecipientsSupportV2(i)&&this.allRecipientsSupportCompression(i),o={id:e,name:t.name,mimeType:n?.mimeType??t.type,topic:n?.topic??``,timestamp:Date.now(),size:t.size,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?pA.GCM:pA.NONE},s=kB(OB(o,{compression:a?$A.DEFLATE_RAW:$A.NONE}),i),c=t.stream().pipeThrough(NB(t.size,n?.onProgress)),l=a?c.pipeThrough(oB()):c;return yield this.sendChunkedByteStream(s,e,i,l),t.size===0&&((r=n?.onProgress)==null||r.call(n,1)),o})}streamBytes(e){return J(this,void 0,void 0,function*(){let t=e?.streamId??crypto.randomUUID(),n=e?.destinationIdentities,r={id:t,mimeType:e?.mimeType??`application/octet-stream`,topic:e?.topic??``,timestamp:Date.now(),attributes:e?.attributes,size:e?.totalSize,name:e?.name??`unknown`,encryptionType:this.engine.e2eeManager?.isDataChannelEncryptionEnabled?pA.GCM:pA.NONE},i=kB(OB(r),n);yield PB(this.engine,i);let a=0,o=new jD,s=this.engine,c=this.log;return new EB(new WritableStream({write(e){return J(this,void 0,void 0,function*(){let r=yield o.lock(),i=0;try{for(;i<e.byteLength;){let r=e.slice(i,i+uB),o=new DA({destinationIdentities:n,value:{case:`streamChunk`,value:new rj({content:r,streamId:t,chunkIndex:pI(a)})}});yield s.sendDataPacket(o,rz.RELIABLE),a+=1,i+=r.byteLength}}finally{r()}})},close(){return J(this,void 0,void 0,function*(){yield FB(t,n,s)})},abort(e){c.error(`Sink error:`,e)}}),r)})}},MB=class e{constructor(e){this.state=e}static fromStream(t){return new e({type:`stream`,stream:t})}collect(){return J(this,void 0,void 0,function*(){switch(this.state.type){case`stream`:let e=yield lB(this.state.stream);return this.state={type:`collected`,bytes:e},e;case`collected`:return this.state.bytes}})}stream(){switch(this.state.type){case`stream`:return this.state.stream;case`collected`:return wI(this.state.bytes)}}};function NB(e,t){let n=0;return new TransformStream({transform(r,i){n+=r.byteLength,t&&typeof e==`number`&&e>0&&t(Math.min(n/e,1)),i.enqueue(r)}})}function PB(e,t){return J(this,void 0,void 0,function*(){if(t.toBinary().byteLength>uB)throw new EP(`data stream header exceeds the ${uB}-byte limit; reduce attribute size`,TP.HeaderTooLarge);yield e.sendDataPacket(t,rz.RELIABLE)})}function FB(e,t,n){return J(this,void 0,void 0,function*(){let r=new DA({destinationIdentities:t,value:{case:`streamTrailer`,value:new ij({streamId:e})}});yield n.sendDataPacket(r,rz.RELIABLE)})}function IB(e){if(e.length===0)return new AbortController().signal;if(e.length===1)return e[0];for(let t of e)if(t.aborted)return t;let t=new AbortController,n=Array(e.length),r=()=>{for(let e of n)e()};return e.forEach((e,i)=>{let a=()=>{t.abort(e.reason),r()};e.addEventListener(`abort`,a),n[i]=()=>e.removeEventListener(`abort`,a)}),t.signal}function LB(e){let t=new AbortController;return setTimeout(()=>{t.abort(new DOMException(`signal timed out after ${e} ms`,`TimeoutError`))},e),t.signal}var RB=1,zB=2,BB=4,VB=8,HB=0,UB=12,WB=5,GB=7,KB=3,qB=3,JB=2,YB=1,XB=0,ZB=3,QB=2,$B=2,eV=1,tV=0,nV;(function(e){e[e.TooShort=0]=`TooShort`,e[e.HeaderOverrun=1]=`HeaderOverrun`,e[e.MissingExtWords=2]=`MissingExtWords`,e[e.UnsupportedVersion=3]=`UnsupportedVersion`,e[e.InvalidHandle=4]=`InvalidHandle`,e[e.MalformedExt=5]=`MalformedExt`})(nV||={});var rV=class e extends mP{constructor(e,t,n){super(19,e,n),this.name=`DataTrackDeserializeError`,this.reason=t,this.reasonName=nV[t]}static tooShort(){return new e(`Too short to contain a valid header`,nV.TooShort)}static headerOverrun(){return new e(`Header exceeds total packet length`,nV.HeaderOverrun)}static missingExtWords(){return new e(`Extension word indicator is missing`,nV.MissingExtWords)}static unsupportedVersion(t){return new e(`Unsupported version ${t}`,nV.UnsupportedVersion)}static invalidHandle(t){return new e(`invalid track handle: ${t.message}`,nV.InvalidHandle,{cause:t})}static malformedExt(t){return new e(`Extension with tag ${t} is malformed`,nV.MalformedExt)}},iV;(function(e){e[e.TooSmallForHeader=0]=`TooSmallForHeader`,e[e.TooSmallForPayload=1]=`TooSmallForPayload`})(iV||={});var aV=class e extends mP{constructor(e,t,n){super(19,e,n),this.name=`DataTrackSerializeError`,this.reason=t,this.reasonName=iV[t]}static tooSmallForHeader(){return new e(`Buffer cannot fit header`,iV.TooSmallForHeader)}static tooSmallForPayload(){return new e(`Buffer cannot fit payload`,iV.TooSmallForPayload)}},oV=class{toBinary(){let e=this.toBinaryLengthBytes(),t=new ArrayBuffer(e),n=new DataView(t),r=this.toBinaryInto(n);if(e!==r)throw Error(`${this.constructor.name}.toBinary: written bytes (${r} bytes) not equal to allocated array buffer length (${e} bytes).`);return new Uint8Array(t)}},sV;(function(e){e[e.UserTimestamp=2]=`UserTimestamp`,e[e.E2ee=1]=`E2ee`})(sV||={});var cV=class extends oV{},lV=class e extends cV{constructor(e){super(),this.timestamp=e}toBinaryLengthBytes(){return 2+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=RB,t.setUint8(n,e.lengthBytes),n+=RB,t.setBigUint64(n,this.timestamp),n+=VB;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackUserTimestampExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,timestamp:this.timestamp}}};lV.tag=sV.UserTimestamp,lV.lengthBytes=8;var uV=class e extends cV{constructor(e,t){super(),this.keyIndex=e,this.iv=t}toBinaryLengthBytes(){return 2+e.lengthBytes}toBinaryInto(t){let n=0;t.setUint8(n,e.tag),n+=RB,t.setUint8(n,e.lengthBytes),n+=RB,t.setUint8(n,this.keyIndex),n+=RB;for(let e=0;e<this.iv.length;e+=1)t.setUint8(n,this.iv[e]),n+=RB;let r=this.toBinaryLengthBytes();if(n!==r)throw Error(`DataTrackE2eeExtension.toBinaryInto: Wrote ${n} bytes but expected length was ${r} bytes`);return n}toJSON(){return{tag:e.tag,lengthBytes:e.lengthBytes,keyIndex:this.keyIndex,iv:this.iv}}};uV.tag=sV.E2ee,uV.lengthBytes=13;var dV=class e extends oV{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:{};super(),this.userTimestamp=e.userTimestamp,this.e2ee=e.e2ee}toBinaryLengthBytes(){let e=0;return this.userTimestamp&&(e+=this.userTimestamp.toBinaryLengthBytes()),this.e2ee&&(e+=this.e2ee.toBinaryLengthBytes()),e}toBinaryInto(e){let t=0;if(this.e2ee){let n=this.e2ee.toBinaryInto(e);t+=n}if(this.userTimestamp){let n=this.userTimestamp.toBinaryInto(new DataView(e.buffer,e.byteOffset+t));t+=n}let n=this.toBinaryLengthBytes();if(t!==n)throw Error(`DataTrackExtensions.toBinaryInto: Wrote ${t} bytes but expected length was ${n} bytes`);return t}static fromBinary(t){let n=wL(t),r,i,a=0;for(;n.byteLength-a>=2;){let e=n.getUint8(a);a+=RB;let t=n.getUint8(a);if(a+=RB,e!==tV)switch(e){case sV.UserTimestamp:if(n.byteLength-a<lV.lengthBytes)throw rV.malformedExt(e);r=new lV(n.getBigUint64(a)),a+=t;break;case sV.E2ee:if(n.byteLength-a<uV.lengthBytes)throw rV.malformedExt(e);let o=n.getUint8(a),s=new Uint8Array(12);for(let e=0;e<s.length;e+=1){let t=a;t+=RB,t+=e*RB,s[e]=n.getUint8(t)}i=new uV(o,s),a+=t;break;default:if(n.byteLength-a<t)throw rV.malformedExt(e);a+=t}}return[new e({userTimestamp:r,e2ee:i}),n.byteLength]}toJSON(){return{userTimestamp:this.userTimestamp?.toJSON()??null,e2ee:this.e2ee?.toJSON()??null}}},fV={from(e){return{payload:e.payload,extensions:new dV({userTimestamp:e.userTimestamp?new lV(e.userTimestamp):void 0})}},lossyIntoFrame(e){return{payload:e.payload,userTimestamp:e.extensions.userTimestamp?.timestamp}}},pV=Symbol.for(`lk.track`),mV=Symbol.for(`lk.data-track`),hV=class{constructor(e,t,n){this.trackSymbol=pV,this.isLocal=!1,this.typeSymbol=mV,this.info=e,this.manager=t,this.publisherIdentity=n.publisherIdentity}subscribe(e){try{let t=wO(this.manager.openSubscriptionStream(this.info.sid,e?.signal,e?.bufferSize),2),n=t[0];return t[1].catch(()=>{}),n}catch(e){throw e}}setPipelineOptions(e){this.manager.setPipelineOptions(this.info.sid,e)}},gV=class e extends oV{constructor(e){super(),this.marker=e.marker,this.trackHandle=e.trackHandle,this.sequence=e.sequence,this.frameNumber=e.frameNumber,this.timestamp=e.timestamp,this.extensions=e.extensions??new dV}extensionsMetrics(){let e=this.extensions.toBinaryLengthBytes(),t=Math.ceil((QB+e)/4);return{lengthBytes:e,lengthWords:t,paddingLengthBytes:t*4-QB-e}}toBinaryLengthBytes(){let e=this.extensionsMetrics(),t=e.lengthBytes,n=e.paddingLengthBytes,r=UB;return t>0&&(r+=QB+t+n),r}toBinaryInto(e){if(e.byteLength<this.toBinaryLengthBytes())throw aV.tooSmallForHeader();let t=0,n;switch(this.marker){case _V.Inter:n=XB;break;case _V.Final:n=YB;break;case _V.Start:n=JB;break;case _V.Single:n=ZB}t|=n<<KB;let r=this.extensionsMetrics(),i=r.lengthBytes,a=r.lengthWords,o=r.paddingLengthBytes;i>0&&(t|=4);let s=0;if(e.setUint8(s,t),s+=RB,e.setUint8(s,0),s+=RB,e.setUint16(s,this.trackHandle),s+=zB,e.setUint16(s,this.sequence.value),s+=zB,e.setUint16(s,this.frameNumber.value),s+=zB,e.setUint32(s,this.timestamp.asTicks()),s+=BB,i>0){let t=a-1;e.setUint16(s,t),s+=zB;let n=this.extensions.toBinaryInto(new DataView(e.buffer,e.byteOffset+s));s+=n;for(let t=0;t<o;t+=1)e.setUint8(s,0),s+=RB}let c=this.toBinaryLengthBytes();if(s!==c)throw Error(`DataTrackPacketHeader.toBinaryInto: Wrote ${s} bytes but expected length was ${c} bytes`);return c}static fromBinary(t){let n=wL(t);if(n.byteLength<UB)throw rV.tooShort();let r=0,i=n.getUint8(r);r+=RB;let a=i>>WB&GB;if(a>HB)throw rV.unsupportedVersion(a);let o;switch(i>>KB&qB){case JB:o=_V.Start;break;case YB:o=_V.Final;break;case ZB:o=_V.Single;break;case XB:default:o=_V.Inter}let s=(i>>$B&eV)>0;r+=RB;let c;try{c=DL.fromNumber(n.getUint16(r))}catch(e){throw e instanceof EL&&(e.isReason(TL.Reserved)||e.isReason(TL.TooLarge))?rV.invalidHandle(e):e}r+=zB;let l=xL.u16(n.getUint16(r));r+=zB;let u=xL.u16(n.getUint16(r));r+=zB;let d=SL.fromRtpTicks(n.getUint32(r));r+=BB;let f=new dV;if(s){if(n.byteLength-r<zB)throw rV.missingExtWords();let e=n.getUint16(r);r+=zB;let t=4*(e+1)-QB;if(r+t>n.byteLength)throw rV.headerOverrun();let i=new DataView(n.buffer,n.byteOffset+r,t),a=wO(dV.fromBinary(i),2),o=a[0],s=a[1];f=o,r+=s}return[new e({marker:o,trackHandle:c,sequence:l,frameNumber:u,timestamp:d,extensions:f}),r]}toJSON(){return{marker:this.marker,trackHandle:this.trackHandle,sequence:this.sequence.value,frameNumber:this.frameNumber.value,timestamp:this.timestamp.asTicks(),extensions:this.extensions.toJSON()}}},_V;(function(e){e[e.Start=0]=`Start`,e[e.Inter=1]=`Inter`,e[e.Final=2]=`Final`,e[e.Single=3]=`Single`})(_V||={});var vV=class e extends oV{constructor(e,t){super(),this.header=e,this.payload=t}toBinaryLengthBytes(){return this.header.toBinaryLengthBytes()+this.payload.byteLength}toBinaryInto(e){let t=0,n=this.header.toBinaryInto(e);if(t+=n,e.byteLength-t<this.payload.byteLength)throw aV.tooSmallForPayload();for(let n=0;n<this.payload.length;n+=1)e.setUint8(t,this.payload[n]),t+=RB;let r=this.toBinaryLengthBytes();if(t!==r)throw Error(`DataTrackPacket.toBinaryInto: Wrote ${t} bytes but expected length was ${r} bytes`);return r}static fromBinary(t){let n=wL(t),r=wO(gV.fromBinary(n),2),i=r[0],a=r[1],o=n.buffer.slice(n.byteOffset+a,n.byteOffset+n.byteLength);return[new e(i,new Uint8Array(o)),n.byteLength]}toJSON(){return{header:this.header.toJSON(),payload:this.payload}}},yV=OM(EM.DataTracks),bV=class e extends mP{constructor(e,t,n,r){super(19,`Frame ${n} dropped: ${e}`,r),this.name=`DataTrackDepacketizerDropError`,this.reason=t,this.reasonName=xV[t],this.frameNumber=n}static interrupted(t,n){return new e(`Interrupted by the start of a new frame ${n}`,xV.Interrupted,t)}static unknownFrame(t){return new e(`Initial packet was never received.`,xV.UnknownFrame,t)}static bufferFull(t){return new e(`Reorder buffer is full.`,xV.BufferFull,t)}static incomplete(t,n,r){return new e(`Not all packets received before final packet. Received ${n} packets, expected ${r} packets.`,xV.Incomplete,t)}},xV;(function(e){e[e.Interrupted=0]=`Interrupted`,e[e.UnknownFrame=1]=`UnknownFrame`,e[e.BufferFull=2]=`BufferFull`,e[e.Incomplete=3]=`Incomplete`})(xV||={});var SV=class e{constructor(){this.partials=new Map}push(e,t){switch(e.header.marker){case _V.Single:return this.frameFromSingle(e,t);case _V.Start:return this.beginPartial(e,t);case _V.Inter:case _V.Final:return this.pushToPartial(e)}}reset(){this.partials.clear()}peekOldestPartialFrameNumber(){let e=this.partials.keys().next();return e.done?null:e.value}frameFromSingle(e,t){if(e.header.marker!==_V.Single)throw Error(`Depacketizer.frameFromSingle: packet.header.marker was not FrameMarker.Single, found ${e.header.marker}.`);let n=t?.maxPartialFrames??1;if(this.partials.size>=n){let n=this.peekOldestPartialFrameNumber();if(typeof n!=`number`)throw Error(`Depacketizer.frameFromSingle: no oldest frame number found, but partials.size is ${this.partials.size}.`);if(this.partials.delete(n),t?.throwOnInterruption)throw bV.interrupted(n,e.header.frameNumber.value);yV.warn(`Data track frame ${n} was interrupted by single-packet frame ${e.header.frameNumber.value}, dropping.`)}return{payload:e.payload,extensions:e.header.extensions}}beginPartial(e,t){if(e.header.marker!==_V.Start)throw Error(`Depacketizer.beginPartial: packet.header.marker was not FrameMarker.Start, found ${e.header.marker}.`);let n=e.header.sequence,r=e.header.frameNumber.value,i={startSequence:n,extensions:e.header.extensions,payloads:new Map([[n.value,e.payload]])},a=t?.maxPartialFrames??1;for(;this.partials.size>=a;){let e=this.peekOldestPartialFrameNumber();if(typeof e!=`number`)break;if(this.partials.delete(e),t?.throwOnInterruption)throw bV.interrupted(e,r);yV.warn(`Data track partials full (max ${a}), evicted oldest frame ${e} to make room for new frame ${r}.`)}return this.partials.set(r,i),null}pushToPartial(t){if(t.header.marker!==_V.Inter&&t.header.marker!==_V.Final)throw Error(`Depacketizer.pushToPartial: packet.header.marker was not FrameMarker.Inter or FrameMarker.Final, found ${t.header.marker}.`);let n=t.header.frameNumber.value,r=this.partials.get(n);if(!r)throw this.partials.delete(n),bV.unknownFrame(n);if(r.payloads.size>=e.MAX_BUFFER_PACKETS)throw this.partials.delete(n),bV.bufferFull(n);return r.payloads.has(t.header.sequence.value)&&yV.warn(`Data track frame ${n} received duplicate packet for sequence ${t.header.sequence.value}, so replacing with newly received packet.`),r.payloads.set(t.header.sequence.value,t.payload),t.header.marker===_V.Final?this.finalize(n,r,t.header.sequence.value):null}finalize(e,t,n){let r=t.payloads.size,i=0;for(let e of t.payloads.values())i+=e.length;let a=new Uint8Array(i),o=t.startSequence.clone(),s=0;for(;;){let r=t.payloads.get(o.value);if(!r)break;t.payloads.delete(o.value);let i=a.length-s;if(r.length>i)throw Error(`Depacketizer.finalize: Expected at least ${r.length} more bytes left in the payload buffer, only got ${i} bytes.`);if(a.set(r,s),s+=r.length,o.value!=n){o.increment();continue}return this.partials.delete(e),{payload:a,extensions:t.extensions}}throw this.partials.delete(e),bV.incomplete(e,r,n-t.startSequence.value+1)}};SV.MAX_BUFFER_PACKETS=128;var CV;(function(e){e[e.Unpublished=0]=`Unpublished`,e[e.Timeout=1]=`Timeout`,e[e.Disconnected=2]=`Disconnected`,e[e.Cancelled=4]=`Cancelled`})(CV||={});var wV=class e extends mP{constructor(e,t,n){super(22,e,n),this.name=`DataTrackSubscribeError`,this.reason=t,this.reasonName=CV[t]}static unpublished(){return new e(`The track has been unpublished and is no longer available`,CV.Unpublished)}static timeout(){return new e(`Request to subscribe to data track timed-out`,CV.Timeout)}static disconnected(){return new e(`Cannot subscribe to data track when disconnected`,CV.Disconnected)}static cancelled(){return new e(`Subscription to data track cancelled by caller`,CV.Cancelled)}},TV=OM(EM.DataTracks),EV=class{constructor(e){let t=e.e2eeManager!==null;if(e.info.usesE2ee!==t)throw Error(`IncomingDataTrackPipeline: DataTrackInfo.usesE2ee must match presence of decryptionProvider`);let n=new SV;this.publisherIdentity=e.publisherIdentity,this.e2eeManager=e.e2eeManager??null,this.depacketizer=n,this.options=e.pipelineOptions??{}}updateE2eeManager(e){this.e2eeManager=e}setOptions(e){this.options=e}processPacket(e){return J(this,void 0,void 0,function*(){let t=this.depacketize(e);return t&&(yield this.decryptIfNeeded(t))||null})}depacketize(e){let t;try{t=this.depacketizer.push(e,{throwOnInterruption:!1,maxPartialFrames:this.options.maxPartialFrames})}catch(e){return TV.warn(`Data frame depacketize error: ${e}`),null}return t}decryptIfNeeded(e){return J(this,void 0,void 0,function*(){let t=this.e2eeManager;if(!t)return e;let n=e.extensions?.e2ee??null;if(!n)return TV.error(`Missing E2EE meta`),null;let r;try{r=yield t.handleEncryptedData(e.payload,n.iv,this.publisherIdentity,n.keyIndex)}catch(e){return TV.error(`Error decrypting packet: ${e}`),null}return e.payload=r.payload,e})}},DV=OM(EM.DataTracks),OV=1e4,kV=16,AV=class extends KM.EventEmitter{constructor(e){super(),this.descriptors=new Map,this.subscriptionHandles=new Map,this.e2eeManager=e?.e2eeManager??null}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.subscription.type===`active`&&t.subscription.pipeline.updateE2eeManager(e)}setPipelineOptions(e,t){let n=this.descriptors.get(e);if(!n){DV.warn(`Unknown track ${e}, cannot set pipeline options.`);return}n.pipelineOptions=t,n.subscription.type===`active`&&n.subscription.pipeline.setOptions(t)}openSubscriptionStream(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:kV,r=null,i=new iI,a=this.descriptors.get(e),o=()=>{t?.removeEventListener(`abort`,c)},s=()=>{if(o(),!r){DV.warn(`ReadableStream subscribed to ${e} was not started.`);return}if(!a||this.descriptors.get(a.info.sid)!==a){DV.warn(`Unknown track ${e}, skipping cancel...`);return}if(a.subscription.type!==`active`){DV.warn(`Subscription for track ${e} is not active, skipping cancel...`);return}a.subscription.streamControllers.delete(r),a.subscription.streamControllers.size===0&&this.unSubscribeRequest(a.info.sid)},c=()=>{var e;r&&(a?.subscription.type===`active`&&a.subscription.streamControllers.delete(r),r.error(wV.cancelled()),(e=i.reject)==null||e.call(i,wV.cancelled()),s())};return[new ReadableStream({start:n=>{r=n,this.subscribeRequest(e,t).then(()=>J(this,void 0,void 0,function*(){var r,s,l;if(!a||this.descriptors.get(a.info.sid)!==a){DV.error(`Unknown track ${e}`);let t=wV.disconnected();n.error(t),(r=i.reject)==null||r.call(i,t);return}if(a.subscription.type!==`active`){DV.error(`Subscription for track ${e} is not active`);let t=wV.disconnected();n.error(t),(s=i.reject)==null||s.call(i,t);return}if(t?.aborted){c();return}t?.addEventListener(`abort`,c),a.subscription.streamControllers.set(n,o),(l=i.resolve)==null||l.call(i)})).catch(e=>{var t;n.error(e),(t=i.reject)==null||t.call(i,e)})},cancel:()=>{s()}},new CountQueuingStrategy({highWaterMark:n})),i.promise]}subscribeRequest(e,t){return J(this,void 0,void 0,function*(){let n=this.descriptors.get(e);if(!n)throw Error(`Cannot subscribe to unknown track`);let r=(t,n,r)=>J(this,void 0,void 0,function*(){if(t.subscription.type===`active`)return;if(t.subscription.type!==`pending`)throw Error(`Descriptor for track ${e} is not pending, found ${t.subscription.type}`);let i=IB([n,r].filter(e=>e!==void 0)),a=new iI;t.subscription.completionFuture.promise.then(()=>a.resolve?.call(a)).catch(e=>a.reject?.call(a,e));let o=()=>{var e;if(t.subscription.type===`pending`){if(--t.subscription.pendingRequestCount,r?.aborted){t.subscription.cancel();return}if(t.subscription.pendingRequestCount<=0){t.subscription.cancel();return}(e=a.reject)==null||e.call(a,wV.cancelled())}};i.aborted&&o(),i.addEventListener(`abort`,o),yield a.promise,i.removeEventListener(`abort`,o)});switch(n.subscription.type){case`none`:{n.subscription={type:`pending`,completionFuture:new iI,pendingRequestCount:1,cancel:()=>{var e,t;let r=n.subscription;n.subscription={type:`none`},this.emit(`sfuUpdateSubscription`,{sid:n.info.sid,subscribe:!1}),r.type===`pending`&&((t=(e=r.completionFuture).reject)==null||t.call(e,i.aborted?wV.timeout():wV.cancelled()))}},this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!0});let i=LB(OV);yield r(n,t,i);return}case`pending`:n.subscription.pendingRequestCount+=1,yield r(n,t);return;case`active`:return}})}querySubscribed(){return J(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).filter(e=>e.subscription.type===`active`).map(e=>[e.info,e.publisherIdentity])})}unSubscribeRequest(e){let t=this.descriptors.get(e);if(!t)throw Error(`Cannot subscribe to unknown track`);if(t.subscription.type!==`active`){DV.warn(`Unexpected descriptor state in unSubscribeRequest, expected active, found ${t.subscription?.type}`);return}this.closeStreamControllers(t.subscription.streamControllers,e);let n=t.subscription;t.subscription={type:`none`},this.subscriptionHandles.delete(n.subcriptionHandle),this.emit(`sfuUpdateSubscription`,{sid:e,subscribe:!1})}closeStreamControllers(e,t){for(let r of e){var n=wO(r,2);let e=n[0],i=n[1];i();try{e.close()}catch(e){DV.warn(`Failed to close readable stream for track ${t}: ${e}`)}}}receiveSfuPublicationUpdates(e){return J(this,void 0,void 0,function*(){if(e.size===0)return;let t=new Map;for(let r of e.entries()){var n=wO(r,2);let e=n[0],i=n[1],a=new Set;for(let t of i)a.add(t.sid),!this.descriptors.has(t.sid)&&(this.handleSidReassigned(e,t)||(yield this.handleTrackPublished(e,t)));t.set(e,a)}for(let e of t.entries()){var r=wO(e,2);let t=r[0],n=r[1],i=Array.from(this.descriptors.entries()).filter(e=>{let n=wO(e,2);return n[0],n[1].publisherIdentity===t}).map(e=>wO(e,1)[0]).filter(e=>!n.has(e));for(let e of i)this.handleTrackUnpublished(e)}})}queryPublications(){return J(this,void 0,void 0,function*(){return Array.from(this.descriptors.values()).map(e=>e.info)})}handleTrackPublished(e,t){return J(this,void 0,void 0,function*(){if(this.descriptors.has(t.sid)){DV.error(`Existing descriptor for track ${t.sid}`);return}let n={info:t,publisherIdentity:e,subscription:{type:`none`},pipelineOptions:{}};this.descriptors.set(n.info.sid,n);let r=new hV(n.info,this,{publisherIdentity:e});this.emit(`trackPublished`,{track:r})})}handleSidReassigned(e,t){let n=Array.from(this.descriptors.entries()).find(n=>{let r=wO(n,2);r[0];let i=r[1];return i.publisherIdentity===e&&i.info.pubHandle===t.pubHandle});if(!n)return!1;let r=wO(n,2),i=r[0],a=r[1],o=a.info,s=o.name,c=o.usesE2ee;if(s!==t.name||c!==t.usesE2ee)return DV.warn(`Info mismatch for ${i}, treating as new publication`),!1;let l=t.sid;if(DV.debug(`SID reassigned: ${i} -> ${l}`),!this.descriptors.delete(i))return!1;switch(a.info.sid=l,a.subscription.type){case`none`:break;case`pending`:case`active`:this.emit(`sfuUpdateSubscription`,{sid:l,subscribe:!0})}return a.subscription.type===`active`&&this.subscriptionHandles.set(a.subscription.subcriptionHandle,l),this.descriptors.set(l,a),!0}handleTrackUnpublished(e){let t=this.descriptors.get(e);if(!t){DV.error(`Unknown track ${e}`);return}this.descriptors.delete(e),t.subscription.type===`active`&&(this.closeStreamControllers(t.subscription.streamControllers,e),this.subscriptionHandles.delete(t.subscription.subcriptionHandle)),this.emit(`trackUnpublished`,{sid:e,publisherIdentity:t.publisherIdentity})}receivedSfuSubscriberHandles(e){for(let n of e.entries()){var t=wO(n,2);let e=t[0],r=t[1];this.registerSubscriberHandle(e,r)}}registerSubscriberHandle(e,t){var n,r;let i=this.descriptors.get(t);if(!i){DV.error(`Unknown track ${t}`);return}switch(i.subscription.type){case`none`:DV.warn(`No subscription for ${t}`);return;case`active`:this.subscriptionHandles.delete(i.subscription.subcriptionHandle),i.subscription.subcriptionHandle=e,this.subscriptionHandles.set(e,t);return;case`pending`:{DV.debug(`data track subscription activated`,{sid:t,handle:e});let a=new EV({info:i.info,publisherIdentity:i.publisherIdentity,e2eeManager:this.e2eeManager,pipelineOptions:i.pipelineOptions}),o=i.subscription;i.subscription={type:`active`,subcriptionHandle:e,pipeline:a,streamControllers:new Map},this.subscriptionHandles.set(e,t),(r=(n=o.completionFuture).resolve)==null||r.call(n)}}}packetReceived(e){return J(this,void 0,void 0,function*(){let t;try{t=wO(vV.fromBinary(e),1)[0]}catch(e){DV.error(`Failed to deserialize packet: ${e}`);return}let n=this.subscriptionHandles.get(t.header.trackHandle);if(!n){DV.warn(`Unknown subscriber handle ${t.header.trackHandle}`);return}let r=this.descriptors.get(n);if(!r){DV.error(`Missing descriptor for track ${n}`);return}if(r.subscription.type!==`active`){DV.warn(`Received packet for track ${n} without active subscription`);return}let i=yield r.subscription.pipeline.processPacket(t);if(i)for(let e of r.subscription.streamControllers.keys()){if(e.desiredSize!==null&&e.desiredSize<=0){DV.warn(`Cannot send frame to subscribers: readable stream is full (desiredSize is ${e.desiredSize}). To increase this threshold, set a higher 'options.highWaterMark' when calling .subscribe().`);continue}let t=fV.lossyIntoFrame(i);e.enqueue(t)}})}resendSubscriptionUpdates(){for(let t of this.descriptors){var e=wO(t,2);let n=e[0];e[1].subscription.type!==`none`&&this.emit(`sfuUpdateSubscription`,{sid:n,subscribe:!0})}}handleRemoteParticipantDisconnected(e){var t,n;for(let r of this.descriptors.values())if(r.publisherIdentity===e)switch(r.subscription.type){case`none`:break;case`pending`:(n=(t=r.subscription.completionFuture).reject)==null||n.call(t,wV.disconnected());break;case`active`:this.unSubscribeRequest(r.info.sid)}}reset(){var e,t;for(let n of this.descriptors.values())this.emit(`trackUnpublished`,{sid:n.info.sid,publisherIdentity:n.publisherIdentity}),n.subscription.type===`pending`&&((t=(e=n.subscription.completionFuture).reject)==null||t.call(e,wV.disconnected())),n.subscription.type===`active`&&this.closeStreamControllers(n.subscription.streamControllers,n.info.sid);this.descriptors.clear(),this.subscriptionHandles.clear()}},jV=class e extends mP{constructor(e,t,n){super(19,e,n),this.name=`DataTrackPacketizerError`,this.reason=t,this.reasonName=MV[t]}static mtuTooShort(){return new e(`MTU is too short to send frame`,MV.MtuTooShort)}},MV;(function(e){e[e.MtuTooShort=0]=`MtuTooShort`})(MV||={});var NV=class e{constructor(e,t){this.sequence=xL.u16(0),this.frameNumber=xL.u16(0),this.clock=CL.rtpStartingNow(SL.rtpRandom()),this.handle=e,this.mtuSizeBytes=t}static computeFrameMarker(e,t){return t<=1?_V.Single:e===0?_V.Start:e===t-1?_V.Final:_V.Inter}*packetize(t,n){let r=this.frameNumber.getThenIncrement(),i={marker:_V.Inter,trackHandle:this.handle,sequence:xL.u16(0),frameNumber:r,timestamp:n?.now??this.clock.now(),extensions:t.extensions},a=new gV(i).toBinaryLengthBytes();if(a>=this.mtuSizeBytes)throw jV.mtuTooShort();let o=this.mtuSizeBytes-a,s=Math.ceil(t.payload.byteLength/o);for(let n=0,r=0;r<t.payload.byteLength;c=[n+1,r+o],n=c[0],r=c[1]){var c;let a=this.sequence.getThenIncrement(),l=new gV(Object.assign(Object.assign({},i),{marker:e.computeFrameMarker(n,s),sequence:a})),u=Math.min(o,t.payload.byteLength-r);yield new vV(l,new Uint8Array(t.payload.buffer,t.payload.byteOffset+r,u))}}},PV;(function(e){e[e.NotAllowed=0]=`NotAllowed`,e[e.DuplicateName=1]=`DuplicateName`,e[e.Timeout=2]=`Timeout`,e[e.LimitReached=3]=`LimitReached`,e[e.Disconnected=4]=`Disconnected`,e[e.Cancelled=5]=`Cancelled`,e[e.InvalidName=6]=`InvalidName`,e[e.Unknown=7]=`Unknown`})(PV||={});var FV=class e extends mP{constructor(e,t,n){super(21,e,n),this.name=`DataTrackPublishError`,this.reason=t,this.reasonName=PV[t],this.rawMessage=n?.rawMessage}static notAllowed(t){return new e(`Data track publishing unauthorized`,PV.NotAllowed,{rawMessage:t})}static duplicateName(t){return new e(`Track name already taken`,PV.DuplicateName,{rawMessage:t})}static invalidName(t){return new e(`Track name is invalid`,PV.InvalidName,{rawMessage:t})}static timeout(){return new e(`Publish data track timed-out. Does the LiveKit server support data tracks?`,PV.Timeout)}static limitReached(t){return new e(`Data track publication limit reached`,PV.LimitReached,{rawMessage:t})}static unknown(t,n){return new e(`Received RequestResponse for publishDataTrack, but reason was unrecognised (${t}, ${n})`,PV.Unknown)}static disconnected(){return new e(`Room disconnected`,PV.Disconnected)}static cancelled(){return new e(`Publish data track cancelled by caller`,PV.Cancelled)}},IV;(function(e){e[e.TrackUnpublished=0]=`TrackUnpublished`,e[e.Dropped=1]=`Dropped`})(IV||={});var LV=class e extends mP{constructor(e,t,n){super(22,e,n),this.name=`DataTrackPushFrameError`,this.reason=t,this.reasonName=IV[t]}static trackUnpublished(){return new e(`Track is no longer published`,IV.TrackUnpublished)}static dropped(t){return new e(`Frame was dropped`,IV.Dropped,{cause:t})}},RV;(function(e){e[e.Packetizer=0]=`Packetizer`,e[e.Encryption=1]=`Encryption`})(RV||={});var zV=class e extends mP{constructor(e,t,n){super(21,e,n),this.name=`DataTrackOutgoingPipelineError`,this.reason=t,this.reasonName=RV[t]}static packetizer(t){return new e(`Error packetizing frame`,RV.Packetizer,{cause:t})}static encryption(t){return new e(`Error encrypting frame`,RV.Encryption,{cause:t})}},BV=class e{constructor(e,t){this.trackSymbol=pV,this.isLocal=!0,this.typeSymbol=mV,this.handle=null,this.log=DM,this.flushedFuture=new iI,this.isFlushed=!0,this.handleManagerReset=()=>{var e,t;(t=(e=this.flushedFuture).resolve)==null||t.call(e),this.manager.off(`packetsFlushedChange`,this.handleManagerPacketsFlushedChange),this.manager.off(`reset`,this.handleManagerReset)},this.handleManagerPacketsFlushedChange=e=>{var t,n;this.isFlushed=e.isFlushed,e.isFlushed&&((n=(t=this.flushedFuture).resolve)==null||n.call(t),this.flushedFuture=new iI)},this.options=e,this.manager=t,this.log=OM(EM.DataTracks),this.manager.on(`packetsFlushedChange`,this.handleManagerPacketsFlushedChange),this.manager.on(`reset`,this.handleManagerReset)}static withExplicitHandle(t,n,r){let i=new e(t,n);return i.handle=r,i}get info(){let e=this.descriptor;if(e?.type===`active`)return e.info}get descriptor(){return this.handle?this.manager.getDescriptor(this.handle):null}publish(e){return J(this,void 0,void 0,function*(){try{this.handle=yield this.manager.publishRequest(this.options,e)}catch(e){throw e}})}isPublished(){return this.descriptor?.type===`active`&&this.descriptor.publishState!==`unpublished`}tryPush(e){if(!this.handle)throw LV.trackUnpublished();let t=fV.from(e);try{return this.manager.tryProcessAndSend(this.handle,t)}catch(e){throw e}}flush(){return J(this,void 0,void 0,function*(){if(!this.isFlushed)return this.flushedFuture.promise})}unpublish(){return J(this,void 0,void 0,function*(){if(!this.handle){DM.warn(`Data track "${this.options.name}" is not published, so unpublishing has no effect.`);return}try{yield this.manager.unpublishRequest(this.handle)}catch(e){throw e}})}},VV=class e{constructor(t){this.e2eeManager=t.e2eeManager,this.packetizer=new NV(t.info.pubHandle,e.TRANSPORT_MTU_BYTES)}updateE2eeManager(e){this.e2eeManager=e}processFrame(e){return BM(this,arguments,function*(){let t=yield zM(this.encryptIfNeeded(e));try{yield zM(yield*VM(HM(this.packetizer.packetize(t))))}catch(e){throw e instanceof jV?zV.packetizer(e):e}})}encryptIfNeeded(e){return J(this,void 0,void 0,function*(){if(!this.e2eeManager)return e;let t;try{t=yield this.e2eeManager.encryptData(e.payload)}catch(e){throw zV.encryption(e)}return e.payload=t.payload,e.extensions.e2ee=new uV(t.keyIndex,t.iv),e})}};VV.TRANSPORT_MTU_BYTES=16e3;var HV=OM(EM.DataTracks),UV={pending(){return{type:`pending`,completionFuture:new iI}},active(e,t){return{type:`active`,info:e,publishState:`published`,pipeline:new VV({info:e,e2eeManager:t}),unpublishingFuture:new iI}}},WV=1e4,GV=class e extends KM.EventEmitter{constructor(e){super(),this.handleAllocator=new OL,this.descriptors=new Map,this.inFlightPacketCounter=new Map,this.e2eeManager=e?.e2eeManager??null}static withDescriptors(t){let n=new e;return n.descriptors=t,n}updateE2eeManager(e){this.e2eeManager=e;for(let t of this.descriptors.values())t.type===`active`&&t.pipeline.updateE2eeManager(e)}getDescriptor(e){return this.descriptors.get(e)??null}tryProcessAndSend(e,t){return J(this,void 0,void 0,function*(){var n,r,i,a;let o=this.getDescriptor(e);if(o?.type!==`active`||o.publishState===`unpublished`)throw LV.trackUnpublished();if(o.publishState===`republishing`)throw LV.dropped(`Data track republishing`);try{try{for(var s=!0,c=HM(o.pipeline.processFrame(t)),l;l=yield c.next(),n=l.done,!n;s=!0){a=l.value,s=!1;let t=a,n=this.inFlightPacketCounter.get(e)??0;this.inFlightPacketCounter.set(e,n+1),n===0&&this.emit(`packetsFlushedChange`,{handle:e,isFlushed:!1}),this.emit(`packetAvailable`,{handle:e,bytes:t.toBinary()})}}catch(e){r={error:e}}finally{try{!s&&!n&&(i=c.return)&&(yield i.call(c))}finally{if(r)throw r.error}}}catch(e){throw LV.dropped(e)}})}handlePacketSendComplete(e){let t=(this.inFlightPacketCounter.get(e)??0)-1;t<0&&(HV.warn(`OutgoingDataTrackManager.handlePacketSendComplete: inFlightPacketCounter was decremented below 0 (got ${this.inFlightPacketCounter} - resetting to 0. Were more packets send than were emitted?`),t=0),this.inFlightPacketCounter.set(e,t),t===0&&this.emit(`packetsFlushedChange`,{handle:e,isFlushed:!0})}publishRequest(e,t){return J(this,void 0,void 0,function*(){let n=this.handleAllocator.get();if(!n)throw FV.limitReached();let r=LB(WV),i=t?IB([t,r]):r;if(this.descriptors.has(n))throw Error(`Descriptor for handle already exists`);let a=UV.pending();this.descriptors.set(n,a);let o=()=>{var e,t;let i=this.descriptors.get(n);if(!i){HV.warn(`No descriptor for ${n}`);return}this.descriptors.delete(n),this.emit(`sfuUnpublishRequest`,{handle:n}),i.type===`pending`&&((t=(e=i.completionFuture).reject)==null||t.call(e,r.aborted?FV.timeout():FV.cancelled()))};return i.aborted?(o(),a.completionFuture.promise.then(()=>n)):(i.addEventListener(`abort`,o),this.emit(`sfuPublishRequest`,{handle:n,name:e.name,usesE2ee:this.e2eeManager!==null}),yield a.completionFuture.promise,i.removeEventListener(`abort`,o),this.emit(`trackPublished`,{track:BV.withExplicitHandle(e,this,n)}),n)})}queryPublished(){return Array.from(this.descriptors.values()).filter(e=>e.type===`active`).map(e=>e.info)}unpublishRequest(e){return J(this,void 0,void 0,function*(){let t=this.descriptors.get(e);if(!t){HV.warn(`No descriptor for ${e}`);return}if(t.type!==`active`){HV.warn(`Track ${e} not active`);return}this.emit(`sfuUnpublishRequest`,{handle:e}),yield t.unpublishingFuture.promise,this.inFlightPacketCounter.delete(e),this.emit(`trackUnpublished`,{sid:t.info.sid})})}receivedSfuPublishResponse(e,t){var n,r,i,a;let o=this.descriptors.get(e);if(!o){HV.warn(`No descriptor for ${e}`);return}switch(this.descriptors.delete(e),o.type){case`pending`:if(t.type===`ok`){let i=t.data;HV.debug(`SFU accepted publish request for handle ${e}`,{sid:i.sid});let a=i.usesE2ee?this.e2eeManager:null;this.descriptors.set(i.pubHandle,UV.active(i,a)),(r=(n=o.completionFuture).resolve)==null||r.call(n)}else HV.debug(`SFU rejected publish request for handle ${e}`,{error:t.error}),(a=(i=o.completionFuture).reject)==null||a.call(i,t.error);return;case`active`:if(o.publishState!==`republishing`){HV.warn(`Track ${e} already active`);return}if(t.type===`error`){HV.warn(`Republish failed for track ${e}`);return}HV.debug(`Track ${e} republished`),o.info.sid=t.data.sid,o.publishState=`published`,this.descriptors.set(o.info.pubHandle,o)}}receivedSfuUnpublishResponse(e){var t,n;let r=this.descriptors.get(e);if(!r){HV.warn(`No descriptor for ${e}`);return}if(this.descriptors.delete(e),r.type!==`active`){HV.warn(`Track ${e} not active`);return}r.publishState=`unpublished`,(n=(t=r.unpublishingFuture).resolve)==null||n.call(t)}sfuWillRepublishTracks(){var e,t;for(let r of this.descriptors.entries()){var n=wO(r,2);let i=n[0],a=n[1];switch(a.type){case`pending`:this.descriptors.delete(i),(t=(e=a.completionFuture).reject)==null||t.call(e,FV.disconnected());break;case`active`:a.publishState=`republishing`,this.emit(`sfuPublishRequest`,{handle:a.info.pubHandle,name:a.info.name,usesE2ee:a.info.usesE2ee})}}}reset(){return J(this,void 0,void 0,function*(){var e,t,n,r;this.handleAllocator.reset();for(let i of this.descriptors.values())switch(i.type){case`pending`:(t=(e=i.completionFuture).reject)==null||t.call(e,FV.disconnected());break;case`active`:(r=(n=i.unpublishingFuture).resolve)==null||r.call(n),yield this.unpublishRequest(i.info.pubHandle)}this.descriptors.clear(),this.inFlightPacketCounter.clear(),this.emit(`reset`)})}},KV=class e extends Error{constructor(t,n,r,i){super(n),this.code=t,this.message=eH(n,e.MAX_MESSAGE_BYTES),this.data=r?eH(r,e.MAX_DATA_BYTES):void 0,i?.cause!==void 0&&(this.cause=i?.cause)}static fromProto(t){return new e(t.code,t.message,t.data)}toProto(){return new VA({code:this.code,message:this.message,data:this.data})}static builtIn(t,n,r){return new e(e.ErrorCode[t],e.ErrorMessage[t],n,r)}};KV.MAX_MESSAGE_BYTES=256,KV.MAX_DATA_BYTES=15360,KV.ErrorCode={APPLICATION_ERROR:1500,CONNECTION_TIMEOUT:1501,RESPONSE_TIMEOUT:1502,RECIPIENT_DISCONNECTED:1503,RESPONSE_PAYLOAD_TOO_LARGE:1504,SEND_FAILED:1505,UNSUPPORTED_METHOD:1400,RECIPIENT_NOT_FOUND:1401,REQUEST_PAYLOAD_TOO_LARGE:1402,UNSUPPORTED_SERVER:1403,UNSUPPORTED_VERSION:1404},KV.ErrorMessage={APPLICATION_ERROR:`Application error in method handler`,CONNECTION_TIMEOUT:`Connection timeout`,RESPONSE_TIMEOUT:`Response timeout`,RECIPIENT_DISCONNECTED:`Recipient disconnected`,RESPONSE_PAYLOAD_TOO_LARGE:`Response payload too large`,SEND_FAILED:`Failed to send`,UNSUPPORTED_METHOD:`Method not supported at destination`,RECIPIENT_NOT_FOUND:`Recipient not found`,REQUEST_PAYLOAD_TOO_LARGE:`Request payload too large`,UNSUPPORTED_SERVER:`RPC not supported by server`,UNSUPPORTED_VERSION:`Unsupported RPC version`};var qV=15360,JV=`lk.rpc_request`,YV=`lk.rpc_response`,XV;(function(e){e.RPC_REQUEST_ID=`lk.rpc_request_id`,e.RPC_REQUEST_METHOD=`lk.rpc_request_method`,e.RPC_REQUEST_RESPONSE_TIMEOUT_MS=`lk.rpc_request_response_timeout_ms`,e.RPC_REQUEST_VERSION=`lk.rpc_request_version`})(XV||={});var ZV=1,QV=2;function $V(e){return new TextEncoder().encode(e).length}function eH(e,t){if($V(e)<=t)return e;let n=0,r=e.length,i=new TextEncoder;for(;n<r;){let a=Math.floor((n+r+1)/2);i.encode(e.slice(0,a)).length<=t?n=a:r=a-1}return e.slice(0,n)}var tH=class extends KM.EventEmitter{constructor(e,t,n,r){super(),this.pendingAcks=new Map,this.pendingResponses=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n,this.getServerVersion=r}performRpc(e){return J(this,arguments,void 0,function(e){var t=this;let n=e.destinationIdentity,r=e.method,i=e.payload,a=e.responseTimeout,o=a===void 0?15e3:a;return function*(){let e=t.getRemoteParticipantClientProtocol(n);if($V(i)>qV&&e<1)throw KV.builtIn(`REQUEST_PAYLOAD_TOO_LARGE`);let a=t.getServerVersion();if(a&&qF(a,`1.8.0`)<0)throw KV.builtIn(`UNSUPPORTED_SERVER`);let s=Math.max(o,8e3),c=crypto.randomUUID(),l=new iI,u=null,d=setTimeout(()=>{var e;t.pendingAcks.delete(c),(e=l.reject)==null||e.call(l,KV.builtIn(`CONNECTION_TIMEOUT`)),t.pendingResponses.delete(c),u!==null&&clearTimeout(u)},7e3);return t.pendingAcks.set(c,{resolve:()=>{clearTimeout(d)},participantIdentity:n}),t.pendingResponses.set(c,{completionFuture:l,participantIdentity:n}),yield t.publishRpcRequest(n,c,r,i,s,e),u=setTimeout(()=>{var e;t.pendingResponses.delete(c),(e=l.reject)==null||e.call(l,KV.builtIn(`RESPONSE_TIMEOUT`))},o),[c,l.promise.finally(()=>{clearTimeout(u),t.pendingAcks.has(c)&&(t.log.warn(`RPC response received before ack`,c),t.pendingAcks.delete(c),clearTimeout(d))})]}()})}publishRpcRequest(e,t,n,r,i,a){return J(this,void 0,void 0,function*(){if(a>=1){yield this.outgoingDataStreamManager.sendText(r,{topic:JV,destinationIdentities:[e],attributes:{[XV.RPC_REQUEST_ID]:t,[XV.RPC_REQUEST_METHOD]:n,[XV.RPC_REQUEST_RESPONSE_TIMEOUT_MS]:`${i}`,[XV.RPC_REQUEST_VERSION]:`${QV}`}});return}this.emit(`sendDataPacket`,{packet:new DA({destinationIdentities:[e],kind:OA.RELIABLE,value:{case:`rpcRequest`,value:new RA({id:t,method:n,payload:r,responseTimeoutMs:i,version:ZV})}})})})}handleIncomingDataStream(e,t,n){return J(this,void 0,void 0,function*(){let r=n[XV.RPC_REQUEST_ID];if(!r){this.log.warn(`RPC data stream malformed: ${XV.RPC_REQUEST_ID} not set.`);return}let i=this.pendingResponses.get(r);if(i&&i.participantIdentity!==t){this.log.warn(`RPC response stream for ${r} arrived from unexpected sender ${t}, expected ${i.participantIdentity}. Ignoring.`);return}let a;try{a=yield e.readAll()}catch(e){this.log.warn(`Error reading RPC response payload: ${e}`),this.handleIncomingRpcResponseFailure(r,KV.builtIn(`APPLICATION_ERROR`,`Error reading RPC response payload`,{cause:e}));return}this.handleIncomingRpcResponseSuccess(r,a)})}handleIncomingRpcResponseSuccess(e,t){var n,r;let i=this.pendingResponses.get(e);i?((r=(n=i.completionFuture).resolve)==null||r.call(n,t),this.pendingResponses.delete(e)):this.log.error(`Response received for unexpected RPC request`,e)}handleIncomingRpcResponseFailure(e,t){var n,r;let i=this.pendingResponses.get(e);i?((r=(n=i.completionFuture).reject)==null||r.call(n,t),this.pendingResponses.delete(e)):this.log.error(`Response received for unexpected RPC request`,e)}handleIncomingRpcAck(e){let t=this.pendingAcks.get(e);t?(t.resolve(),this.pendingAcks.delete(e)):this.log.error(`Ack received for unexpected RPC request: ${e}`)}handleParticipantDisconnected(e){var t;for(let t of this.pendingAcks){var n=wO(t,2);let r=n[0];n[1].participantIdentity===e&&this.pendingAcks.delete(r)}for(let n of this.pendingResponses){var r=wO(n,2);let a=r[0];var i=r[1];let o=i.participantIdentity,s=i.completionFuture;o===e&&((t=s.reject)==null||t.call(s,KV.builtIn(`RECIPIENT_DISCONNECTED`)),this.pendingResponses.delete(a))}}},nH=class extends KM.EventEmitter{constructor(e,t,n){super(),this.rpcHandlers=new Map,this.log=e,this.outgoingDataStreamManager=t,this.getRemoteParticipantClientProtocol=n}registerRpcMethod(e,t){if(this.rpcHandlers.has(e))throw Error(`RPC handler already registered for method ${e}, unregisterRpcMethod before trying to register again`);this.rpcHandlers.set(e,t)}unregisterRpcMethod(e){this.rpcHandlers.delete(e)}handleIncomingRpcRequest(e,t){return J(this,void 0,void 0,function*(){if(this.publishRpcAck(e,t.id),t.version!==1){this.publishRpcResponsePacket(e,t.id,null,KV.builtIn(`UNSUPPORTED_VERSION`));return}let n=this.rpcHandlers.get(t.method);if(!n){this.publishRpcResponsePacket(e,t.id,null,KV.builtIn(`UNSUPPORTED_METHOD`));return}let r;try{r=yield n({requestId:t.id,callerIdentity:e,payload:t.payload,responseTimeout:t.responseTimeoutMs})}catch(n){let r;n instanceof KV?r=n:(this.log.warn(`Uncaught error returned by RPC handler for ${t.method}. Returning APPLICATION_ERROR instead.`,n),r=KV.builtIn(`APPLICATION_ERROR`,`Uncaught error: ${n?.message??n}`,{cause:n})),this.publishRpcResponsePacket(e,t.id,null,r);return}yield this.publishRpcResponse(e,t.id,r??``)})}handleIncomingDataStream(e,t,n){return J(this,void 0,void 0,function*(){let r=n[XV.RPC_REQUEST_ID],i=n[XV.RPC_REQUEST_METHOD],a=parseInt(n[XV.RPC_REQUEST_RESPONSE_TIMEOUT_MS],10),o=parseInt(n[XV.RPC_REQUEST_VERSION],10);if(!r||!i||Number.isNaN(a)||Number.isNaN(o)){this.log.warn(`RPC data stream malformed: ${XV.RPC_REQUEST_ID} / ${XV.RPC_REQUEST_METHOD} / ${XV.RPC_REQUEST_RESPONSE_TIMEOUT_MS} / ${XV.RPC_REQUEST_VERSION} not set.`),this.publishRpcResponsePacket(t,r,null,KV.builtIn(`APPLICATION_ERROR`,`RPC data stream malformed`));return}if(this.publishRpcAck(t,r),o!==QV){this.publishRpcResponsePacket(t,r,null,KV.builtIn(`UNSUPPORTED_VERSION`));return}let s;try{s=yield e.readAll()}catch(e){this.log.warn(`Error reading RPC request payload: ${e}`),this.publishRpcResponsePacket(t,r,null,KV.builtIn(`APPLICATION_ERROR`,`Error reading RPC request payload`,{cause:e}));return}let c=this.rpcHandlers.get(i);if(!c){this.publishRpcResponsePacket(t,r,null,KV.builtIn(`UNSUPPORTED_METHOD`));return}let l;try{l=yield c({requestId:r,callerIdentity:t,payload:s,responseTimeout:a})}catch(e){let n;e instanceof KV?n=e:(this.log.warn(`Uncaught error returned by RPC handler for ${i}. Returning APPLICATION_ERROR instead.`,e),n=KV.builtIn(`APPLICATION_ERROR`)),this.publishRpcResponsePacket(t,r,null,n);return}yield this.publishRpcResponse(t,r,l??``)})}publishRpcAck(e,t){this.emit(`sendDataPacket`,{packet:new DA({destinationIdentities:[e],kind:OA.RELIABLE,value:{case:`rpcAck`,value:new zA({requestId:t})}})})}publishRpcResponsePacket(e,t,n,r){this.emit(`sendDataPacket`,{packet:new DA({destinationIdentities:[e],kind:OA.RELIABLE,value:{case:`rpcResponse`,value:new BA({requestId:t,value:r?{case:`error`,value:r.toProto()}:{case:`payload`,value:n??``}})}})})}publishRpcResponse(e,t,n){return J(this,void 0,void 0,function*(){if(this.getRemoteParticipantClientProtocol(e)>=1){yield this.outgoingDataStreamManager.sendText(n,{topic:YV,destinationIdentities:[e],attributes:{[XV.RPC_REQUEST_ID]:t}});return}if($V(n)>qV){this.log.warn(`RPC Response payload too large for request ${t}. To send larger responses, consider updating the sending client.`),this.publishRpcResponsePacket(e,t,null,KV.builtIn(`RESPONSE_PAYLOAD_TOO_LARGE`));return}this.publishRpcResponsePacket(e,t,n,null)})}},rH=class extends iL{constructor(e,t,n,r,i,a){super(e,t,$.Kind.Audio,n,a),this.monitorReceiver=()=>J(this,void 0,void 0,function*(){if(!this.receiver){this._currentBitrate=0;return}let e=yield this.getReceiverStats();e&&this.prevStats&&this.receiver&&(this._currentBitrate=rL(e,this.prevStats)),this.prevStats=e}),this.audioContext=r,this.webAudioPluginNodes=[],i&&(this.sinkId=i.deviceId)}setVolume(e){var t;for(let n of this.attachedElements)this.audioContext?(t=this.gainNode)==null||t.gain.setTargetAtTime(e,0,.1):n.volume=e;VF()&&this._mediaStreamTrack._setVolume(e),this.elementVolume=e}getVolume(){if(this.elementVolume)return this.elementVolume;if(VF())return 1;let e=0;return this.attachedElements.forEach(t=>{t.volume>e&&(e=t.volume)}),e}setSinkId(e){return J(this,void 0,void 0,function*(){this.sinkId=e,yield Promise.all(this.attachedElements.map(t=>{if(kF(t))return t.setSinkId(e)}))})}attach(e){let t=this.attachedElements.length===0;return e?super.attach(e):e=super.attach(),this.sinkId&&kF(e)&&e.setSinkId(this.sinkId).catch(e=>{this.log.error(`Failed to set sink id on remote audio track`,e,this.logContext)}),this.audioContext&&t&&(this.log.debug(`using audio context mapping`,this.logContext),this.connectWebAudio(this.audioContext,e),e.volume=0,e.muted=!0),this.elementVolume&&this.setVolume(this.elementVolume),e}detach(e){let t;return e?(t=super.detach(e),this.audioContext&&(this.attachedElements.length>0?this.connectWebAudio(this.audioContext,this.attachedElements[0]):this.disconnectWebAudio())):(t=super.detach(),this.disconnectWebAudio()),t}setAudioContext(e){this.audioContext=e,e&&this.attachedElements.length>0?this.connectWebAudio(e,this.attachedElements[0]):e||this.disconnectWebAudio()}setWebAudioPlugins(e){this.webAudioPluginNodes=e,this.attachedElements.length>0&&this.audioContext&&this.connectWebAudio(this.audioContext,this.attachedElements[0])}connectWebAudio(e,t){this.disconnectWebAudio(),this.sourceNode=e.createMediaStreamSource(t.srcObject);let n=this.sourceNode;this.webAudioPluginNodes.forEach(e=>{n.connect(e),n=e}),this.gainNode=e.createGain(),n.connect(this.gainNode),this.gainNode.connect(e.destination),this.elementVolume&&this.gainNode.gain.setTargetAtTime(this.elementVolume,0,.1),e.state!==`running`&&e.resume().then(()=>{e.state!==`running`&&this.emit(Q.AudioPlaybackFailed,Error(`Audio Context couldn't be started automatically`))}).catch(e=>{this.emit(Q.AudioPlaybackFailed,e)})}disconnectWebAudio(){var e,t;(e=this.gainNode)==null||e.disconnect(),(t=this.sourceNode)==null||t.disconnect(),this.gainNode=void 0,this.sourceNode=void 0}getReceiverStats(){return J(this,void 0,void 0,function*(){if(!this.receiver||!this.receiver.getStats)return;let e=yield this.receiver.getStats(),t;return e.forEach(e=>{e.type===`inbound-rtp`&&(t={type:`audio`,streamId:e.id,timestamp:e.timestamp,jitter:e.jitter,bytesReceived:e.bytesReceived,concealedSamples:e.concealedSamples,concealmentEvents:e.concealmentEvents,silentConcealedSamples:e.silentConcealedSamples,silentConcealmentEvents:e.silentConcealmentEvents,totalAudioEnergy:e.totalAudioEnergy,totalSamplesDuration:e.totalSamplesDuration})}),t})}},iH=class extends KM.EventEmitter{constructor(e,t,n,r){super(),this.metadataMuted=!1,this.encryption=pA.NONE,this.log=DM,this.handleMuted=()=>{this.emit(Q.Muted)},this.handleUnmuted=()=>{this.emit(Q.Unmuted)},this.log=OM(r?.loggerName??EM.Publication),this.loggerContextCb=this.loggerContextCb,this.setMaxListeners(100),this.kind=e,this.trackSid=t,this.trackName=n,this.source=$.Source.Unknown}setTrack(e){this.track&&(this.track.off(Q.Muted,this.handleMuted),this.track.off(Q.Unmuted,this.handleUnmuted)),this.track=e,e&&(e.on(Q.Muted,this.handleMuted),e.on(Q.Unmuted,this.handleUnmuted))}get logContext(){return Object.assign(Object.assign({},this.loggerContextCb?.call(this)),rF(this))}get isMuted(){return this.metadataMuted}get isEnabled(){return!0}get isSubscribed(){return this.track!==void 0}get isEncrypted(){return this.encryption!==pA.NONE}get audioTrack(){if(hI(this.track))return this.track}get videoTrack(){if(gI(this.track))return this.track}updateInfo(e){this.trackSid=e.sid,this.trackName=e.name,this.source=$.sourceFromProto(e.source),this.mimeType=e.mimeType,this.kind===$.Kind.Video&&e.width>0&&(this.dimensions={width:e.width,height:e.height},this.simulcasted=e.simulcast),this.encryption=e.encryption,this.trackInfo=e,this.log.debug(`update publication info`,Object.assign(Object.assign({},this.logContext),{info:e}))}};(function(e){(function(e){e.Desired=`desired`,e.Subscribed=`subscribed`,e.Unsubscribed=`unsubscribed`})(e.SubscriptionStatus||={}),(function(e){e.Allowed=`allowed`,e.NotAllowed=`not_allowed`})(e.PermissionStatus||={})})(iH||={});var aH=class extends iH{get isUpstreamPaused(){return this.track?.isUpstreamPaused}constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.handleTrackEnded=()=>{this.emit(Q.Ended)},this.handleCpuConstrained=()=>{this.track&&gI(this.track)&&this.emit(Q.CpuConstrained,this.track)},this.updateInfo(t),this.setTrack(n)}setTrack(e){this.track&&(this.track.off(Q.Ended,this.handleTrackEnded),this.track.off(Q.CpuConstrained,this.handleCpuConstrained)),super.setTrack(e),e&&(e.on(Q.Ended,this.handleTrackEnded),e.on(Q.CpuConstrained,this.handleCpuConstrained))}get isMuted(){return this.track?this.track.isMuted:super.isMuted}get audioTrack(){return super.audioTrack}get videoTrack(){return super.videoTrack}get isLocal(){return!0}mute(){return J(this,void 0,void 0,function*(){return this.track?.mute()})}unmute(){return J(this,void 0,void 0,function*(){return this.track?.unmute()})}pauseUpstream(){return J(this,void 0,void 0,function*(){yield this.track?.pauseUpstream()})}resumeUpstream(){return J(this,void 0,void 0,function*(){yield this.track?.resumeUpstream()})}getTrackFeatures(){if(hI(this.track)){let e=this.track.getSourceTrackSettings(),t=new Set;return e.autoGainControl&&t.add(iA.TF_AUTO_GAIN_CONTROL),e.echoCancellation&&t.add(iA.TF_ECHO_CANCELLATION),e.noiseSuppression&&t.add(iA.TF_NOISE_SUPPRESSION),e.channelCount&&e.channelCount>1&&t.add(iA.TF_STEREO),this.options?.dtx||t.add(iA.TF_NO_DTX),this.track.enhancedNoiseCancellation&&t.add(iA.TF_ENHANCED_NOISE_CANCELLATION),Array.from(t.values())}return[]}};function oH(e,t){return J(this,void 0,void 0,function*(){e??={};let n=!1,r=oF(e),i=r.audioProcessor,a=r.videoProcessor,o=r.optionsWithoutProcessor,s=o.audio,c=o.video;if(i&&typeof o.audio==`object`&&(o.audio.processor=i),a&&typeof o.video==`object`&&(o.video.processor=a),e.audio&&typeof o.audio==`object`&&typeof o.audio.deviceId==`string`){let e=o.audio.deviceId;o.audio.deviceId={exact:e},n=!0,s=Object.assign(Object.assign({},o.audio),{deviceId:{ideal:e}})}if(o.video&&typeof o.video==`object`&&typeof o.video.deviceId==`string`){let e=o.video.deviceId;o.video.deviceId={exact:e},n=!0,c=Object.assign(Object.assign({},o.video),{deviceId:{ideal:e}})}o.audio===!0?o.audio={deviceId:`default`}:typeof o.audio==`object`&&o.audio!==null&&(o.audio=Object.assign(Object.assign({},o.audio),{deviceId:o.audio.deviceId||`default`})),o.video===!0?o.video={deviceId:`default`}:typeof o.video==`object`&&!o.video.deviceId&&(o.video.deviceId=`default`);let l=YP(qP(o,qR,JR)),u=navigator.mediaDevices.getUserMedia(l);o.audio&&(vL.userMediaPromiseMap.set(`audioinput`,u),u.catch(()=>vL.userMediaPromiseMap.delete(`audioinput`))),o.video&&(vL.userMediaPromiseMap.set(`videoinput`,u),u.catch(()=>vL.userMediaPromiseMap.delete(`videoinput`)));try{let e=yield u;return yield Promise.all(e.getTracks().map(n=>J(this,void 0,void 0,function*(){let r=n.kind===`audio`,o,s=r?l.audio:l.video;typeof s!=`boolean`&&(o=s);let c=n.getSettings().deviceId;o?.deviceId&&oI(o.deviceId)!==c?o.deviceId=c:o||={deviceId:c};let u=Sz(n,o,t);return u.kind===$.Kind.Video?u.source=$.Source.Camera:u.kind===$.Kind.Audio&&(u.source=$.Source.Microphone),u.mediaStream=e,hI(u)&&i?yield u.setProcessor(i):gI(u)&&a&&(yield u.setProcessor(a)),u})))}catch(r){if(!n)throw r;return oH(Object.assign(Object.assign({},e),{audio:s,video:c}),t)}})}var sH;(function(e){e.Excellent=`excellent`,e.Good=`good`,e.Poor=`poor`,e.Lost=`lost`,e.Unknown=`unknown`})(sH||={});function cH(e){switch(e){case $k.EXCELLENT:return sH.Excellent;case $k.GOOD:return sH.Good;case $k.POOR:return sH.Poor;case $k.LOST:return sH.Lost;default:return sH.Unknown}}var lH=class extends KM.EventEmitter{get logContext(){var e;return Object.assign({},((e=this.loggerOptions)?.loggerContextCb)?.call(e))}get isEncrypted(){return this.trackPublications.size>0&&Array.from(this.trackPublications.values()).every(e=>e.isEncrypted)}get isAgent(){return this.permissions?.agent||this.kind===dA.AGENT}get isActive(){return this.participantInfo?.state===uA.ACTIVE}get kind(){return this._kind}get attributes(){return Object.freeze(Object.assign({},this._attributes))}constructor(e,t,n,r,i,a){let o=arguments.length>6&&arguments[6]!==void 0?arguments[6]:dA.STANDARD;super(),this.audioLevel=0,this.isSpeaking=!1,this._connectionQuality=sH.Unknown,this.log=DM,this.loggerOptions=a,this.log=OM(a?.loggerName??EM.Participant,()=>this.logContext),this.setMaxListeners(100),this.sid=e,this.identity=t,this.name=n,this.metadata=r,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this._kind=o,this._attributes=i??{}}getTrackPublications(){return Array.from(this.trackPublications.values())}getTrackPublication(e){for(let t of this.trackPublications){let n=wO(t,2)[1];if(n.source===e)return n}}getTrackPublicationByName(e){for(let t of this.trackPublications){let n=wO(t,2)[1];if(n.trackName===e)return n}}waitUntilActive(){return this.isActive?Promise.resolve():this.activeFuture?this.activeFuture.promise:(this.activeFuture=new iI,this.once(X.Active,()=>{var e,t;(t=(e=this.activeFuture)?.resolve)==null||t.call(e),this.activeFuture=void 0}),this.activeFuture.promise)}get connectionQuality(){return this._connectionQuality}get isCameraEnabled(){return!(this.getTrackPublication($.Source.Camera)?.isMuted??!0)}get isMicrophoneEnabled(){return!(this.getTrackPublication($.Source.Microphone)?.isMuted??!0)}get isScreenShareEnabled(){return!!this.getTrackPublication($.Source.ScreenShare)}get isLocal(){return!1}get joinedAt(){return this.participantInfo?new Date(Number.parseInt(this.participantInfo.joinedAt.toString())*1e3):new Date}updateInfo(e){return this.participantInfo&&this.participantInfo.sid===e.sid&&this.participantInfo.version>e.version?!1:(this.identity=e.identity,this.sid=e.sid,this._setName(e.name),this._setMetadata(e.metadata),this._setAttributes(e.attributes),e.state===uA.ACTIVE&&this.participantInfo?.state!==uA.ACTIVE&&this.emit(X.Active),e.permission&&this.setPermissions(e.permission),this.participantInfo=e,!0)}_setMetadata(e){let t=this.metadata!==e,n=this.metadata;this.metadata=e,t&&this.emit(X.ParticipantMetadataChanged,n)}_setName(e){let t=this.name!==e;this.name=e,t&&this.emit(X.ParticipantNameChanged,e)}_setAttributes(e){let t=aF(this.attributes,e);this._attributes=e,Object.keys(t).length>0&&this.emit(X.AttributesChanged,t)}setPermissions(e){let t=this.permissions,n=e.canPublish!==this.permissions?.canPublish||e.canSubscribe!==this.permissions?.canSubscribe||e.canPublishData!==this.permissions?.canPublishData||e.hidden!==this.permissions?.hidden||e.recorder!==this.permissions?.recorder||e.canPublishSources.length!==this.permissions.canPublishSources.length||e.canPublishSources.some((e,t)=>e!==this.permissions?.canPublishSources[t])||e.canSubscribeMetrics!==this.permissions?.canSubscribeMetrics;return this.permissions=e,n&&this.emit(X.ParticipantPermissionsChanged,t),n}setIsSpeaking(e){e!==this.isSpeaking&&(this.isSpeaking=e,e&&(this.lastSpokeAt=new Date),this.emit(X.IsSpeakingChanged,e))}setConnectionQuality(e){let t=this._connectionQuality;this._connectionQuality=cH(e),t!==this._connectionQuality&&this.emit(X.ConnectionQualityChanged,this._connectionQuality)}setDisconnected(){var e,t;this.activeFuture&&=((t=(e=this.activeFuture).reject)==null||t.call(e,Error(`Participant disconnected`)),void 0)}setAudioContext(e){this.audioContext=e,this.audioTrackPublications.forEach(t=>hI(t.track)&&t.track.setAudioContext(e))}addTrackPublication(e){this.log.debug(`adding track publication`,{trackSid:e.trackSid,source:e.source,kind:e.kind}),e.on(Q.Muted,()=>{this.emit(X.TrackMuted,e)}),e.on(Q.Unmuted,()=>{this.emit(X.TrackUnmuted,e)});let t=e;switch(t.track&&(t.track.sid=e.trackSid),this.trackPublications.set(e.trackSid,e),e.kind){case $.Kind.Audio:this.audioTrackPublications.set(e.trackSid,e);break;case $.Kind.Video:this.videoTrackPublications.set(e.trackSid,e)}}};function uH(e){if(!e.participantSid&&!e.participantIdentity)throw Error(`Invalid track permission, must provide at least one of participantIdentity and participantSid`);return new Qj({participantIdentity:e.participantIdentity??``,participantSid:e.participantSid??``,allTracks:e.allowAll??!1,trackSids:e.allowedTrackSids||[]})}var dH=class extends lH{constructor(e,t,n,r,i,a,o,s){super(e,t,void 0,void 0,void 0,{loggerName:r.loggerName,loggerContextCb:()=>this.engine.logContext}),this.pendingPublishing=new Set,this.pendingPublishPromises=new Map,this.participantTrackPermissions=[],this.allParticipantsAllowedToSubscribe=!0,this.encryptionType=pA.NONE,this.e2eeStateMutex=new jD,this.enabledPublishVideoCodecs=[],this.handleReconnecting=()=>{this.reconnectFuture||=new iI},this.handleReconnected=()=>{var e,t;(t=(e=this.reconnectFuture)?.resolve)==null||t.call(e),this.reconnectFuture=void 0,this.updateTrackSubscriptionPermissions()},this.handleClosing=()=>{var e,t,n,r,i,a;this.reconnectFuture&&=(this.reconnectFuture.promise.catch(e=>this.log.warn(e.message)),(t=(e=this.reconnectFuture)?.reject)==null||t.call(e,Error(`Got disconnected during reconnection attempt`)),void 0),this.signalConnectedFuture&&=((r=(n=this.signalConnectedFuture).reject)==null||r.call(n,Error(`Got disconnected without signal connected`)),void 0),(a=(i=this.activeAgentFuture)?.reject)==null||a.call(i,Error(`Got disconnected without active agent present`)),this.activeAgentFuture=void 0,this.firstActiveAgent=void 0},this.handleSignalConnected=e=>{var t,n;e.participant&&this.updateInfo(e.participant),this.signalConnectedFuture||=new iI,(n=(t=this.signalConnectedFuture).resolve)==null||n.call(t)},this.handleSignalRequestResponse=e=>{let t=e.requestId,n=e.reason,r=e.message,i=this.pendingSignalRequests.get(t);switch(i&&(n!==fM.OK&&i.reject(new wP(r,n)),this.pendingSignalRequests.delete(t)),e.request.case){case`publishDataTrack`:{let t;switch(e.reason){case fM.NOT_ALLOWED:t=FV.notAllowed(e.message);break;case fM.DUPLICATE_NAME:t=FV.duplicateName(e.message);break;case fM.INVALID_NAME:t=FV.invalidName(e.message);break;case fM.LIMIT_EXCEEDED:t=FV.limitReached(e.message);break;default:t=FV.unknown(e.reason,e.message)}this.roomOutgoingDataTrackManager.receivedSfuPublishResponse(e.request.value.pubHandle,{type:`error`,error:t});break}}},this.updateTrackSubscriptionPermissions=()=>{this.log.debug(`updating track subscription permissions`,{allParticipantsAllowed:this.allParticipantsAllowedToSubscribe,participantTrackPermissions:this.participantTrackPermissions}),this.engine.client.sendUpdateSubscriptionPermissions(this.allParticipantsAllowedToSubscribe,this.participantTrackPermissions.map(e=>uH(e)))},this.onTrackUnmuted=e=>{this.onTrackMuted(e,e.isUpstreamPaused)},this.onTrackMuted=(e,t)=>{if(t===void 0&&(t=!0),!e.sid){this.log.error(`could not update mute status for unpublished track`,rF(e));return}this.engine.updateMuteStatus(e.sid,t)},this.onTrackUpstreamPaused=e=>{this.log.debug(`upstream paused`,rF(e)),this.onTrackMuted(e,!0)},this.onTrackUpstreamResumed=e=>{this.log.debug(`upstream resumed`,rF(e)),this.onTrackMuted(e,e.isMuted)},this.onTrackFeatureUpdate=e=>{let t=this.audioTrackPublications.get(e.sid);if(!t){this.log.warn(`Could not update local audio track settings, missing publication for track ${e.sid}`);return}this.engine.client.sendUpdateLocalAudioTrack(t.trackSid,t.getTrackFeatures())},this.onTrackCpuConstrained=(e,t)=>{this.log.debug(`track cpu constrained`,rF(t)),this.emit(X.LocalTrackCpuConstrained,e,t)},this.handleSubscribedQualityUpdate=e=>J(this,void 0,void 0,function*(){var t,n,r,i;if(!this.roomOptions?.dynacast)return;let a=this.videoTrackPublications.get(e.trackSid);if(!a){this.log.warn(`received subscribed quality update for unknown track`,{trackSid:e.trackSid});return}if(!a.videoTrack)return;let o=yield a.videoTrack.setPublishingCodecs(e.subscribedCodecs);try{for(var s=!0,c=HM(o),l;l=yield c.next(),t=l.done,!t;s=!0){i=l.value,s=!1;let e=i;VP(e)&&(this.log.debug(`publish ${e} for ${a.videoTrack.sid}`,rF(a)),yield this.publishAdditionalCodecForTrack(a.videoTrack,e,a.options))}}catch(e){n={error:e}}finally{try{!s&&!t&&(r=c.return)&&(yield r.call(c))}finally{if(n)throw n.error}}}),this.handleLocalTrackUnpublished=e=>{let t=this.trackPublications.get(e.trackSid);if(!t){this.log.warn(`received unpublished event for unknown track`,{trackSid:e.trackSid});return}this.unpublishTrack(t.track)},this.handleTrackEnded=e=>J(this,void 0,void 0,function*(){if(e.source===$.Source.ScreenShare||e.source===$.Source.ScreenShareAudio)this.log.debug(`unpublishing local track due to TrackEnded`,rF(e)),this.unpublishTrack(e);else if(e.isUserProvided)yield e.mute();else if(vI(e)||_I(e))try{if(BF())try{let t=yield navigator==null?void 0:navigator.permissions.query({name:e.source===$.Source.Camera?`camera`:`microphone`});if(t&&t.state===`denied`)throw this.log.warn(`user has revoked access to ${e.source}`,rF(e)),t.onchange=()=>{t.state!==`denied`&&(e.isMuted||e.restartTrack(),t.onchange=null)},Error(`GetUserMedia Permission denied`)}catch{}e.isMuted||(this.log.debug(`track ended, attempting to use a different device`,rF(e)),vI(e)?yield e.restartTrack({deviceId:`default`}):yield e.restartTrack())}catch{this.log.warn(`could not restart track, muting instead`,rF(e)),yield e.mute()}}),this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.trackPublications=new Map,this.engine=n,this.roomOptions=r,this.setupEngine(n),this.activeDeviceMap=new Map([[`audioinput`,`default`],[`videoinput`,`default`],[`audiooutput`,`default`]]),this.pendingSignalRequests=new Map,this.roomOutgoingDataStreamManager=i,this.roomOutgoingDataTrackManager=a,this.rpcClientManager=o,this.rpcServerManager=s}get lastCameraError(){return this.cameraError}get lastMicrophoneError(){return this.microphoneError}get isE2EEEnabled(){return this.encryptionType!==pA.NONE}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setupEngine(e){this.engine=e,this.engine.on(Z.RemoteMute,(e,t)=>{let n=this.trackPublications.get(e);n&&n.track&&(t?n.mute():n.unmute())}),this.signalConnectedFuture?.isResolved&&(this.signalConnectedFuture=void 0),this.engine.on(Z.Connected,this.handleReconnected).on(Z.SignalConnected,this.handleSignalConnected).on(Z.SignalRestarted,this.handleReconnected).on(Z.SignalResumed,this.handleReconnected).on(Z.Restarting,this.handleReconnecting).on(Z.Resuming,this.handleReconnecting).on(Z.LocalTrackUnpublished,this.handleLocalTrackUnpublished).on(Z.SubscribedQualityUpdate,this.handleSubscribedQualityUpdate).on(Z.Closing,this.handleClosing).on(Z.SignalRequestResponse,this.handleSignalRequestResponse)}setMetadata(e){return J(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({metadata:e})})}setName(e){return J(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({name:e})})}setAttributes(e){return J(this,void 0,void 0,function*(){yield this.requestMetadataUpdate({attributes:e})})}requestMetadataUpdate(e){return J(this,arguments,void 0,function(e){var t=this;let n=e.metadata,r=e.name,i=e.attributes;return function*(){return new aP((e,a)=>J(t,void 0,void 0,function*(){try{let t=!1,o=yield this.engine.client.sendUpdateLocalMetadata(n??this.metadata??``,r??this.name??``,i),s=performance.now();for(this.pendingSignalRequests.set(o,{resolve:e,reject:e=>{a(e),t=!0},values:{name:r,metadata:n,attributes:i}});performance.now()-s<5e3&&!t;){if((!r||this.name===r)&&(!n||this.metadata===n)&&(!i||Object.entries(i).every(e=>{let t=wO(e,2),n=t[0],r=t[1];return this.attributes[n]===r||r===``&&!this.attributes[n]}))){this.pendingSignalRequests.delete(o),e();return}yield vF(50)}a(new wP(`Request to update local metadata timed out`,`TimeoutError`))}catch(e){e instanceof Error?a(e):a(Error(String(e)))}}))}()})}setCameraEnabled(e,t,n){return this.setTrackEnabled($.Source.Camera,e,t,n)}setMicrophoneEnabled(e,t,n){return this.setTrackEnabled($.Source.Microphone,e,t,n)}setScreenShareEnabled(e,t,n){return this.setTrackEnabled($.Source.ScreenShare,e,t,n)}setE2EEEnabled(e){return J(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.encryptionType=e?pA.GCM:pA.NONE,yield Promise.all(this.pendingPublishPromises.values()),this.trackPublications.size===0||Array.from(this.trackPublications.values()).every(t=>t.isEncrypted===e))return;yield this.republishAllTracks(void 0,!1)}finally{t()}})}setTrackEnabled(e,t,n,r){return J(this,void 0,void 0,function*(){this.log.debug(`setTrackEnabled`,{source:e,enabled:t}),this.republishPromise&&(yield this.republishPromise);let i=this.getTrackPublication(e);if(t){if(i)yield i.unmute();else{let t;if(this.pendingPublishing.has(e)){let t=yield this.waitForPendingPublicationOfSource(e);return t||this.log.info(`waiting for pending publication promise timed out`,{source:e}),yield t?.unmute(),t}this.pendingPublishing.add(e);try{switch(e){case $.Source.Camera:t=yield this.createTracks({video:n??!0});break;case $.Source.Microphone:t=yield this.createTracks({audio:n??!0});break;case $.Source.ScreenShare:t=yield this.createScreenTracks(Object.assign({},n));break;default:throw new vP(e)}}catch(n){throw t?.forEach(e=>{e.stop()}),n instanceof Error&&this.emit(X.MediaDevicesError,n,$P(e)),this.pendingPublishing.delete(e),n}for(let r of t){let t=Object.assign(Object.assign({},this.roomOptions.publishDefaults),n);e===$.Source.Microphone&&hI(r)&&t.preConnectBuffer&&(this.log.info(`starting preconnect buffer for microphone`),r.startPreConnectBuffer())}try{let e=[];for(let n of t)this.log.info(`publishing track`,rF(n)),e.push(this.publishTrack(n,r));i=wO(yield Promise.all(e),1)[0]}catch(e){throw t?.forEach(e=>{e.stop()}),e}finally{this.pendingPublishing.delete(e)}}}else if(!i?.track&&this.pendingPublishing.has(e)&&(i=yield this.waitForPendingPublicationOfSource(e),i||this.log.info(`waiting for pending publication promise timed out`,{source:e})),i&&i.track){if(e===$.Source.ScreenShare){let e=[this.unpublishTrack(i.track)],t=this.getTrackPublication($.Source.ScreenShareAudio);t&&t.track&&e.push(this.unpublishTrack(t.track)),i=wO(yield Promise.all(e),1)[0]}else yield i.mute()}return i})}enableCameraAndMicrophone(){return J(this,void 0,void 0,function*(){if(!(this.pendingPublishing.has($.Source.Camera)||this.pendingPublishing.has($.Source.Microphone))){this.pendingPublishing.add($.Source.Camera),this.pendingPublishing.add($.Source.Microphone);try{let e=yield this.createTracks({audio:!0,video:!0});yield Promise.all(e.map(e=>this.publishTrack(e)))}finally{this.pendingPublishing.delete($.Source.Camera),this.pendingPublishing.delete($.Source.Microphone)}}})}createTracks(e){return J(this,void 0,void 0,function*(){e??={};let t=qP(e,this.roomOptions?.audioCaptureDefaults,this.roomOptions?.videoCaptureDefaults);try{return(yield oH(t,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext})).map(e=>(hI(e)&&(this.microphoneError=void 0,e.setAudioContext(this.audioContext),e.source=$.Source.Microphone,this.emit(X.AudioStreamAcquired)),gI(e)&&(this.cameraError=void 0,e.source=$.Source.Camera),e))}catch(t){throw t instanceof Error&&(e.audio&&(this.microphoneError=t),e.video&&(this.cameraError=t)),t}})}createScreenTracks(e){return J(this,void 0,void 0,function*(){if(e===void 0&&(e={}),navigator.mediaDevices.getDisplayMedia===void 0)throw new _P(`getDisplayMedia not supported`);e.resolution===void 0&&!IF()&&(e.resolution=KP.h1080fps30.resolution);let t=eF(e),n=yield navigator.mediaDevices.getDisplayMedia(t),r=n.getVideoTracks();if(r.length===0)throw new vP(`no video track found`);let i=new Vz(r[0],void 0,!1,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});i.source=$.Source.ScreenShare,e.contentHint&&(i.mediaStreamTrack.contentHint=e.contentHint);let a=[i];if(n.getAudioTracks().length>0){this.emit(X.AudioStreamAcquired);let e=new xz(n.getAudioTracks()[0],void 0,!1,this.audioContext,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});e.source=$.Source.ScreenShareAudio,a.push(e)}return a})}publishTrack(e,t){return J(this,void 0,void 0,function*(){return this.publishOrRepublishTrack(e,t)})}waitForNextEngineRestart(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:15e3;return new Promise((t,n)=>{let r=()=>{clearTimeout(o),this.engine.off(Z.Restarted,i),this.engine.off(Z.Closing,a)},i=()=>{r(),t()},a=()=>{r(),n(Error(`engine closed before restart completed`))},o=setTimeout(()=>{r(),n(Error(`timed out waiting for engine restart`))},e);this.engine.once(Z.Restarted,i),this.engine.once(Z.Closing,a)})}publishOrRepublishTrack(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0&&arguments[2],i=arguments.length>3&&arguments[3]!==void 0&&arguments[3];return function*(){vI(e)&&e.setAudioContext(n.audioContext),yield n.reconnectFuture?.promise,n.republishPromise&&!r&&(yield n.republishPromise),mI(e)&&n.pendingPublishPromises.has(e)&&(yield n.pendingPublishPromises.get(e));let a;if(e instanceof MediaStreamTrack)a=e.getConstraints();else{a=e.constraints;let t;switch(e.source){case $.Source.Microphone:t=`audioinput`;break;case $.Source.Camera:t=`videoinput`}t&&n.activeDeviceMap.has(t)&&(a=Object.assign(Object.assign({},a),{deviceId:n.activeDeviceMap.get(t)}))}if(e instanceof MediaStreamTrack)switch(e.kind){case`audio`:e=new xz(e,a,!0,n.audioContext,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;case`video`:e=new Vz(e,a,!0,{loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});break;default:throw new vP(`unsupported MediaStreamTrack kind ${e.kind}`)}else e.updateLoggerOptions({loggerName:n.roomOptions.loggerName,loggerContextCb:()=>n.logContext});let o;if(n.trackPublications.forEach(t=>{t.track&&t.track===e&&(o=t)}),o)return n.log.warn(`track has already been published, skipping`,rF(o)),o;let s=Object.assign(Object.assign({},n.roomOptions.publishDefaults),t),c=`channelCount`in e.mediaStreamTrack.getSettings()&&e.mediaStreamTrack.getSettings().channelCount===2||e.mediaStreamTrack.getConstraints().channelCount===2,l=s.forceStereo??c;l&&(s.dtx===void 0&&n.log.debug(`Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.`,rF(e)),s.red===void 0&&n.log.debug(`Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work.`),s.dtx??=!1,s.red??=!1),!zF()&&n.roomOptions.e2ee&&(n.log.info(`End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2`),s.simulcast=!1),s.source&&(e.source=s.source);let u=new Promise((t,r)=>J(n,void 0,void 0,function*(){try{if(this.engine.client.currentState!==iR.CONNECTED){this.log.debug(`deferring track publication until signal is connected`,{track:rF(e)});let n=!1,i=setTimeout(()=>{n=!0,e.stop(),r(new CP(`publishing rejected as engine not connected within timeout`,408))},15e3);if(yield this.waitUntilEngineConnected(),clearTimeout(i),n)return;t(yield this.publish(e,s,l))}else try{t(yield this.publish(e,s,l))}catch(e){r(e)}}catch(e){r(e)}}));n.pendingPublishPromises.set(e,u);try{return yield u}catch(a){if(!i&&a instanceof xP)return n.log.warn(`negotiation due to track publish failed, retrying after reconnect`,{error:a}),n.pendingPublishPromises.delete(e),yield n.waitForNextEngineRestart(),yield n.publishOrRepublishTrack(e,t,r,!0);throw a}finally{n.pendingPublishPromises.delete(e)}}()})}waitUntilEngineConnected(){return this.signalConnectedFuture||=new iI,this.signalConnectedFuture.promise}hasPermissionsToPublish(e){if(!this.permissions)return this.log.warn(`no permissions present for publishing track`,rF(e)),!1;let t=this.permissions,n=t.canPublish,r=t.canPublishSources;return n&&(r.length===0||r.map(e=>sF(e)).includes(e.source))?!0:(this.log.warn(`insufficient permissions to publish`,rF(e)),!1)}publish(e,t,n){return J(this,void 0,void 0,function*(){if(!this.hasPermissionsToPublish(e))throw new CP(`failed to publish track, insufficient permissions`,403);Array.from(this.trackPublications.values()).find(t=>mI(e)&&t.source===e.source)&&e.source!==$.Source.Unknown&&this.log.info(`publishing a second track with the same source: ${e.source}`,rF(e)),t.stopMicTrackOnMute&&hI(e)&&(e.stopOnMute=!0),e.source===$.Source.ScreenShare&&jF()&&(t.simulcast=!1),t.videoCodec===`av1`&&!xF()&&(t.videoCodec=void 0),t.videoCodec===`vp9`&&!SF()&&(t.videoCodec=void 0),t.videoCodec===void 0&&(t.videoCodec=GR),this.enabledPublishVideoCodecs.length>0&&(this.enabledPublishVideoCodecs.some(e=>t.videoCodec===tF(e.mime))||(t.videoCodec=tF(this.enabledPublishVideoCodecs[0].mime)));let r=t.videoCodec;e.on(Q.Muted,this.onTrackMuted),e.on(Q.Unmuted,this.onTrackUnmuted),e.on(Q.Ended,this.handleTrackEnded),e.on(Q.UpstreamPaused,this.onTrackUpstreamPaused),e.on(Q.UpstreamResumed,this.onTrackUpstreamResumed),e.on(Q.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate);let i=[],a=!(t.dtx??!0),o=e.getSourceTrackSettings();o.autoGainControl&&i.push(iA.TF_AUTO_GAIN_CONTROL),o.echoCancellation&&i.push(iA.TF_ECHO_CANCELLATION),o.noiseSuppression&&i.push(iA.TF_NOISE_SUPPRESSION),o.channelCount&&o.channelCount>1&&i.push(iA.TF_STEREO),a&&i.push(iA.TF_NO_DTX),vI(e)&&e.hasPreConnectBuffer&&i.push(iA.TF_PRECONNECT_BUFFER);let s=this.normalizeRequestedFrameMetadataOptions(e,t),c=new fj({cid:e.mediaStreamTrack.id,name:t.name,type:$.kindToProto(e.kind),muted:e.isMuted,source:$.sourceToProto(e.source),disableDtx:a,encryption:this.encryptionType,stereo:n,disableRed:this.isE2EEEnabled||!(t.red??!0),stream:t?.stream,backupCodecPolicy:t?.backupCodecPolicy,audioFeatures:i,packetTrailerFeatures:s}),l;if(e.kind===$.Kind.Video){let n;try{n=yield e.waitForDimensions()}catch{let t=this.roomOptions.videoCaptureDefaults?.resolution??WP.h720.resolution;n={width:t.width,height:t.height},this.log.error(`could not determine track dimensions, using defaults`,Object.assign(Object.assign({},rF(e)),{dims:n}))}if(c.width=n.width,c.height=n.height,_I(e)){TF(r,t)&&(EF()||!OF(this.engine?.serverVersion))&&(t.simulcast=!1,this.log.info(`SVC simulcast is not supported, disabling simulcast.`,rF(e)));let n=TF(r,t);CF(r)&&!n&&(e.source===$.Source.ScreenShare&&(t.scalabilityMode=`L1T3`,`contentHint`in e.mediaStreamTrack&&(e.mediaStreamTrack.contentHint=`motion`,this.log.debug(`forcing contentHint to motion for screenshare with SVC codecs`,rF(e)))),t.scalabilityMode=t.scalabilityMode??`L3T3_KEY`);let i=new dj({codec:r,cid:e.mediaStreamTrack.id});n&&(i.videoLayerMode=EA.ONE_SPATIAL_LAYER_PER_STREAM),c.simulcastCodecs=[i],t.backupCodec===!0&&(t.backupCodec={codec:GR}),t.backupCodec&&r!==t.backupCodec.codec&&c.encryption===pA.NONE&&(this.roomOptions.dynacast||(this.roomOptions.dynacast=!0),c.simulcastCodecs.push(new dj({codec:t.backupCodec.codec,cid:``})))}l=Az(e.source===$.Source.ScreenShare,c.width,c.height,t),c.layers=Wz(c.width,c.height,l,CF(t.videoCodec)&&!TF(t.videoCodec,t))}else e.kind===$.Kind.Audio&&(l=[{maxBitrate:t.audioPreset?.maxBitrate,priority:t.audioPreset?.priority??`high`,networkPriority:t.audioPreset?.priority??`high`}]);if(!this.engine||this.engine.isClosed)throw new bP(`cannot publish track when not connected`);let u=()=>J(this,void 0,void 0,function*(){if(!this.engine.pcManager)throw new bP(`pcManager is not ready`);if(e.sender=yield this.engine.createSender(e,t,l),_I(e)&&(e.publishOptions=t),this.emit(X.LocalSenderCreated,e.sender,e),_I(e)&&(t.degradationPreference??=zz(e),e.setDegradationPreference(t.degradationPreference)),l){if(jF()&&e.kind===$.Kind.Audio){let t;for(let n of this.engine.pcManager.publisher.getTransceivers())if(n.sender===e.sender){t=n;break}t&&this.engine.pcManager.publisher.setTrackCodecBitrate({transceiver:t,codec:`opus`,maxbr:l[0]?.maxBitrate?l[0].maxBitrate/1e3:0})}else if(e.codec&&aI(e.codec)){let n=jz(e.codec,t,l);n>0&&this.engine.pcManager.publisher.setTrackCodecBitrate({cid:c.cid,codec:e.codec,maxbr:n/1e3,isScreenShare:e.source===$.Source.ScreenShare})}}yield this.engine.negotiate()}),d,f=new Promise((t,n)=>J(this,void 0,void 0,function*(){try{d=yield this.engine.addTrack(c),t(d)}catch(t){if(e.sender&&this.engine.pcManager?.publisher){try{this.engine.pcManager.publisher.removeTrack(e.sender)}catch(e){this.log.error(e)}yield this.engine.negotiate().catch(t=>{this.log.error(`failed to negotiate after removing track due to failed add track request`,Object.assign(Object.assign({},rF(e)),{error:t}))})}n(t)}}));if(this.enabledPublishVideoCodecs.length>0&&s.length===0)d=(yield Promise.all([f,u()]))[0];else{d=yield f;let n;if(d.codecs.forEach(e=>{n===void 0&&(n=e.mimeType)}),n&&e.kind===$.Kind.Video){let i=tF(n);i!==r&&(this.log.debug(`falling back to server selected codec`,Object.assign(Object.assign({},rF(e)),{codec:i})),t.videoCodec=i,l=Az(e.source===$.Source.ScreenShare,c.width,c.height,t))}yield u()}let p=new aH(e.kind,d,e,{loggerName:this.roomOptions.loggerName,loggerContextCb:()=>this.logContext});if(p.on(Q.CpuConstrained,e=>this.onTrackCpuConstrained(e,p)),p.options=t,e.sid=d.sid,_I(e)&&(e.publishOptions=t,c.width&&c.height&&(e.lastEncodedDimensions={width:c.width,height:c.height})),this.log.debug(`publishing ${e.kind} with encodings`,{encodings:l,trackInfo:d}),_I(e)?e.startMonitor(this.engine.client):vI(e)&&e.startMonitor(),this.addTrackPublication(p),this.emit(X.LocalTrackPublished,p),vI(e)&&d.audioFeatures.includes(iA.TF_PRECONNECT_BUFFER)){let t=e.getPreConnectBuffer(),n=e.getPreConnectBufferMimeType();this.on(X.LocalTrackSubscribed,t=>{if(t.trackSid===d.sid){if(!e.hasPreConnectBuffer){this.log.warn(`subscribe event came to late, buffer already closed`);return}this.log.debug(`finished recording preconnect buffer`,rF(e)),e.stopPreConnectBuffer()}}),t&&new Promise((r,i)=>J(this,void 0,void 0,function*(){var a,s,c,l;try{this.log.debug(`waiting for agent`,rF(e));let m=setTimeout(()=>{i(Error(`agent not active within 10 seconds`))},1e4),h=yield this.waitUntilActiveAgentPresent();clearTimeout(m),this.log.debug(`sending preconnect buffer`,rF(e));let g=yield this.streamBytes({name:`preconnect-buffer`,mimeType:n,topic:`lk.agent.pre-connect-audio-buffer`,destinationIdentities:[h.identity],attributes:{trackId:p.trackSid,sampleRate:String(o.sampleRate??`48000`),channels:String(o.channelCount??`1`)}});try{for(var u=!0,d=HM(t),f;f=yield d.next(),a=f.done,!a;u=!0){l=f.value,u=!1;let e=l;yield g.write(e)}}catch(e){s={error:e}}finally{try{!u&&!a&&(c=d.return)&&(yield c.call(d))}finally{if(s)throw s.error}}yield g.close(),r()}catch(e){i(e)}})).then(()=>{this.log.debug(`preconnect buffer sent successfully`,rF(e))}).catch(t=>{this.log.error(`error sending preconnect buffer`,Object.assign(Object.assign({},rF(e)),{error:t}))})}return p})}canPublishFrameMetadata(){return!!(this.roomOptions.e2ee||this.roomOptions.encryption||ZI(this.roomOptions.frameMetadata??this.roomOptions.packetTrailer))}normalizeRequestedFrameMetadataOptions(e,t){let n=t.frameMetadata??t.packetTrailer;if(e.kind!==$.Kind.Video||!QI(n))return t.frameMetadata=void 0,t.packetTrailer=void 0,[];if(!this.canPublishFrameMetadata())return this.log.warn(`frame metadata transform not supported; not advertising features`,Object.assign(Object.assign({},this.logContext),rF(e))),t.frameMetadata=void 0,t.packetTrailer=void 0,[];let r=$I(n),i=eL(r);return t.frameMetadata=i,t.packetTrailer=i,r}get isLocal(){return!0}publishAdditionalCodecForTrack(e,t,n){return J(this,void 0,void 0,function*(){if(this.encryptionType!==pA.NONE)return;let r;if(this.trackPublications.forEach(t=>{t.track&&t.track===e&&(r=t)}),!r)throw new vP(`track is not published`);if(!_I(e))throw new vP(`track is not a video track`);let i=Object.assign(Object.assign({},this.roomOptions?.publishDefaults),n),a=Mz(e,t,i);if(!a){this.log.info(`backup codec has been disabled, ignoring request to add additional codec for track`,rF(e));return}let o=e.addSimulcastTrack(t,a);if(!o)return;let s=this.normalizeRequestedFrameMetadataOptions(e,i),c=new fj({cid:o.mediaStreamTrack.id,type:$.kindToProto(e.kind),muted:e.isMuted,source:$.sourceToProto(e.source),sid:e.sid,packetTrailerFeatures:s,simulcastCodecs:[{codec:i.videoCodec,cid:o.mediaStreamTrack.id}]});if(c.layers=Wz(c.width,c.height,a),!this.engine||this.engine.isClosed)throw new bP(`cannot publish track when not connected`);let l=(yield Promise.all([this.engine.addTrack(c),J(this,void 0,void 0,function*(){yield this.engine.createSimulcastSender(e,o,i,a),yield this.engine.negotiate()})]))[0];this.log.debug(`published ${t} for track ${e.sid}`,{encodings:a,trackInfo:l})})}unpublishTrack(e,t){return J(this,void 0,void 0,function*(){if(mI(e)){let t=this.pendingPublishPromises.get(e);t&&(this.log.debug(`awaiting publish promise before attempting to unpublish`,rF(e)),yield t)}let n=this.getPublicationForTrack(e),r=n?rF(n):void 0;if(this.log.info(`unpublishing track`,r),!n||!n.track){this.log.warn(`track was not unpublished because no publication was found`,r);return}e=n.track,e.off(Q.Muted,this.onTrackMuted),e.off(Q.Unmuted,this.onTrackUnmuted),e.off(Q.Ended,this.handleTrackEnded),e.off(Q.UpstreamPaused,this.onTrackUpstreamPaused),e.off(Q.UpstreamResumed,this.onTrackUpstreamResumed),e.off(Q.AudioTrackFeatureUpdate,this.onTrackFeatureUpdate),t===void 0&&(t=this.roomOptions?.stopLocalTrackOnUnpublish??!0),t?e.stop():e.stopMonitor();let i=!1,a=e.sender;if(e.sender=void 0,this.engine.pcManager&&this.engine.pcManager.currentState<ZR.FAILED&&a)try{for(let e of this.engine.pcManager.publisher.getTransceivers())e.sender===a&&(e.direction=`inactive`,i=!0);try{i=this.engine.removeTrack(a)}catch(e){this.log.warn(e),i=!0}if(_I(e)){for(let t of e.simulcastCodecs){let e=wO(t,2)[1];if(e.sender){try{i=this.engine.removeTrack(e.sender)}catch(e){this.log.warn(e),i=!0}e.sender=void 0}}e.simulcastCodecs.clear()}}catch(e){this.log.warn(`failed to unpublish track`,Object.assign(Object.assign({},r),{error:e}))}switch(this.trackPublications.delete(n.trackSid),n.kind){case $.Kind.Audio:this.audioTrackPublications.delete(n.trackSid);break;case $.Kind.Video:this.videoTrackPublications.delete(n.trackSid)}return this.emit(X.LocalTrackUnpublished,n),n.setTrack(void 0),i&&(yield this.engine.negotiate()),n})}unpublishTracks(e){return J(this,void 0,void 0,function*(){return(yield Promise.all(e.map(e=>this.unpublishTrack(e)))).filter(e=>!!e)})}republishAllTracks(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return function*(){t.republishPromise&&(yield t.republishPromise),t.republishPromise=new aP((r,i)=>J(t,void 0,void 0,function*(){try{let t=[];this.trackPublications.forEach(n=>{n.track&&(e&&(n.options=Object.assign(Object.assign({},n.options),e)),t.push(n))}),yield Promise.all(t.map(e=>J(this,void 0,void 0,function*(){let t=e.track;yield this.unpublishTrack(t,!1),n&&!t.isMuted&&t.source!==$.Source.ScreenShare&&t.source!==$.Source.ScreenShareAudio&&(vI(t)||_I(t))&&!t.isUserProvided&&(this.log.debug(`restarting existing track`,{track:e.trackSid}),yield t.restartTrack()),yield this.publishOrRepublishTrack(t,e.options,!0)}))),r()}catch(e){e instanceof Error?i(e):i(Error(String(e)))}finally{this.republishPromise=void 0}})),yield t.republishPromise}()})}publishData(e){return J(this,arguments,void 0,function(e){var t=this;let n=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{};return function*(){let r=n.reliable?rz.RELIABLE:rz.LOSSY,i=n.reliable?OA.RELIABLE:OA.LOSSY,a=n.destinationIdentities,o=n.topic,s=new DA({kind:i,value:{case:`user`,value:new NA({participantIdentity:t.identity,payload:e,destinationIdentities:a,topic:o})}});yield t.engine.sendDataPacket(s,r)}()})}publishDtmf(e,t){return J(this,void 0,void 0,function*(){let n=new DA({kind:OA.RELIABLE,value:{case:`sipDtmf`,value:new PA({code:e,digit:t})}});yield this.engine.sendDataPacket(n,rz.RELIABLE)})}sendChatMessage(e,t){return J(this,void 0,void 0,function*(){let n={id:crypto.randomUUID(),message:e,timestamp:Date.now(),attachedFiles:t?.attachments},r=new DA({value:{case:`chatMessage`,value:new LA(Object.assign(Object.assign({},n),{timestamp:cO.parse(n.timestamp)}))}});return yield this.engine.sendDataPacket(r,rz.RELIABLE),this.emit(X.ChatMessage,n),n})}editChatMessage(e,t){return J(this,void 0,void 0,function*(){let n=Object.assign(Object.assign({},t),{message:e,editTimestamp:Date.now()}),r=new DA({value:{case:`chatMessage`,value:new LA(Object.assign(Object.assign({},n),{timestamp:cO.parse(n.timestamp),editTimestamp:cO.parse(n.editTimestamp)}))}});return yield this.engine.sendDataPacket(r,rz.RELIABLE),this.emit(X.ChatMessage,n),n})}sendText(e,t){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendText(e,t)})}streamText(e){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamText(e)})}sendFile(e,t){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendFile(e,t)})}sendBytes(e,t){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.sendBytes(e,t)})}streamBytes(e){return J(this,void 0,void 0,function*(){return this.roomOutgoingDataStreamManager.streamBytes(e)})}performRpc(e){return this.rpcClientManager.performRpc(e).then(e=>{let t=wO(e,2);return t[0],t[1]})}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setTrackSubscriptionPermissions(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[];this.participantTrackPermissions=t,this.allParticipantsAllowedToSubscribe=e,this.engine.client.isDisconnected||this.updateTrackSubscriptionPermissions()}setEnabledPublishCodecs(e){this.enabledPublishVideoCodecs=e.filter(e=>e.mime.split(`/`)[0].toLowerCase()===`video`)}updateInfo(e){return super.updateInfo(e)?(e.tracks.forEach(e=>{let t=this.trackPublications.get(e.sid);if(t){let n=t.isMuted||(t.track?.isUpstreamPaused??!1);n!==e.muted&&(this.log.debug(`updating server mute state after reconcile`,Object.assign(Object.assign({},rF(t)),{mutedOnServer:n})),this.engine.client.sendMuteTrack(e.sid,n))}}),!0):!1}setActiveAgent(e){var t,n,r,i;this.firstActiveAgent=e,e&&!this.firstActiveAgent&&(this.firstActiveAgent=e),e?(n=(t=this.activeAgentFuture)?.resolve)==null||n.call(t,e):(i=(r=this.activeAgentFuture)?.reject)==null||i.call(r,Error(`Agent disconnected`)),this.activeAgentFuture=void 0}waitUntilActiveAgentPresent(){return this.firstActiveAgent?Promise.resolve(this.firstActiveAgent):(this.activeAgentFuture||=new iI,this.activeAgentFuture.promise)}getPublicationForTrack(e){let t;return this.trackPublications.forEach(n=>{let r=n.track;r&&(e instanceof MediaStreamTrack?(vI(r)||_I(r))&&r.mediaStreamTrack===e&&(t=n):e===r&&(t=n))}),t}waitForPendingPublicationOfSource(e){return J(this,void 0,void 0,function*(){let t=Date.now();for(;Date.now()<t+1e4;){let t=Array.from(this.pendingPublishPromises.entries()).find(t=>wO(t,1)[0].source===e);if(t)return t[1];yield vF(20)}})}publishDataTrack(e){return J(this,void 0,void 0,function*(){let t=new BV(e,this.roomOutgoingDataTrackManager);return yield t.publish(),t})}},fH=class extends DOMException{constructor(e,t){super(e,`AbortError`),this.reason=t}},pH=class extends Map{constructor(){super(...arguments),this.pending=new Map}set(e,t){var n;super.set(e,t);let r=this.pending?.get(e);if(r){for(let e of r)e.isResolved||(n=e.resolve)==null||n.call(e,t);this.pending.delete(e)}return this}get[Symbol.toStringTag](){return`DeferrableMap`}getDeferred(e,t){return J(this,void 0,void 0,function*(){let n=this.get(e);if(n!==void 0)return n;if(t?.aborted)throw new fH(`The operation was aborted.`,t.reason);let r=new iI(void 0,()=>{let t=this.pending.get(e);if(!t)return;let n=t.indexOf(r);n!==-1&&t.splice(n,1),t.length===0&&this.pending.delete(e)}),i=this.pending.get(e);if(i?i.push(r):this.pending.set(e,[r]),t){let e=()=>{var e;r.isResolved||(e=r.reject)==null||e.call(r,new fH(`The operation was aborted.`,t.reason))};t.addEventListener(`abort`,e,{once:!0}),r.promise.finally(()=>{t.removeEventListener(`abort`,e)})}return r.promise})}},mH=class extends iH{constructor(e,t,n,r){super(e,t.sid,t.name,r),this.track=void 0,this.allowed=!0,this.requestedDisabled=void 0,this.visible=!0,this.handleEnded=e=>{this.setTrack(void 0),this.emit(Q.Ended,e)},this.handleVisibilityChange=e=>{this.log.debug(`adaptivestream video visibility ${this.trackSid}, visible=${e}`,this.logContext),this.visible=e,this.emitTrackUpdate()},this.handleVideoDimensionsChange=e=>{this.log.debug(`adaptivestream video dimensions ${e.width}x${e.height}`,this.logContext),this.videoDimensionsAdaptiveStream=e,this.emitTrackUpdate()},this.subscribed=n,this.updateInfo(t)}setSubscribed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.subscribed=e,e&&(this.allowed=!0);let r=new Dj({trackSids:[this.trackSid],subscribe:this.subscribed,participantTracks:[new HA({participantSid:``,trackSids:[this.trackSid]})]});this.emit(Q.UpdateSubscription,r),this.emitSubscriptionUpdateIfChanged(t),this.emitPermissionUpdateIfChanged(n)}get subscriptionStatus(){return this.subscribed===!1?iH.SubscriptionStatus.Unsubscribed:super.isSubscribed?iH.SubscriptionStatus.Subscribed:iH.SubscriptionStatus.Desired}get permissionStatus(){return this.allowed?iH.PermissionStatus.Allowed:iH.PermissionStatus.NotAllowed}get isSubscribed(){return this.subscribed!==!1&&super.isSubscribed}get isDesired(){return this.subscribed!==!1}get isEnabled(){return this.requestedDisabled===void 0?!this.isAdaptiveStream||this.visible:!this.requestedDisabled}get isLocal(){return!1}setEnabled(e){this.isManualOperationAllowed()&&this.requestedDisabled!==!e&&(this.requestedDisabled=!e,this.emitTrackUpdate())}setVideoQuality(e){this.isManualOperationAllowed()&&this.requestedMaxQuality!==e&&(this.requestedMaxQuality=e,this.requestedVideoDimensions=void 0,this.emitTrackUpdate())}setVideoDimensions(e){this.isManualOperationAllowed()&&(this.requestedVideoDimensions?.width!==e.width||this.requestedVideoDimensions?.height!==e.height)&&(xI(this.track)&&(this.requestedVideoDimensions=e),this.requestedMaxQuality=void 0,this.emitTrackUpdate())}setVideoFPS(e){this.isManualOperationAllowed()&&xI(this.track)&&this.fps!==e&&(this.fps=e,this.emitTrackUpdate())}get videoQuality(){return this.requestedMaxQuality??fF.HIGH}setTrack(e){let t=this.subscriptionStatus,n=this.permissionStatus,r=this.track;r!==e&&(r&&(r.off(Q.VideoDimensionsChanged,this.handleVideoDimensionsChange),r.off(Q.VisibilityChanged,this.handleVisibilityChange),r.off(Q.Ended,this.handleEnded),r.detach(),r.stopMonitor(),this.emit(Q.Unsubscribed,r)),super.setTrack(e),e&&(e.sid=this.trackSid,e.on(Q.VideoDimensionsChanged,this.handleVideoDimensionsChange),e.on(Q.VisibilityChanged,this.handleVisibilityChange),e.on(Q.Ended,this.handleEnded),this.emit(Q.Subscribed,e)),this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t))}setAllowed(e){let t=this.subscriptionStatus,n=this.permissionStatus;this.allowed=e,this.emitPermissionUpdateIfChanged(n),this.emitSubscriptionUpdateIfChanged(t)}setSubscriptionError(e){this.emit(Q.SubscriptionFailed,e)}updateInfo(e){super.updateInfo(e);let t=this.metadataMuted;this.metadataMuted=e.muted,this.track?this.track.setMuted(e.muted):t!==e.muted&&this.emit(e.muted?Q.Muted:Q.Unmuted)}emitSubscriptionUpdateIfChanged(e){let t=this.subscriptionStatus;e!==t&&this.emit(Q.SubscriptionStatusChanged,t,e)}emitPermissionUpdateIfChanged(e){this.permissionStatus!==e&&this.emit(Q.SubscriptionPermissionChanged,this.permissionStatus,e)}isManualOperationAllowed(){return this.isDesired?!0:(this.log.warn(`cannot update track settings when not subscribed`,this.logContext),!1)}get isAdaptiveStream(){return xI(this.track)&&this.track.isAdaptiveStream}emitTrackUpdate(){let e=new Pj({trackSids:[this.trackSid],disabled:!this.isEnabled,fps:this.fps});if(this.kind===$.Kind.Video){let t=this.requestedVideoDimensions;if(this.videoDimensionsAdaptiveStream!==void 0){if(t)cF(this.videoDimensionsAdaptiveStream,t)&&(this.log.debug(`using adaptive stream dimensions instead of requested`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream);else if(this.requestedMaxQuality!==void 0&&this.trackInfo){let e=lF(this.trackInfo,this.requestedMaxQuality);e&&cF(this.videoDimensionsAdaptiveStream,e)&&(this.log.debug(`using adaptive stream dimensions instead of max quality layer`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream)}else this.log.debug(`using adaptive stream dimensions`,Object.assign(Object.assign({},this.logContext),this.videoDimensionsAdaptiveStream)),t=this.videoDimensionsAdaptiveStream}t?(e.width=Math.ceil(t.width),e.height=Math.ceil(t.height)):this.requestedMaxQuality===void 0?(this.log.debug(`using default quality`,Object.assign(Object.assign({},this.logContext),{quality:fF.HIGH})),e.quality=fF.HIGH):(this.log.debug(`using requested max quality`,Object.assign(Object.assign({},this.logContext),{quality:this.requestedMaxQuality})),e.quality=this.requestedMaxQuality)}this.emit(Q.UpdateSettings,e)}},hH=class e extends lH{static fromParticipantInfo(t,n,r,i){return new e(t,n.sid,n.identity,n.name,n.metadata,n.attributes,r,n.kind,n.dataTracks.map(e=>new hV(kL.from(e),i,{publisherIdentity:n.identity})),n.clientProtocol,n.capabilities)}get logContext(){return Object.assign(Object.assign({},super.logContext),{remoteParticipantID:this.sid,remoteParticipant:this.identity})}constructor(e,t,n,r,i,a,o){let s=arguments.length>7&&arguments[7]!==void 0?arguments[7]:dA.STANDARD,c=arguments.length>8&&arguments[8]!==void 0?arguments[8]:[],l=arguments.length>9&&arguments[9]!==void 0?arguments[9]:0,u=arguments.length>10&&arguments[10]!==void 0?arguments[10]:[];super(t,n||``,r,i,a,o,s),this.signalClient=e,this.trackPublications=new Map,this.audioTrackPublications=new Map,this.videoTrackPublications=new Map,this.dataTracks=new pH(c.map(e=>[e.info.name,e])),this.volumeMap=new Map,this.clientProtocol=l,this.capabilities=u}addTrackPublication(e){super.addTrackPublication(e),e.on(Q.UpdateSettings,t=>{this.log.debug(`send update settings`,Object.assign(Object.assign(Object.assign({},this.logContext),rF(e)),{settings:t})),this.signalClient.sendUpdateTrackSettings(t)}),e.on(Q.UpdateSubscription,e=>{e.participantTracks.forEach(e=>{e.participantSid=this.sid}),this.signalClient.sendUpdateSubscription(e)}),e.on(Q.SubscriptionPermissionChanged,t=>{this.emit(X.TrackSubscriptionPermissionChanged,e,t)}),e.on(Q.SubscriptionStatusChanged,t=>{this.emit(X.TrackSubscriptionStatusChanged,e,t)}),e.on(Q.Subscribed,t=>{this.emit(X.TrackSubscribed,t,e)}),e.on(Q.Unsubscribed,t=>{this.emit(X.TrackUnsubscribed,t,e)}),e.on(Q.SubscriptionFailed,t=>{this.emit(X.TrackSubscriptionFailed,e.trackSid,t)})}getTrackPublication(e){let t=super.getTrackPublication(e);if(t)return t}getTrackPublicationByName(e){let t=super.getTrackPublicationByName(e);if(t)return t}setVolume(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:$.Source.Microphone;this.volumeMap.set(t,e);let n=this.getTrackPublication(t);n&&n.track&&n.track.setVolume(e)}getVolume(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:$.Source.Microphone,t=this.getTrackPublication(e);return t&&t.track?t.track.getVolume():this.volumeMap.get(e)}addSubscribedMediaTrack(e,t,n,r,i,a){let o=this.getTrackPublicationBySid(t);if(o||t.startsWith(`TR`)||this.trackPublications.forEach(t=>{!o&&e.kind===t.kind.toString()&&(o=t)}),!o){if(a===0){this.log.error(`could not find published track`,Object.assign(Object.assign({},this.logContext),{trackSid:t})),this.emit(X.TrackSubscriptionFailed,t);return}a===void 0&&(a=20),setTimeout(()=>{this.addSubscribedMediaTrack(e,t,n,r,i,a-1)},150);return}if(e.readyState===`ended`){this.log.error(`unable to subscribe because MediaStreamTrack is ended. Do not call MediaStreamTrack.stop()`,Object.assign(Object.assign({},this.logContext),rF(o))),this.emit(X.TrackSubscriptionFailed,t);return}let s=e.kind===`video`,c;return c=s?new oL(e,t,r,i):new rH(e,t,r,this.audioContext,this.audioOutput),c.source=o.source,c.isMuted=o.isMuted,c.setMediaStream(n),c.start(),o.setTrack(c),this.volumeMap.has(o.source)&&yI(c)&&hI(c)&&c.setVolume(this.volumeMap.get(o.source)),o}get hasMetadata(){return!!this.participantInfo}getTrackPublicationBySid(e){return this.trackPublications.get(e)}updateInfo(e){if(!super.updateInfo(e))return!1;let t=new Map,n=new Map;return e.tracks.forEach(e=>{let r=this.getTrackPublicationBySid(e.sid);if(r)r.updateInfo(e);else{let t=$.kindFromProto(e.type);if(!t)return;r=new mH(t,e,this.signalClient.connectOptions?.autoSubscribe,{loggerContextCb:()=>this.logContext,loggerName:this.loggerOptions?.loggerName}),r.updateInfo(e),n.set(e.sid,r);let i=Array.from(this.trackPublications.values()).find(e=>e.source===r?.source);i&&r.source!==$.Source.Unknown&&this.log.debug(`received a second track publication for ${this.identity} with the same source: ${r.source}`,Object.assign(Object.assign({},this.logContext),{oldTrack:rF(i),newTrack:rF(r)})),this.addTrackPublication(r)}t.set(e.sid,r)}),this.trackPublications.forEach(e=>{t.has(e.trackSid)||(this.log.trace(`detected removed track on remote participant, unpublishing`,Object.assign(Object.assign({},this.logContext),rF(e))),this.unpublishTrack(e.trackSid,!0))}),n.forEach(e=>{this.emit(X.TrackPublished,e)}),!0}unpublishTrack(e,t){let n=this.trackPublications.get(e);if(!n)return;let r=n.track;switch(r&&(r.stop(),n.setTrack(void 0)),this.trackPublications.delete(e),n.kind){case $.Kind.Audio:this.audioTrackPublications.delete(e);break;case $.Kind.Video:this.videoTrackPublications.delete(e)}t&&this.emit(X.TrackUnpublished,n)}setAudioOutput(e){return J(this,void 0,void 0,function*(){this.audioOutput=e;let t=[];this.audioTrackPublications.forEach(n=>{hI(n.track)&&yI(n.track)&&t.push(n.track.setSinkId(e.deviceId??`default`))}),yield Promise.all(t)})}addRemoteDataTrack(e){this.dataTracks.set(e.info.name,e)}removeRemoteDataTrack(e){for(let n of this.dataTracks.entries()){var t=wO(n,2);let r=t[0];e===t[1].info.sid&&this.dataTracks.delete(r)}}emit(e){var t=[...arguments].slice(1);return this.log.trace(`participant event`,Object.assign(Object.assign({},this.logContext),{event:e,args:t})),super.emit(e,...t)}},gH;(function(e){e.Disconnected=`disconnected`,e.Connecting=`connecting`,e.Connected=`connected`,e.Reconnecting=`reconnecting`,e.SignalReconnecting=`signalReconnecting`})(gH||={});var _H=4e3,vH=3e4,yH=class e extends KM.EventEmitter{get hasE2EESetup(){return this.e2eeManager!==void 0}constructor(t){var n,r,i;if(super(),n=this,this.state=gH.Disconnected,this.activeSpeakers=[],this.isE2EEEnabled=!1,this.audioEnabled=!0,this.e2eeStateMutex=new jD,this.isVideoPlaybackBlocked=!1,this.log=DM,this.statsLog=DM,this.bufferedEvents=[],this.isResuming=!1,this.pendingTrackAddedCallbacks=new Map,this.connect=(e,t,n)=>J(this,void 0,void 0,function*(){if(!AF())throw VF()?Error(`WebRTC isn't detected, have you called registerGlobals?`):Error(`LiveKit doesn't seem to be supported on this browser. Try to update your browser and make sure no browser extensions are disabling webRTC.`);let r=yield this.disconnectLock.lock();if(this.state===gH.Connected)return this.log.info(`already connected to room ${this.name}`),r(),Promise.resolve();if(this.connectFuture)return r(),this.connectFuture.promise;this.setAndEmitConnectionState(gH.Connecting),this.regionUrlProvider?.getServerUrl().toString()!==NI(e)&&(this.regionUrl=void 0,this.regionUrlProvider=void 0),HF(new URL(e))&&(this.regionUrlProvider===void 0?this.regionUrlProvider=new iB(e,t):this.regionUrlProvider.updateToken(t),this.regionUrlProvider.fetchRegionSettings().then(e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions(e)}).catch(e=>{this.log.warn(`could not fetch region settings`,{error:e})}));let i=(a,o,s)=>J(this,void 0,void 0,function*(){this.abortController&&this.abortController.abort();let c=new AbortController;this.abortController=c,r?.();try{if(yield gL.getInstance().getBackOffPromise(e),c.signal.aborted)throw gP.cancelled(`Connection attempt aborted`);yield this.attemptConnection(s??e,t,n,c),this.abortController=void 0,a()}catch(t){if(this.regionUrlProvider&&t instanceof gP&&t.reason!==hP.Cancelled&&t.reason!==hP.NotAllowed){let n=null;try{this.log.debug(`Fetching next region`),n=yield this.regionUrlProvider.getNextBestRegionUrl(this.abortController?.signal)}catch(e){if(e instanceof gP&&(e.status===401||e.reason===hP.Cancelled)){this.handleDisconnect(this.options.stopLocalTrackOnUnpublish),o(e);return}}[hP.InternalError,hP.ServerUnreachable,hP.Timeout].includes(t.reason)&&(this.log.debug(`Adding failed connection attempt to back off`),gL.getInstance().addFailedConnectionAttempt(e)),n&&!this.abortController?.signal.aborted?(this.log.info(`Initial connection failed with ConnectionError: ${t.message}. Retrying with another region: ${n}`),this.recreateEngine(!0),yield i(a,o,n)):(this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,dI(t)),o(t))}else{let e=tA.UNKNOWN_REASON;t instanceof gP&&(e=dI(t)),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e),o(t)}}}),a=this.regionUrl;return this.regionUrl=void 0,this.connectFuture=new iI((e,t)=>{i(e,t,a)},()=>{this.clearConnectionFutures()}),this.connectFuture.promise}),this.connectSignal=(e,t,n,r,i,a)=>J(this,void 0,void 0,function*(){let o=yield n.join(e,t,{autoSubscribe:r.autoSubscribe,adaptiveStream:typeof i.adaptiveStream==`object`||i.adaptiveStream,clientInfoCapabilities:this.getClientInfoCapabilities(i),maxRetries:r.maxRetries,e2eeEnabled:!!this.e2eeManager,websocketTimeout:r.websocketTimeout},a.signal,!i.singlePeerConnection),s=o.joinResponse,c=o.serverInfo;if(this.serverInfo=c,!c.version)throw new yP(`unknown server version`);return c.version===`0.15.1`&&this.options.dynacast&&(this.log.debug(`disabling dynacast due to server version`),i.dynacast=!1),s}),this.applyJoinResponse=e=>{let t=e.participant;if(this.localParticipant.sid=t.sid,this.localParticipant.identity=t.identity,this.localParticipant.setEnabledPublishCodecs(e.enabledPublishCodecs),this.e2eeManager)try{this.e2eeManager.setSifTrailer(e.sifTrailer)}catch(e){this.log.error(e instanceof Error?e.message:`Could not set SifTrailer`,{error:e})}this.handleParticipantUpdates([t,...e.otherParticipants]),e.room&&this.handleRoomUpdate(e.room)},this.attemptConnection=(e,t,n,r)=>J(this,void 0,void 0,function*(){this.state===gH.Reconnecting||this.isResuming||this.engine?.pendingReconnect?(this.log.info(`Reconnection attempt replaced by new connection attempt`),this.recreateEngine(!0)):this.maybeCreateEngine(),this.regionUrlProvider?.isCloud()&&this.engine.setRegionStrategy(this.createRegionStrategy()),this.acquireAudioContext(),this.connOptions=Object.assign(Object.assign({},XR),n),this.connOptions.rtcConfig&&(this.engine.rtcConfig=this.connOptions.rtcConfig),this.connOptions.peerConnectionTimeout&&(this.engine.peerConnectionTimeout=this.connOptions.peerConnectionTimeout);try{let n=yield this.connectSignal(e,t,this.engine,this.connOptions,this.options,r);this.applyJoinResponse(n),this.setupLocalParticipantEvents(),this.emit(Y.SignalConnected)}catch(e){yield this.engine.close(),this.recreateEngine();let t=r.signal.aborted?gP.cancelled(`Signal connection aborted`):gP.serverUnreachable(`could not establish signal connection`);throw e instanceof Error&&(t.message=`${t.message}: ${e.message}`),e instanceof gP&&(t.reason=e.reason,t.status=e.status),this.log.debug(`error trying to establish signal connection`,{error:e}),t}if(r.signal.aborted)throw yield this.engine.close(),this.recreateEngine(),gP.cancelled(`Connection attempt aborted`);try{yield this.engine.waitForPCInitialConnection(this.connOptions.peerConnectionTimeout,r)}catch(e){throw yield this.engine.close(),this.recreateEngine(),e}BF()&&this.options.disconnectOnPageLeave&&(window.addEventListener(`pagehide`,this.onPageLeave),window.addEventListener(`beforeunload`,this.onPageLeave)),BF()&&window.addEventListener(`freeze`,this.onPageLeave),this.setAndEmitConnectionState(gH.Connected),this.emit(Y.Connected),gL.getInstance().resetFailedConnectionAttempts(e),this.registerConnectionReconcile(),this.regionUrlProvider&&this.regionUrlProvider.notifyConnected()}),this.disconnect=function(){return J(n,[...arguments],void 0,function(){var e=this;let t=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0;return function*(){var n,r,i;let a=yield e.disconnectLock.lock();try{if(e.state===gH.Disconnected){e.log.debug(`already disconnected`);return}if(e.log.info(`disconnect from room`),e.state===gH.Connecting||e.state===gH.Reconnecting||e.isResuming){let t=`Abort connection attempt due to user initiated disconnect`;e.log.warn(t),(n=e.abortController)==null||n.abort(t),(i=(r=e.connectFuture)?.reject)==null||i.call(r,gP.cancelled(`Client initiated disconnect`)),e.connectFuture=void 0}e.engine&&(e.engine.client.isDisconnected||(yield e.engine.client.sendLeave()),yield e.engine.close()),e.handleDisconnect(t,tA.CLIENT_INITIATED),e.engine=void 0}finally{a()}}()})},this.onPageLeave=()=>J(this,void 0,void 0,function*(){this.log.info(`Page leave detected, disconnecting`),yield this.disconnect()}),this.startAudio=()=>J(this,void 0,void 0,function*(){let e=[],t=cP();if(t&&t.os===`iOS`){let t=`livekit-dummy-audio-el`,n=document.getElementById(t);if(!n){n=document.createElement(`audio`),n.id=t,n.autoplay=!0,n.hidden=!0;let e=rI();e.enabled=!0;let r=new MediaStream([e]);n.srcObject=r,document.addEventListener(`visibilitychange`,()=>{n&&(n.srcObject=document.hidden?null:r,document.hidden||(this.log.debug(`page visible again, triggering startAudio to resume playback and update playback status`),this.startAudio()))}),document.body.append(n),this.once(Y.Disconnected,()=>{n?.remove(),n=null})}e.push(n)}this.remoteParticipants.forEach(t=>{t.audioTrackPublications.forEach(t=>{t.track&&t.track.attachedElements.forEach(t=>{e.push(t)})})});try{yield Promise.all([this.acquireAudioContext(),...e.map(e=>(this.options.webAudioMix||(e.muted=!1),e.play()))]),this.handleAudioPlaybackStarted()}catch(e){throw this.handleAudioPlaybackFailed(e),e}}),this.startVideo=()=>J(this,void 0,void 0,function*(){let e=[];for(let t of this.remoteParticipants.values())t.videoTrackPublications.forEach(t=>{var n;(n=t.track)==null||n.attachedElements.forEach(t=>{e.includes(t)||e.push(t)})});yield Promise.all(e.map(e=>e.play())).then(()=>{this.handleVideoPlaybackStarted()}).catch(e=>{e.name===`NotAllowedError`?this.handleVideoPlaybackFailed():this.log.warn("Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler")})}),this.handleRestarting=()=>{this.clearConnectionReconcile(),this.isResuming=!1;for(let e of this.remoteParticipants.values())this.handleParticipantDisconnected(e.identity,e);this.setAndEmitConnectionState(gH.Reconnecting)&&this.emit(Y.Reconnecting)},this.handleRestarted=()=>{this.outgoingDataTrackManager.sfuWillRepublishTracks(),this.incomingDataTrackManager.resendSubscriptionUpdates()},this.handleSignalRestarted=e=>J(this,void 0,void 0,function*(){this.log.debug(`signal reconnected to server, region ${e.serverRegion}`,{region:e.serverRegion}),this.bufferedEvents=[],this.applyJoinResponse(e);try{yield this.localParticipant.republishAllTracks(void 0,!0)}catch(e){this.log.error(`error trying to re-publish tracks after reconnection`,{error:e})}try{yield this.engine.waitForRestarted(),this.log.debug(`fully reconnected to server`,{region:e.serverRegion})}catch{return}this.setAndEmitConnectionState(gH.Connected),this.emit(Y.Reconnected),this.registerConnectionReconcile(),this.emitBufferedEvents()}),this.handleParticipantUpdates=e=>{for(let t of e){if(t.identity===this.localParticipant.identity){this.localParticipant.updateInfo(t);continue}t.identity===``&&(t.identity=this.sidToIdentity.get(t.sid)??``);let e=this.remoteParticipants.get(t.identity);t.state===uA.DISCONNECTED?this.handleParticipantDisconnected(t.identity,e,t.disconnectReason===tA.UNKNOWN_REASON?void 0:t.disconnectReason):this.getOrCreateParticipant(t.identity,t)}let t=new Map(e.filter(e=>e.identity!==this.localParticipant.identity).map(e=>[e.identity,e.dataTracks.map(e=>kL.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)},this.handleActiveSpeakersUpdate=e=>{let t=[],n={};e.forEach(e=>{if(n[e.sid]=!0,e.sid===this.localParticipant.sid)this.localParticipant.audioLevel=e.level,this.localParticipant.setIsSpeaking(!0),t.push(this.localParticipant);else{let n=this.getRemoteParticipantBySid(e.sid);n&&(n.audioLevel=e.level,n.setIsSpeaking(!0),t.push(n))}}),n[this.localParticipant.sid]||(this.localParticipant.audioLevel=0,this.localParticipant.setIsSpeaking(!1)),this.remoteParticipants.forEach(e=>{n[e.sid]||(e.audioLevel=0,e.setIsSpeaking(!1))}),this.activeSpeakers=t,this.emitWhenConnected(Y.ActiveSpeakersChanged,t)},this.handleSpeakersChanged=e=>{let t=new Map;this.activeSpeakers.forEach(e=>{let n=this.remoteParticipants.get(e.identity);n&&n.sid!==e.sid||t.set(e.sid,e)}),e.forEach(e=>{let n=this.getRemoteParticipantBySid(e.sid);e.sid===this.localParticipant.sid&&(n=this.localParticipant),n&&(n.audioLevel=e.level,n.setIsSpeaking(e.active),e.active?t.set(e.sid,n):t.delete(e.sid))});let n=Array.from(t.values());n.sort((e,t)=>t.audioLevel-e.audioLevel),this.activeSpeakers=n,this.emitWhenConnected(Y.ActiveSpeakersChanged,n)},this.handleStreamStateUpdate=e=>{e.streamStates.forEach(e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);if(!n||!n.track)return;let r=$.streamStateFromProto(e.state),i=n.track.streamState;n.track.setStreamState(r),r!==i&&(t.emit(X.TrackStreamStateChanged,n,n.track.streamState),this.emitWhenConnected(Y.TrackStreamStateChanged,n,n.track.streamState,t))})},this.handleSubscriptionPermissionUpdate=e=>{let t=this.getRemoteParticipantBySid(e.participantSid);if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setAllowed(e.allowed)},this.handleSubscriptionError=e=>{this.cancelPendingTrackAdded(e.trackSid);let t=Array.from(this.remoteParticipants.values()).find(t=>t.trackPublications.has(e.trackSid));if(!t)return;let n=t.getTrackPublicationBySid(e.trackSid);n&&n.setSubscriptionError(e.err)},this.handleDataPacket=(e,t)=>{let n=this.remoteParticipants.get(e.participantIdentity);if(e.value.case===`user`)this.handleUserPacket(n,e.value.value,e.kind,t);else if(e.value.case===`transcription`)this.handleTranscription(n,e.value.value);else if(e.value.case===`sipDtmf`)this.handleSipDtmf(n,e.value.value);else if(e.value.case===`chatMessage`)this.handleChatMessage(n,e.value.value);else if(e.value.case===`metrics`)this.handleMetrics(e.value.value,n);else if(e.value.case===`streamHeader`||e.value.case===`streamChunk`||e.value.case===`streamTrailer`)this.handleDataStream(e,t);else if(e.value.case===`rpcRequest`){let t=e.value.value;this.rpcServerManager.handleIncomingRpcRequest(e.participantIdentity,t)}else if(e.value.case===`rpcResponse`){let t=e.value.value;switch(t.value.case){case`payload`:this.rpcClientManager.handleIncomingRpcResponseSuccess(t.requestId,t.value.value);break;case`error`:this.rpcClientManager.handleIncomingRpcResponseFailure(t.requestId,KV.fromProto(t.value.value));break;default:this.log.warn(`Unknown rpcResponse.value.case: ${t.value.case}`,this.logContext)}}else e.value.case===`rpcAck`&&this.rpcClientManager.handleIncomingRpcAck(e.value.value.requestId)},this.handleUserPacket=(e,t,n,r)=>{this.emit(Y.DataReceived,t.payload,e,n,t.topic,r),e?.emit(X.DataReceived,t.payload,n,r)},this.handleSipDtmf=(e,t)=>{this.emit(Y.SipDTMFReceived,t,e),e?.emit(X.SipDTMFReceived,t)},this.handleTranscription=(e,t)=>{let n=t.transcribedParticipantIdentity===this.localParticipant.identity?this.localParticipant:this.getParticipantByIdentity(t.transcribedParticipantIdentity),r=n?.trackPublications.get(t.trackId),i=lI(t,this.transcriptionReceivedTimes);r?.emit(Q.TranscriptionReceived,i),n?.emit(X.TranscriptionReceived,i,r),this.emit(Y.TranscriptionReceived,i,n,r)},this.handleChatMessage=(e,t)=>{let n=uI(t);this.emit(Y.ChatMessage,n,e)},this.handleMetrics=(e,t)=>{this.emit(Y.MetricsReceived,e,t)},this.handleDataStream=(e,t)=>{this.incomingDataStreamManager.handleDataStreamPacket(e,t)},this.bufferedSegments=new Map,this.handleAudioPlaybackStarted=()=>{this.canPlaybackAudio||(this.audioEnabled=!0,this.emit(Y.AudioPlaybackStatusChanged,!0))},this.handleAudioPlaybackFailed=e=>{this.log.warn(`could not playback audio`,{error:e}),this.canPlaybackAudio&&(this.audioEnabled=!1,this.emit(Y.AudioPlaybackStatusChanged,!1))},this.handleVideoPlaybackStarted=()=>{this.isVideoPlaybackBlocked&&(this.isVideoPlaybackBlocked=!1,this.emit(Y.VideoPlaybackStatusChanged,!0))},this.handleVideoPlaybackFailed=()=>{this.isVideoPlaybackBlocked||(this.isVideoPlaybackBlocked=!0,this.emit(Y.VideoPlaybackStatusChanged,!1))},this.handleDeviceChange=()=>J(this,void 0,void 0,function*(){cP()?.os!==`iOS`&&(yield this.selectDefaultDevices()),this.emit(Y.MediaDevicesChanged)}),this.handleRoomUpdate=e=>{let t=this.roomInfo;this.roomInfo=e,t&&t.metadata!==e.metadata&&this.emitWhenConnected(Y.RoomMetadataChanged,e.metadata),t?.activeRecording!==e.activeRecording&&this.emitWhenConnected(Y.RecordingStatusChanged,e.activeRecording)},this.handleConnectionQualityUpdate=e=>{e.updates.forEach(e=>{if(e.participantSid===this.localParticipant.sid){this.localParticipant.setConnectionQuality(e.quality);return}let t=this.getRemoteParticipantBySid(e.participantSid);t&&t.setConnectionQuality(e.quality)})},this.getRemoteParticipantClientProtocol=e=>this.remoteParticipants.get(e)?.clientProtocol??0,this.getRemoteParticipantCapabilities=e=>this.remoteParticipants.get(e)?.capabilities??[],this.getAllRemoteParticipantIdentities=()=>Array.from(this.remoteParticipants.keys()),this.logWebRTCStats=()=>J(this,void 0,void 0,function*(){let e=this.engine?.pcManager;if(e)try{let t=wO(yield Promise.all([e.publisher.getStats(),e.subscriber?.getStats()]),2),n=t[0],r=t[1],i=n&&FP(n),a=r&&FP(r);this.statsLog.info(`webrtc stats`,{publisher:i?.connection,subscriber:a?.connection,inbound:[...i?.inbound??[],...a?.inbound??[]],outbound:i?.outbound})}catch(e){this.statsLog.debug(`could not collect webrtc stats`,{error:e})}}),this.onLocalParticipantMetadataChanged=e=>{this.emit(Y.ParticipantMetadataChanged,e,this.localParticipant)},this.onLocalParticipantNameChanged=e=>{this.emit(Y.ParticipantNameChanged,e,this.localParticipant)},this.onLocalAttributesChanged=e=>{this.emit(Y.ParticipantAttributesChanged,e,this.localParticipant)},this.onLocalTrackMuted=e=>{this.emit(Y.TrackMuted,e,this.localParticipant)},this.onLocalTrackUnmuted=e=>{this.emit(Y.TrackUnmuted,e,this.localParticipant)},this.onTrackProcessorUpdate=e=>{var t;(t=e?.onPublish)==null||t.call(e,this)},this.onLocalTrackPublished=e=>J(this,void 0,void 0,function*(){var t,n,r,i;(t=e.track)==null||t.on(Q.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.on(Q.Restarted,this.onLocalTrackRestarted),(i=(r=e.track?.getProcessor())?.onPublish)==null||i.call(r,this),this.emit(Y.LocalTrackPublished,e,this.localParticipant),vI(e.track)&&(yield e.track.checkForSilence())&&this.emit(Y.LocalAudioSilenceDetected,e);let a=yield e.track?.getDeviceId(!1),o=$P(e.source);o&&a&&a!==this.localParticipant.activeDeviceMap.get(o)&&(this.localParticipant.activeDeviceMap.set(o,a),this.emit(Y.ActiveDeviceChanged,o,a))}),this.onLocalTrackUnpublished=e=>{var t,n;(t=e.track)==null||t.off(Q.TrackProcessorUpdate,this.onTrackProcessorUpdate),(n=e.track)==null||n.off(Q.Restarted,this.onLocalTrackRestarted),this.emit(Y.LocalTrackUnpublished,e,this.localParticipant)},this.onLocalTrackRestarted=e=>J(this,void 0,void 0,function*(){let t=yield e.getDeviceId(!1),n=$P(e.source);n&&t&&t!==this.localParticipant.activeDeviceMap.get(n)&&(this.log.debug(`local track restarted, setting ${n} ${t} active`),this.localParticipant.activeDeviceMap.set(n,t),this.emit(Y.ActiveDeviceChanged,n,t))}),this.onLocalConnectionQualityChanged=e=>{this.emit(Y.ConnectionQualityChanged,e,this.localParticipant)},this.onMediaDevicesError=(e,t)=>{this.emit(Y.MediaDevicesError,e,t)},this.onLocalParticipantPermissionsChanged=e=>{this.emit(Y.ParticipantPermissionsChanged,e,this.localParticipant)},this.onLocalChatMessageSent=e=>{this.emit(Y.ChatMessage,e,this.localParticipant)},this.setMaxListeners(100),this.remoteParticipants=new Map,this.sidToIdentity=new Map,this.options=Object.assign(Object.assign({},YR),t),this.log=OM(this.options.loggerName??EM.Room,()=>this.logContext),this.statsLog=OM(EM.Stats,()=>this.logContext),this.transcriptionReceivedTimes=new Map,this.options.audioCaptureDefaults=Object.assign(Object.assign({},qR),t?.audioCaptureDefaults),this.options.videoCaptureDefaults=Object.assign(Object.assign({},JR),t?.videoCaptureDefaults),this.options.publishDefaults=Object.assign(Object.assign({},KR),t?.publishDefaults),this.maybeCreateEngine(),this.incomingDataStreamManager=new hB(this.options.dataStream?.maxPayloadByteLength),this.outgoingDataStreamManager=new jB(this.engine,this.log,this.getRemoteParticipantClientProtocol,this.getRemoteParticipantCapabilities,this.getAllRemoteParticipantIdentities),this.incomingDataTrackManager=new AV({e2eeManager:this.e2eeManager}),this.incomingDataTrackManager.on(`sfuUpdateSubscription`,e=>{this.engine.client.sendUpdateDataSubscription(e.sid,e.subscribe)}).on(`trackPublished`,e=>{var t;e.track.publisherIdentity!==this.localParticipant.identity&&(this.emit(Y.DataTrackPublished,e.track),(t=this.remoteParticipants.get(e.track.publisherIdentity))==null||t.addRemoteDataTrack(e.track))}).on(`trackUnpublished`,e=>{var t;e.publisherIdentity!==this.localParticipant.identity&&(this.emit(Y.DataTrackUnpublished,e.sid),(t=this.remoteParticipants.get(e.publisherIdentity))==null||t.removeRemoteDataTrack(e.sid))}),this.outgoingDataTrackManager=new GV({e2eeManager:this.e2eeManager}),this.outgoingDataTrackManager.on(`sfuPublishRequest`,e=>{this.engine.client.sendPublishDataTrackRequest(e.handle,e.name,e.usesE2ee)}).on(`sfuUnpublishRequest`,e=>{this.engine.client.sendUnPublishDataTrackRequest(e.handle)}).on(`trackPublished`,e=>{this.emit(Y.LocalDataTrackPublished,e.track)}).on(`trackUnpublished`,e=>{this.emit(Y.LocalDataTrackUnpublished,e.sid)}).on(`packetAvailable`,e=>{let t=e.handle,n=e.bytes;this.engine.sendDataTrackFrame(n).finally(()=>this.outgoingDataTrackManager.handlePacketSendComplete(t))}),this.registerRpcDataStreamHandler(),this.rpcClientManager=new tH(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol,()=>this.engine?.serverVersion),this.rpcClientManager.on(`sendDataPacket`,e=>{let t=e.packet;var n;(n=this.engine)==null||n.sendDataPacket(t,rz.RELIABLE)}),this.rpcServerManager=new nH(this.log,this.outgoingDataStreamManager,this.getRemoteParticipantClientProtocol),this.rpcServerManager.on(`sendDataPacket`,e=>{let t=e.packet;var n;(n=this.engine)==null||n.sendDataPacket(t,rz.RELIABLE)}),this.disconnectLock=new jD,this.localParticipant=new dH(``,``,this.engine,this.options,this.outgoingDataStreamManager,this.outgoingDataTrackManager,this.rpcClientManager,this.rpcServerManager),this.setupFrameMetadata(),(this.options.e2ee||this.options.encryption)&&this.setupE2EE(),this.engine.e2eeManager=this.e2eeManager,this.incomingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.outgoingDataTrackManager.updateE2eeManager(this.e2eeManager??null),this.options.videoCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`videoinput`,oI(this.options.videoCaptureDefaults.deviceId)),this.options.audioCaptureDefaults.deviceId&&this.localParticipant.activeDeviceMap.set(`audioinput`,oI(this.options.audioCaptureDefaults.deviceId)),this.options.audioOutput?.deviceId&&this.switchActiveDevice(`audiooutput`,oI(this.options.audioOutput.deviceId)).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`)),BF()){let t=new AbortController,n;if(e.cleanupRegistry){let r=new WeakRef(this);n=()=>{let e=r.deref();e&&e.handleDeviceChange()},e.cleanupRegistry.register(this,()=>{t.abort()})}else n=this.handleDeviceChange;(i=(r=navigator.mediaDevices)?.addEventListener)==null||i.call(r,`devicechange`,n,{signal:t.signal})}}registerTextStreamHandler(e,t){return this.incomingDataStreamManager.registerTextStreamHandler(e,t)}unregisterTextStreamHandler(e){return this.incomingDataStreamManager.unregisterTextStreamHandler(e)}registerByteStreamHandler(e,t){return this.incomingDataStreamManager.registerByteStreamHandler(e,t)}unregisterByteStreamHandler(e){return this.incomingDataStreamManager.unregisterByteStreamHandler(e)}registerRpcMethod(e,t){this.rpcServerManager.registerRpcMethod(e,t)}unregisterRpcMethod(e){this.rpcServerManager.unregisterRpcMethod(e)}setE2EEEnabled(e){return J(this,void 0,void 0,function*(){let t=yield this.e2eeStateMutex.lock();try{if(this.e2eeManager)this.isE2EEEnabled!==e&&(yield this.localParticipant.setE2EEEnabled(e),this.localParticipant.identity!==``&&this.e2eeManager.setParticipantCryptorEnabled(e,this.localParticipant.identity));else throw Error(`e2ee not configured, please set e2ee settings within the room options`)}finally{t()}})}setupE2EE(){var e,t;let n=!!this.options.encryption,r=this.options.encryption||this.options.e2ee;r&&(`e2eeManager`in r?(this.e2eeManager=r.e2eeManager,this.e2eeManager.isDataChannelEncryptionEnabled=n):this.e2eeManager=new uL(r,n),this.e2eeManager.on(HI.ParticipantEncryptionStatusChanged,(e,t)=>{SI(t)&&(this.isE2EEEnabled=e),this.emit(Y.ParticipantEncryptionStatusChanged,e,t)}),this.e2eeManager.on(HI.EncryptionError,(e,t)=>{let n=t?this.getParticipantByIdentity(t):void 0;this.emit(Y.EncryptionError,e,n)}),(e=this.e2eeManager)==null||e.setup(this),(t=this.e2eeManager)==null||t.setupEngine(this.engine))}setupFrameMetadata(){let e=this.options.frameMetadata??this.options.packetTrailer;this.frameMetadataManager=new pL(e),this.frameMetadataManager.setup(this)}get logContext(){return{room:this.name,roomID:this.roomInfo?.sid,participant:this.localParticipant?.identity,participantID:this.localParticipant?.sid}}get isRecording(){return this.roomInfo?.activeRecording??!1}getSid(){return this.state===gH.Disconnected?aP.resolve(``):this.roomInfo&&this.roomInfo.sid!==``?aP.resolve(this.roomInfo.sid):new aP((e,t)=>{let n=t=>{t.sid!==``&&(this.engine.off(Z.RoomUpdate,n),e(t.sid))};this.engine.on(Z.RoomUpdate,n),this.once(Y.Disconnected,()=>{this.engine.off(Z.RoomUpdate,n),t(new bP(`Room disconnected before room server id was available`))})})}get name(){return this.roomInfo?.name??``}get metadata(){return this.roomInfo?.metadata}get numParticipants(){return this.roomInfo?.numParticipants??0}get numPublishers(){return this.roomInfo?.numPublishers??0}maybeCreateEngine(){(!this.engine||!this.engine.isNewlyCreated&&this.engine.isClosed)&&(this.engine=new $z(this.options),this.engine.e2eeManager=this.e2eeManager,this.engine.on(Z.ParticipantUpdate,this.handleParticipantUpdates).on(Z.RoomUpdate,this.handleRoomUpdate).on(Z.SpeakersChanged,this.handleSpeakersChanged).on(Z.StreamStateChanged,this.handleStreamStateUpdate).on(Z.ConnectionQualityUpdate,this.handleConnectionQualityUpdate).on(Z.SubscriptionError,this.handleSubscriptionError).on(Z.SubscriptionPermissionUpdate,this.handleSubscriptionPermissionUpdate).on(Z.MediaTrackAdded,(e,t,n)=>{this.onTrackAdded(e,t,n)}).on(Z.Disconnected,e=>{this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,e)}).on(Z.ActiveSpeakersUpdate,this.handleActiveSpeakersUpdate).on(Z.DataPacketReceived,this.handleDataPacket).on(Z.Resuming,()=>{this.clearConnectionReconcile(),this.isResuming=!0,this.log.debug(`Resuming signal connection`),this.setAndEmitConnectionState(gH.SignalReconnecting)&&this.emit(Y.SignalReconnecting)}).on(Z.Resumed,()=>{this.registerConnectionReconcile(),this.isResuming=!1,this.log.debug(`Resumed signal connection`),this.updateSubscriptions(),this.setAndEmitConnectionState(gH.Connected)&&this.emit(Y.Reconnected),this.emitBufferedEvents()}).on(Z.SignalResumed,()=>{(this.state===gH.Reconnecting||this.isResuming)&&this.sendSyncState(),this.emitBufferedEvents()}).on(Z.Restarting,this.handleRestarting).on(Z.Restarted,this.handleRestarted).on(Z.SignalRestarted,this.handleSignalRestarted).on(Z.Offline,()=>{this.setAndEmitConnectionState(gH.Reconnecting)&&this.emit(Y.Reconnecting)}).on(Z.DCBufferStatusChanged,(e,t)=>{this.emit(Y.DCBufferStatusChanged,e,t)}).on(Z.LocalTrackSubscribed,e=>{this.handleLocalTrackSubscribed(e)}).on(Z.RoomMoved,e=>{this.log.debug(`room moved`,e),e.room&&this.handleRoomUpdate(e.room),this.remoteParticipants.forEach((e,t)=>{this.handleParticipantDisconnected(t,e)}),this.emit(Y.Moved,e.room.name),e.participant?this.handleParticipantUpdates([e.participant,...e.otherParticipants]):this.handleParticipantUpdates(e.otherParticipants)}).on(Z.PublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received PublishDataTrackResponse, but event.info was ${e.info}, so skipping.`);return}this.outgoingDataTrackManager.receivedSfuPublishResponse(e.info.pubHandle,{type:`ok`,data:{sid:e.info.sid,pubHandle:e.info.pubHandle,name:e.info.name,usesE2ee:e.info.encryption!==pA.NONE}})}).on(Z.UnPublishDataTrackResponse,e=>{if(!e.info){this.log.warn(`received UnPublishDataTrackResponse, but event.info was ${e.info}, so skipping.`);return}this.outgoingDataTrackManager.receivedSfuUnpublishResponse(e.info.pubHandle)}).on(Z.DataTrackSubscriberHandles,e=>{let t=new Map(Object.entries(e.subHandles).map(e=>{let t=wO(e,2),n=t[0],r=t[1];return[parseInt(n,10),r.trackSid]}));this.incomingDataTrackManager.receivedSfuSubscriberHandles(t)}).on(Z.DataTrackPacketReceived,e=>{try{this.incomingDataTrackManager.packetReceived(e)}catch(e){throw e}}).on(Z.Joined,e=>{let t=new Map(e.otherParticipants.map(e=>[e.identity,e.dataTracks.map(e=>kL.from(e))]));this.incomingDataTrackManager.receiveSfuPublicationUpdates(t)}).on(Z.TokenRefreshed,e=>{var t;(t=this.regionUrlProvider)==null||t.updateToken(e)}).on(Z.ServerRegionsReported,e=>{var t;(t=this.regionUrlProvider)==null||t.setServerReportedRegions({regionSettings:e,updatedAtInMs:Date.now(),maxAgeInMs:nB})}),this.localParticipant&&this.localParticipant.setupEngine(this.engine),this.e2eeManager&&this.e2eeManager.setupEngine(this.engine),this.outgoingDataStreamManager&&this.outgoingDataStreamManager.setupEngine(this.engine))}createRegionStrategy(){return{getNextUrl:e=>J(this,void 0,void 0,function*(){return this.regionUrlProvider?this.regionUrlProvider.getNextBestRegionUrl(e):null}),resetAttempts:()=>this.regionUrlProvider?.resetAttempts()}}static getLocalDevices(e){let t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:!0;return vL.getInstance().getDevices(e,t)}prepareConnection(e,t){return J(this,void 0,void 0,function*(){if(this.state===gH.Disconnected){this.log.debug(`prepareConnection to ${e}`);try{if(HF(new URL(e))&&t){this.regionUrlProvider=new iB(e,t);let n=yield this.regionUrlProvider.getNextBestRegionUrl();n&&this.state===gH.Disconnected&&(this.regionUrl=n,yield fetch(cI(n),{method:`HEAD`}),this.log.debug(`prepared connection to ${n}`))}else yield fetch(cI(e),{method:`HEAD`})}catch(e){this.log.warn(`could not prepare connection`,{error:e})}}})}getParticipantByIdentity(e){return this.localParticipant.identity===e?this.localParticipant:this.remoteParticipants.get(e)}clearConnectionFutures(){this.connectFuture=void 0}simulateScenario(e,t){return J(this,void 0,void 0,function*(){let n=()=>J(this,void 0,void 0,function*(){}),r;switch(e){case`signal-reconnect`:yield this.engine.client.handleOnClose(`simulate disconnect`);break;case`fail-on-v1-path`:this.engine.failNextV1Path();break;case`speaker`:r=new aM({scenario:{case:`speakerUpdate`,value:3}});break;case`node-failure`:r=new aM({scenario:{case:`nodeFailure`,value:!0}});break;case`server-leave`:r=new aM({scenario:{case:`serverLeave`,value:!0}});break;case`migration`:r=new aM({scenario:{case:`migration`,value:!0}});break;case`resume-reconnect`:this.engine.failNext(),yield this.engine.client.handleOnClose(`simulate resume-disconnect`);break;case`disconnect-signal-on-resume`:n=()=>J(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new aM({scenario:{case:`disconnectSignalOnResume`,value:!0}});break;case`disconnect-signal-on-resume-no-messages`:n=()=>J(this,void 0,void 0,function*(){yield this.engine.client.handleOnClose(`simulate resume-disconnect`)}),r=new aM({scenario:{case:`disconnectSignalOnResumeNoMessages`,value:!0}});break;case`full-reconnect`:this.engine.fullReconnectOnNext=!0,yield this.engine.client.handleOnClose(`simulate full-reconnect`);break;case`force-tcp`:case`force-tls`:r=new aM({scenario:{case:`switchCandidateProtocol`,value:e===`force-tls`?2:1}}),n=()=>J(this,void 0,void 0,function*(){let e=this.engine.client.onLeave;e&&e(new Lj({reason:tA.CLIENT_INITIATED,action:Rj.RECONNECT}))});break;case`subscriber-bandwidth`:if(t===void 0||typeof t!=`number`)throw Error(`subscriber-bandwidth requires a number as argument`);r=new aM({scenario:{case:`subscriberBandwidth`,value:pI(t)}});break;case`leave-full-reconnect`:r=new aM({scenario:{case:`leaveRequestFullReconnect`,value:!0}})}r&&(yield this.engine.client.sendSimulateScenario(r),yield n())})}get canPlaybackAudio(){return this.audioEnabled}get canPlaybackVideo(){return!this.isVideoPlaybackBlocked}getActiveDevice(e){return this.localParticipant.activeDeviceMap.get(e)}switchActiveDevice(e,t){return J(this,arguments,void 0,function(e,t){var n=this;let r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:!0;return function*(){var i,a;let o=!0,s=!1,c=r?{exact:t}:t;if(e===`audioinput`){s=n.localParticipant.audioTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.audioCaptureDefaults.deviceId;n.options.audioCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.audioTrackPublications.values()).filter(e=>e.source===$.Source.Microphone);try{o=(yield Promise.all(r.map(e=>e.audioTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.audioCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`videoinput`){s=n.localParticipant.videoTrackPublications.size===0;let t=n.getActiveDevice(e)??n.options.videoCaptureDefaults.deviceId;n.options.videoCaptureDefaults.deviceId=c;let r=Array.from(n.localParticipant.videoTrackPublications.values()).filter(e=>e.source===$.Source.Camera);try{o=(yield Promise.all(r.map(e=>e.videoTrack?.setDeviceId(c)))).every(e=>e===!0)}catch(e){throw n.options.videoCaptureDefaults.deviceId=t,e}let i=r.some(e=>e.track?.isMuted??!1);o&&i&&(s=!0)}else if(e===`audiooutput`){if(s=!0,!kF()&&!n.options.webAudioMix||n.options.webAudioMix&&n.audioContext&&!(`setSinkId`in n.audioContext))throw Error(`cannot switch audio output, the current browser does not support it`);n.options.webAudioMix&&(t=(yield vL.getInstance().normalizeDeviceId(`audiooutput`,t))??``),(a=n.options).audioOutput??(a.audioOutput={});let r=n.getActiveDevice(e)??n.options.audioOutput.deviceId;n.options.audioOutput.deviceId=t;try{n.options.webAudioMix&&((i=n.audioContext)==null||i.setSinkId(t)),yield Promise.all(Array.from(n.remoteParticipants.values()).map(e=>e.setAudioOutput({deviceId:t})))}catch(e){throw n.options.audioOutput.deviceId=r,e}}return s&&(n.localParticipant.activeDeviceMap.set(e,t),n.emit(Y.ActiveDeviceChanged,e,t)),o}()})}setupLocalParticipantEvents(){this.localParticipant.on(X.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).on(X.ParticipantNameChanged,this.onLocalParticipantNameChanged).on(X.AttributesChanged,this.onLocalAttributesChanged).on(X.TrackMuted,this.onLocalTrackMuted).on(X.TrackUnmuted,this.onLocalTrackUnmuted).on(X.LocalTrackPublished,this.onLocalTrackPublished).on(X.LocalTrackUnpublished,this.onLocalTrackUnpublished).on(X.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).on(X.MediaDevicesError,this.onMediaDevicesError).on(X.AudioStreamAcquired,this.startAudio).on(X.ChatMessage,this.onLocalChatMessageSent).on(X.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged)}recreateEngine(e){let t=this.engine;e&&t&&!t.client.isDisconnected?t.client.sendLeave().finally(()=>t.close()):t?.close(),this.engine=void 0,this.isResuming=!1,this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.bufferedEvents=[],this.maybeCreateEngine()}onTrackAdded(e,t,n){if([gH.Connecting,gH.Reconnecting].includes(this.state)){let r=kI(e,t);this.log.debug(`deferring on track for later`,{mediaTrackId:e.id,mediaStreamId:t.id,tracksInStream:t.getTracks().map(e=>e.id)});let i=()=>{a(),this.onTrackAdded(e,t,n)},a=()=>{if(this.off(Y.Reconnected,i),this.off(Y.Connected,i),this.off(Y.Disconnected,a),r){let e=this.pendingTrackAddedCallbacks.get(r);e?.delete(a),e?.size===0&&this.pendingTrackAddedCallbacks.delete(r)}};if(this.once(Y.Reconnected,i),this.once(Y.Connected,i),this.once(Y.Disconnected,a),r){let e=this.pendingTrackAddedCallbacks.get(r)??new Set;e.add(a),this.pendingTrackAddedCallbacks.set(r,e)}return}if(this.state===gH.Disconnected){this.log.warn(`skipping incoming track after Room disconnected`);return}if(e.readyState===`ended`){this.log.debug(`skipping incoming track as it already ended`);return}let r=_F(t.id),i=r[0],a=r[1],o=kI(e,t)??e.id;if(i===this.localParticipant.sid){this.log.warn(`tried to create RemoteParticipant for local participant`);return}let s=Array.from(this.remoteParticipants.values()).find(e=>e.sid===i);if(!s){i.startsWith(`PA`)&&this.log.error(`Tried to add a track for a participant, that's not present. Sid: ${i}`);return}if(!o.startsWith(`TR`)){let e=this.engine.getTrackIdForReceiver(n);if(!e){this.log.error(`Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ${i}`);return}o=e}o.startsWith(`TR`)||this.log.warn(`Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ${i}, streamId: ${a}, trackId: ${o}`,{remoteParticipantID:i,streamId:a,trackId:o});let c;this.options.adaptiveStream&&(c=typeof this.options.adaptiveStream==`object`?this.options.adaptiveStream:{});let l=s.addSubscribedMediaTrack(e,o,t,n,c);l?.isEncrypted&&!this.e2eeManager&&this.emit(Y.EncryptionError,Error(`Encrypted ${l.source} track received from participant ${s.sid}, but room does not have encryption enabled!`))}cancelPendingTrackAdded(e){var t;(t=this.pendingTrackAddedCallbacks.get(e))==null||t.forEach(e=>e())}handleLocalTrackSubscribed(e){let t=()=>this.localParticipant.getTrackPublications().find(t=>t.trackSid===e),n=t();if(n){this.emitLocalTrackSubscribed(n);return}this.log.debug(`deferring LocalTrackSubscribed, publication not yet available`,{subscribedSid:e});let r,i=t=>{t.trackSid===e&&(a(),this.emitLocalTrackSubscribed(t))},a=()=>{clearTimeout(r),this.localParticipant.off(X.LocalTrackPublished,i),this.off(Y.Disconnected,a)};this.localParticipant.on(X.LocalTrackPublished,i),this.once(Y.Disconnected,a),r=setTimeout(()=>{a();let n=t();n?this.emitLocalTrackSubscribed(n):this.log.warn(`could not find local track publication for LocalTrackSubscribed event after timeout`,{subscribedSid:e})},1e4)}emitLocalTrackSubscribed(e){this.localParticipant.emit(X.LocalTrackSubscribed,e),this.emitWhenConnected(Y.LocalTrackSubscribed,e,this.localParticipant)}handleDisconnect(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:!0,t=arguments.length>1?arguments[1]:void 0;var n,r;if(this.clearConnectionReconcile(),this.isResuming=!1,this.bufferedEvents=[],this.transcriptionReceivedTimes.clear(),this.incomingDataStreamManager.clearControllers(),this.incomingDataTrackManager.reset(),this.outgoingDataTrackManager.reset(),this.state!==gH.Disconnected){this.regionUrl=void 0,this.regionUrlProvider&&this.regionUrlProvider.notifyDisconnected();try{this.remoteParticipants.forEach(e=>{e.trackPublications.forEach(t=>{e.unpublishTrack(t.trackSid)})}),this.localParticipant.trackPublications.forEach(t=>{var n,r,i;t.track&&this.localParticipant.unpublishTrack(t.track,e),e?((n=t.track)==null||n.detach(),(r=t.track)==null||r.stop()):(i=t.track)==null||i.stopMonitor()}),this.localParticipant.off(X.ParticipantMetadataChanged,this.onLocalParticipantMetadataChanged).off(X.ParticipantNameChanged,this.onLocalParticipantNameChanged).off(X.AttributesChanged,this.onLocalAttributesChanged).off(X.TrackMuted,this.onLocalTrackMuted).off(X.TrackUnmuted,this.onLocalTrackUnmuted).off(X.LocalTrackPublished,this.onLocalTrackPublished).off(X.LocalTrackUnpublished,this.onLocalTrackUnpublished).off(X.ConnectionQualityChanged,this.onLocalConnectionQualityChanged).off(X.MediaDevicesError,this.onMediaDevicesError).off(X.AudioStreamAcquired,this.startAudio).off(X.ChatMessage,this.onLocalChatMessageSent).off(X.ParticipantPermissionsChanged,this.onLocalParticipantPermissionsChanged),this.localParticipant.trackPublications.clear(),this.localParticipant.videoTrackPublications.clear(),this.localParticipant.audioTrackPublications.clear(),this.remoteParticipants.clear(),this.sidToIdentity.clear(),this.activeSpeakers=[],this.audioContext&&typeof this.options.webAudioMix==`boolean`&&(this.audioContext.close(),this.audioContext=void 0),BF()&&(window.removeEventListener(`beforeunload`,this.onPageLeave),window.removeEventListener(`pagehide`,this.onPageLeave),window.removeEventListener(`freeze`,this.onPageLeave),(r=(n=navigator.mediaDevices)?.removeEventListener)==null||r.call(n,`devicechange`,this.handleDeviceChange))}finally{this.setAndEmitConnectionState(gH.Disconnected),this.emit(Y.Disconnected,t)}}}handleParticipantDisconnected(e,t,n){this.remoteParticipants.delete(e),t&&(this.incomingDataStreamManager.validateParticipantHasNoActiveDataStreams(e),this.incomingDataTrackManager.handleRemoteParticipantDisconnected(e),t.trackPublications.forEach(e=>{t.unpublishTrack(e.trackSid,!0)}),this.emit(Y.ParticipantDisconnected,t,n),t.setDisconnected(),this.rpcClientManager.handleParticipantDisconnected(t.identity))}selectDefaultDevices(){return J(this,void 0,void 0,function*(){let e=vL.getInstance().previousDevices,t=yield vL.getInstance().getDevices(void 0,!1),n=cP();if(n?.name===`Chrome`&&n.os!==`iOS`)for(let n of t){let t=e.find(e=>e.deviceId===n.deviceId);t&&t.label!==``&&t.kind===n.kind&&t.label!==n.label&&this.getActiveDevice(n.kind)==="default"&&this.emit(Y.ActiveDeviceChanged,n.kind,n.deviceId)}for(let n of[`audiooutput`,`audioinput`,`videoinput`]){let r=QP(n),i=this.localParticipant.getTrackPublication(r);if(i&&i.track?.isUserProvided)continue;let a=t.filter(e=>e.kind===n),o=this.getActiveDevice(n);if(o===e.filter(e=>e.kind===n)[0]?.deviceId&&a.length>0&&a[0]?.deviceId!==o){yield this.switchActiveDevice(n,a[0].deviceId);continue}n===`audioinput`&&!FF()||n===`videoinput`||a.length>0&&!a.find(e=>e.deviceId===this.getActiveDevice(n))&&(n!==`audiooutput`||!FF())&&(yield this.switchActiveDevice(n,a[0].deviceId))}})}acquireAudioContext(){return J(this,void 0,void 0,function*(){if(typeof this.options.webAudioMix!=`boolean`&&this.options.webAudioMix.audioContext?this.audioContext=this.options.webAudioMix.audioContext:(!this.audioContext||this.audioContext.state===`closed`)&&(this.audioContext=ZP()??void 0),this.options.webAudioMix&&this.remoteParticipants.forEach(e=>e.setAudioContext(this.audioContext)),this.localParticipant.setAudioContext(this.audioContext),this.audioContext&&this.audioContext.state===`suspended`)try{yield Promise.race([this.audioContext.resume(),vF(200)])}catch(e){this.log.warn(`Could not resume audio context`,{error:e})}let e=this.audioContext?.state===`running`;e!==this.canPlaybackAudio&&(this.audioEnabled=e,this.emit(Y.AudioPlaybackStatusChanged,e))})}createParticipant(e,t){let n;return n=t?hH.fromParticipantInfo(this.engine.client,t,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName},this.incomingDataTrackManager):new hH(this.engine.client,``,e,void 0,void 0,void 0,{loggerContextCb:()=>this.logContext,loggerName:this.options.loggerName}),this.options.webAudioMix&&n.setAudioContext(this.audioContext),this.options.audioOutput?.deviceId&&n.setAudioOutput(this.options.audioOutput).catch(e=>this.log.warn(`Could not set audio output: ${e.message}`)),n}getOrCreateParticipant(e,t){if(this.remoteParticipants.has(e)){let n=this.remoteParticipants.get(e);return t&&n.updateInfo(t)&&this.sidToIdentity.set(t.sid,t.identity),n}let n=this.createParticipant(e,t);return this.remoteParticipants.set(e,n),this.sidToIdentity.set(t.sid,t.identity),this.emitWhenConnected(Y.ParticipantConnected,n),n.on(X.TrackPublished,e=>{this.emitWhenConnected(Y.TrackPublished,e,n)}).on(X.TrackSubscribed,(e,t)=>{e.kind===$.Kind.Audio?(e.on(Q.AudioPlaybackStarted,this.handleAudioPlaybackStarted),e.on(Q.AudioPlaybackFailed,this.handleAudioPlaybackFailed)):e.kind===$.Kind.Video&&(e.on(Q.VideoPlaybackFailed,this.handleVideoPlaybackFailed),e.on(Q.VideoPlaybackStarted,this.handleVideoPlaybackStarted)),this.emitWhenConnected(Y.TrackSubscribed,e,t,n)}).on(X.TrackUnpublished,e=>{this.cancelPendingTrackAdded(e.trackSid),this.emit(Y.TrackUnpublished,e,n)}).on(X.TrackUnsubscribed,(e,t)=>{this.emit(Y.TrackUnsubscribed,e,t,n)}).on(X.TrackMuted,e=>{this.emitWhenConnected(Y.TrackMuted,e,n)}).on(X.TrackUnmuted,e=>{this.emitWhenConnected(Y.TrackUnmuted,e,n)}).on(X.ParticipantMetadataChanged,e=>{this.emitWhenConnected(Y.ParticipantMetadataChanged,e,n)}).on(X.ParticipantNameChanged,e=>{this.emitWhenConnected(Y.ParticipantNameChanged,e,n)}).on(X.AttributesChanged,e=>{this.emitWhenConnected(Y.ParticipantAttributesChanged,e,n)}).on(X.ConnectionQualityChanged,e=>{this.emitWhenConnected(Y.ConnectionQualityChanged,e,n)}).on(X.ParticipantPermissionsChanged,e=>{this.emitWhenConnected(Y.ParticipantPermissionsChanged,e,n)}).on(X.TrackSubscriptionStatusChanged,(e,t)=>{this.emitWhenConnected(Y.TrackSubscriptionStatusChanged,e,t,n)}).on(X.TrackSubscriptionFailed,(e,t)=>{this.emit(Y.TrackSubscriptionFailed,e,n,t)}).on(X.TrackSubscriptionPermissionChanged,(e,t)=>{this.emitWhenConnected(Y.TrackSubscriptionPermissionChanged,e,t,n)}).on(X.Active,()=>{this.emitWhenConnected(Y.ParticipantActive,n),n.kind===dA.AGENT&&this.localParticipant.setActiveAgent(n)}),t&&n.updateInfo(t),n}sendSyncState(){let e=Array.from(this.remoteParticipants.values()).reduce((e,t)=>(e.push(...t.getTrackPublications()),e),[]),t=this.localParticipant.getTrackPublications(),n=this.outgoingDataTrackManager.queryPublished();this.engine.sendSyncState(e,t,n)}updateSubscriptions(){for(let e of this.remoteParticipants.values())for(let t of e.videoTrackPublications.values())t.isSubscribed&&bI(t)&&t.emitTrackUpdate()}getRemoteParticipantBySid(e){let t=this.sidToIdentity.get(e);if(t)return this.remoteParticipants.get(t)}getClientInfoCapabilities(e){let t=[];return(ZI(e.frameMetadata??e.packetTrailer)||this.e2eeManager)&&t.push(qA.CAP_PACKET_TRAILER),DI()&&t.push(qA.CAP_COMPRESSION_DEFLATE_RAW),t}registerRpcDataStreamHandler(){this.incomingDataStreamManager.registerTextStreamHandler(JV,(e,t)=>J(this,[e,t],void 0,function(e,t){var n=this;let r=t.identity;return function*(){let t=e.info.attributes??{};yield n.rpcServerManager.handleIncomingDataStream(e,r,t)}()})),this.incomingDataStreamManager.registerTextStreamHandler(YV,(e,t)=>J(this,[e,t],void 0,function(e,t){var n=this;let r=t.identity;return function*(){let t=e.info.attributes??{};yield n.rpcClientManager.handleIncomingDataStream(e,r,t)}()}))}setStatsLogging(e){e?this.statsLogInterval||=kP.setInterval(()=>{this.logWebRTCStats()},vH):this.statsLogInterval&&=(kP.clearInterval(this.statsLogInterval),void 0)}registerConnectionReconcile(){this.clearConnectionReconcile();let e=0;this.connectionReconcileInterval=kP.setInterval(()=>{!this.engine||this.engine.isClosed||!this.engine.verifyTransport()?(e++,this.log.warn(`detected connection state mismatch`,{numFailures:e,engine:this.engine?{closed:this.engine.isClosed,transportsConnectedOrConnecting:this.engine.verifyTransport()}:void 0}),e>=3&&(this.clearConnectionReconcile(),this.engine&&!this.engine.isClosed?(this.log.warn(`detected connection state mismatch, attempting full reconnect`),this.engine.reconnect()):(this.recreateEngine(),this.handleDisconnect(this.options.stopLocalTrackOnUnpublish,tA.STATE_MISMATCH)))):e=0},_H)}clearConnectionReconcile(){this.connectionReconcileInterval&&kP.clearInterval(this.connectionReconcileInterval)}setAndEmitConnectionState(e){return e!==this.state&&(this.log.info(`connection state changed: ${this.state} -> ${e}`),this.state=e,this.incomingDataStreamManager.setConnected(e===gH.Connected),this.setStatsLogging(e===gH.Connected),this.emit(Y.ConnectionStateChanged,this.state),!0)}emitBufferedEvents(){this.bufferedEvents.forEach(e=>{let t=wO(e,2),n=t[0],r=t[1];this.emit(n,...r)}),this.bufferedEvents=[]}emitWhenConnected(e){var t=[...arguments].slice(1);if(this.state===gH.Reconnecting||this.isResuming||!this.engine||this.engine.pendingReconnect)this.bufferedEvents.push([e,t]);else if(this.state===gH.Connected)return this.emit(e,...t);return!1}simulateParticipants(e){return J(this,void 0,void 0,function*(){let t=Object.assign({audio:!0,video:!0,useRealTracks:!1},e.publish),n=Object.assign({count:9,audio:!1,video:!0,aspectRatios:[1.66,1.7,1.3]},e.participants);if(this.handleDisconnect(),this.roomInfo=new oA({sid:`RM_SIMULATED`,name:`simulated-room`,emptyTimeout:0,maxParticipants:0,creationTime:cO.parse(new Date().getTime()),metadata:``,numParticipants:1,numPublishers:1,turnPassword:``,enabledCodecs:[],activeRecording:!1}),this.localParticipant.updateInfo(new lA({identity:`simulated-local`,name:`local-name`})),this.setupLocalParticipantEvents(),this.emit(Y.SignalConnected),this.emit(Y.Connected),this.setAndEmitConnectionState(gH.Connected),t.video){let e=new aH($.Kind.Video,new hA({source:Zk.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Xk.AUDIO,name:`video-dummy`}),new Vz(t.useRealTracks&&window.navigator.mediaDevices?.getUserMedia?(yield window.navigator.mediaDevices.getUserMedia({video:!0})).getVideoTracks()[0]:tI(160*(n.aspectRatios[0]??1),160,!0,!0),void 0,!1,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(X.LocalTrackPublished,e)}if(t.audio){let e=new aH($.Kind.Audio,new hA({source:Zk.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Xk.AUDIO}),new xz(t.useRealTracks&&navigator.mediaDevices?.getUserMedia?(yield navigator.mediaDevices.getUserMedia({audio:!0})).getAudioTracks()[0]:rI(),void 0,!1,this.audioContext,{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext}),{loggerName:this.options.loggerName,loggerContextCb:()=>this.logContext});this.localParticipant.addTrackPublication(e),this.localParticipant.emit(X.LocalTrackPublished,e)}for(let e=0;e<n.count-1;e+=1){let t=new lA({sid:Math.floor(Math.random()*1e4).toString(),identity:`simulated-${e}`,state:uA.ACTIVE,tracks:[],joinedAt:cO.parse(Date.now())}),r=this.getOrCreateParticipant(t.identity,t);if(n.video){let i=tI(160*(n.aspectRatios[e%n.aspectRatios.length]??1),160,!1,!0),a=new hA({source:Zk.CAMERA,sid:Math.floor(Math.random()*1e4).toString(),type:Xk.AUDIO});r.addSubscribedMediaTrack(i,a.sid,new MediaStream([i]),new RTCRtpReceiver),t.tracks=[...t.tracks,a]}if(n.audio){let e=rI(),n=new hA({source:Zk.MICROPHONE,sid:Math.floor(Math.random()*1e4).toString(),type:Xk.AUDIO});r.addSubscribedMediaTrack(e,n.sid,new MediaStream([e]),new RTCRtpReceiver),t.tracks=[...t.tracks,n]}r.updateInfo(t)}})}emit(e){var t=[...arguments].slice(1);if(e!==Y.ActiveSpeakersChanged&&e!==Y.TranscriptionReceived){let n=bH(t).filter(e=>e!==void 0);(e===Y.TrackSubscribed||e===Y.TrackUnsubscribed)&&this.log.trace(`subscribe trace: ${e}`,{event:e,args:n}),this.log.debug(`room event ${e}`,{event:e,args:n})}return super.emit(e,...t)}};yH.cleanupRegistry=typeof FinalizationRegistry<`u`&&typeof WeakRef<`u`&&new FinalizationRegistry(e=>{e()});function bH(e){return e.map(e=>{if(e)return Array.isArray(e)?bH(e):typeof e==`object`?`logContext`in e?e.logContext:void 0:e})}var xH;(function(e){e[e.IDLE=0]=`IDLE`,e[e.RUNNING=1]=`RUNNING`,e[e.SKIPPED=2]=`SKIPPED`,e[e.SUCCESS=3]=`SUCCESS`,e[e.FAILED=4]=`FAILED`})(xH||={}),KM.EventEmitter,KM.EventEmitter,new TextEncoder,new TextDecoder,new TextDecoder(`utf-8`,{fatal:!0});var SH=class extends Error{constructor(e,t){var n;super(e,t),gO(this,`code`,`ERR_JOSE_GENERIC`),this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};gO(SH,`code`,`ERR_JOSE_GENERIC`),gO(class extends SH{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),gO(this,`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),gO(this,`claim`,void 0),gO(this,`reason`,void 0),gO(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_CLAIM_VALIDATION_FAILED`),gO(class extends SH{constructor(e,t){let n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:`unspecified`,r=arguments.length>3&&arguments[3]!==void 0?arguments[3]:`unspecified`;super(e,{cause:{claim:n,reason:r,payload:t}}),gO(this,`code`,`ERR_JWT_EXPIRED`),gO(this,`claim`,void 0),gO(this,`reason`,void 0),gO(this,`payload`,void 0),this.claim=n,this.reason=r,this.payload=t}},`code`,`ERR_JWT_EXPIRED`),gO(class extends SH{constructor(){super(...arguments),gO(this,`code`,`ERR_JOSE_ALG_NOT_ALLOWED`)}},`code`,`ERR_JOSE_ALG_NOT_ALLOWED`),gO(class extends SH{constructor(){super(...arguments),gO(this,`code`,`ERR_JOSE_NOT_SUPPORTED`)}},`code`,`ERR_JOSE_NOT_SUPPORTED`),gO(class extends SH{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`decryption operation failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),gO(this,`code`,`ERR_JWE_DECRYPTION_FAILED`)}},`code`,`ERR_JWE_DECRYPTION_FAILED`),gO(class extends SH{constructor(){super(...arguments),gO(this,`code`,`ERR_JWE_INVALID`)}},`code`,`ERR_JWE_INVALID`),gO(class extends SH{constructor(){super(...arguments),gO(this,`code`,`ERR_JWS_INVALID`)}},`code`,`ERR_JWS_INVALID`),gO(class extends SH{constructor(){super(...arguments),gO(this,`code`,`ERR_JWT_INVALID`)}},`code`,`ERR_JWT_INVALID`),gO(class extends SH{constructor(){super(...arguments),gO(this,`code`,`ERR_JWK_INVALID`)}},`code`,`ERR_JWK_INVALID`),gO(class extends SH{constructor(){super(...arguments),gO(this,`code`,`ERR_JWKS_INVALID`)}},`code`,`ERR_JWKS_INVALID`),gO(class extends SH{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`no applicable key found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),gO(this,`code`,`ERR_JWKS_NO_MATCHING_KEY`)}},`code`,`ERR_JWKS_NO_MATCHING_KEY`),gO(class extends SH{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`multiple matching keys found in the JSON Web Key Set`,t=arguments.length>1?arguments[1]:void 0;super(e,t),gO(this,Symbol.asyncIterator,kO(function*(){})),gO(this,`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`)}},`code`,`ERR_JWKS_MULTIPLE_MATCHING_KEYS`),gO(class extends SH{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`request timed out`,t=arguments.length>1?arguments[1]:void 0;super(e,t),gO(this,`code`,`ERR_JWKS_TIMEOUT`)}},`code`,`ERR_JWKS_TIMEOUT`),gO(class extends SH{constructor(){let e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:`signature verification failed`,t=arguments.length>1?arguments[1]:void 0;super(e,t),gO(this,`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`)}},`code`,`ERR_JWS_SIGNATURE_VERIFICATION_FAILED`);var CH=z({server_url:P(),participant_token:P(),identity:P()});async function wH(e,t,n){return CH.parse(await ca(e,`/v1/calls/${t}/${n}`,{}))}function TH(e){let t=j(),[n,r]=(0,D.useState)(`off`),[i,a]=(0,D.useState)(null),o=(0,D.useRef)(null),s=(0,D.useRef)([]),c=(0,D.useCallback)(async()=>{r(`joining`),a(null);try{let n=await wH(t,e,`listen`),i=new yH;o.current=i,i.on(Y.TrackSubscribed,e=>{if(e.kind!==$.Kind.Audio)return;let t=e.attach();t.muted=!0,t.style.display=`none`,document.body.append(t),s.current.push(t)}),i.on(Y.TrackUnsubscribed,e=>{for(let t of e.detach())t.remove(),s.current=s.current.filter(e=>e!==t)}),i.on(Y.Disconnected,()=>r(`off`)),await i.connect(n.server_url,n.participant_token),r(`muted`)}catch(e){a(e instanceof Error?e.message:String(e)),r(`failed`)}},[e,t]),l=(0,D.useCallback)(e=>{for(let t of s.current)t.muted=!e;r(e?`on`:`muted`)},[]),u=(0,D.useCallback)(async()=>{await o.current?.disconnect(),o.current=null},[]);return(0,D.useEffect)(()=>()=>{o.current?.disconnect()},[]),{listening:n,error:i,join:c,hear:l,leave:u}}var EH=`cold`,DH=class{#e;#t;#n;#r=null;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}get spoken(){return this.#n}async send(e){await ca(this.#e,`/v1/calls/${this.#t}/verbs`,C_.parse(e))}async take(){this.#n&&await(await this.#i()).localParticipant.setMicrophoneEnabled(!0),await this.send({verb:`takeover`})}async give(){await this.send({verb:`release`}),await this.#a()}async leave(){await this.#a(),await this.#r?.disconnect(),this.#r=null}async#i(){if(this.#r!==null)return this.#r;let e=await wH(this.#e,this.#t,`supervise`),t=new yH;return await t.connect(e.server_url,e.participant_token,{autoSubscribe:!1}),this.#r=t,t}async#a(){let e=this.#r?.localParticipant,t=e?.getTrackPublication($.Source.Microphone);e!==void 0&&t?.track!==void 0&&await e.unpublishTrack(t.track,!0)}};function OH(e,t){let n=j(),[r,i]=(0,D.useState)(!1),[a,o]=(0,D.useState)(null),s=(0,D.useRef)(null),c=(0,D.useCallback)(()=>((s.current===null||s.current.spoken!==t)&&(s.current=new DH(n,e,t)),s.current),[e,n,t]),l=(0,D.useCallback)(async(e,t)=>{o(null);try{await e(c()),t!==null&&i(t)}catch(e){o(e instanceof Error?e.message:String(e))}},[c]),u=(0,D.useCallback)(e=>l(t=>t.send({verb:`whisper`,text:e}),null),[l]),d=(0,D.useCallback)(e=>l(t=>t.send({verb:`say`,text:e}),null),[l]),f=(0,D.useCallback)(()=>l(e=>e.take(),!0),[l]),p=(0,D.useCallback)(()=>l(e=>e.give(),!1),[l]),m=(0,D.useCallback)(e=>l(t=>t.send({verb:`transfer`,to:e,mode:EH}),null),[l]),h=(0,D.useCallback)(()=>l(e=>e.send({verb:`end`}),null),[l]);return(0,D.useEffect)(()=>()=>{s.current?.leave(),s.current=null},[]),{whisper:u,say:d,takeOver:f,release:p,transfer:m,end:h,holding:r,error:a}}var kH={whisper:e=>`Whisper to the agent — the caller never ${e?`hears`:`reads`} it`,say:e=>`Say it to the caller, ${e?`in the agent's voice`:`as the agent`}, verbatim`};function AH({call:e,live:t,spoken:n}){let r=TH(e),i=OH(e,n),a=(0,D.useRef)(!1);(0,D.useEffect)(()=>{t&&n&&!a.current&&(a.current=!0,r.join())},[t,n,r]);let o=r.error??i.error;return(0,A.jsxs)(`div`,{className:`lv-desk`,role:`group`,"aria-label":`the supervisor's desk`,children:[n&&(0,A.jsx)(MH,{ear:r,live:t}),t?(0,A.jsx)(NH,{desk:i,spoken:n}):(0,A.jsx)(`span`,{className:`lv-desk-note`,children:n?`The call is over: nothing is left to supervise. Read its log below, or play its recording.`:`The conversation is over: nothing is left to supervise. Read it below.`}),o!==null&&(0,A.jsx)(`span`,{className:`lv-desk-refused`,children:o})]})}function jH({verb:e,asks:t,send:n,loud:r=!1}){let[i,a]=(0,D.useState)(``),o=()=>{i.trim()!==``&&(n(i),a(``))};return(0,A.jsxs)(`div`,{className:`lv-desk-say`,children:[(0,A.jsx)(G,{size:`sm`,className:`lv-desk-text`,value:i,placeholder:t,"aria-label":t,onChange:e=>a(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o()}}),(0,A.jsx)(W,{size:`sm`,kind:r?`primary`:void 0,disabled:i.trim()===``,onClick:o,children:e})]})}function MH({ear:e,live:t}){if(!t)return null;switch(e.listening){case`off`:case`failed`:return(0,A.jsxs)(W,{size:`sm`,pill:!0,onClick:()=>void e.join(),children:[(0,A.jsx)(`span`,{className:`lv-desk-dot`}),`Listen`]});case`joining`:return(0,A.jsxs)(W,{size:`sm`,pill:!0,disabled:!0,children:[(0,A.jsx)(`span`,{className:`lv-desk-dot lv-desk-dot-warm`}),`Joining…`]});case`muted`:return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(W,{size:`sm`,pill:!0,onClick:()=>e.hear(!0),children:[(0,A.jsx)(`span`,{className:`lv-desk-dot lv-desk-dot-warm`}),`Hear it`]}),(0,A.jsx)(W,{size:`sm`,pill:!0,onClick:()=>void e.leave(),children:`Stop`})]});case`on`:return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(W,{size:`sm`,pill:!0,onClick:()=>e.hear(!1),children:[(0,A.jsx)(`span`,{className:`lv-desk-dot lv-desk-dot-on`}),`Listening · mute`]}),(0,A.jsx)(W,{size:`sm`,pill:!0,onClick:()=>void e.leave(),children:`Stop`})]})}}function NH({desk:e,spoken:t}){let[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(!1),o=()=>{n!==null&&n.trim()!==``&&(e.transfer(n.trim()),r(null))};return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jH,{verb:`Whisper`,asks:kH.whisper(t),send:t=>e.whisper(t)}),(0,A.jsx)(jH,{verb:`Say`,asks:kH.say(t),send:t=>e.say(t),loud:!0}),(0,A.jsx)(W,{size:`sm`,className:e.holding?`lv-desk-holding`:void 0,title:e.holding?t?`the agent hears and speaks again, and your microphone stops`:`the agent answers again`:t?`your microphone takes the line: the agent stops speaking`:`you answer from here with Say: the agent writes nothing more`,onClick:()=>void(e.holding?e.release():e.takeOver()),children:e.holding?`Hand back`:t?`Take the line`:`Take the thread`}),t?n===null?(0,A.jsx)(W,{size:`sm`,onClick:()=>r(``),children:`Transfer`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(G,{size:`sm`,className:`lv-desk-number`,autoFocus:!0,value:n,placeholder:`+34… then Enter`,onChange:e=>r(e.target.value),onKeyDown:e=>{e.key===`Enter`&&o(),e.key===`Escape`&&r(null)}}),(0,A.jsx)(W,{size:`sm`,disabled:n.trim()===``,onClick:o,children:`Transfer`}),(0,A.jsx)(W,{size:`sm`,onClick:()=>r(null),children:`Cancel`})]}):null,(0,A.jsx)(W,{size:`sm`,kind:`danger`,className:i?`lv-desk-armed`:void 0,onClick:()=>{i&&e.end(),a(!i)},onBlur:()=>a(!1),children:i?`End · sure?`:t?`End call`:`End thread`})]})}var PH=new Set([`tag`,`name`,`id`,`flag`]);function FH({rows:e}){return(0,A.jsx)(`div`,{className:`lv-readings`,children:e.map(e=>(0,A.jsxs)(`div`,{className:`lv-reading`,children:[(0,A.jsx)(`span`,{className:`lv-reading-name`,children:e.field}),(0,A.jsxs)(`span`,{className:`lv-reading-value`,title:String(e.value),children:[IH(String(e.value)),e.unit!==null&&!PH.has(e.unit)&&(0,A.jsxs)(`span`,{className:`lv-seen`,children:[` `,e.unit]})]})]},e.field))})}function IH(e){return/^-?\d+\.\d{4,}$/.test(e)?Number(e).toFixed(3):e}function LH({metrics:e,entries:t}){let n=Dw(t),r=Math.max(...n.map(e=>e.seconds),0),i=xw();return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(nh,{ruled:!0,children:`Metrics`}),(0,A.jsxs)(`div`,{className:`lv-pane-body`,children:[n.length===0&&(0,A.jsx)(`div`,{className:`lv-sub`,children:`Nothing measured yet: the first turn fills this in.`}),n.map(e=>(0,A.jsxs)(`div`,{className:`lv-meter`,title:`median over ${String(e.turns)} turns`,children:[(0,A.jsx)(`span`,{className:`lv-meter-name`,children:e.name}),(0,A.jsx)(Eh,{share:r===0?0:e.seconds/r}),(0,A.jsx)(`span`,{className:`lv-meter-value`,children:Sw(e.seconds)})]},e.name)),Object.entries(e).map(([e,t])=>(0,A.jsx)(RH,{kind:e,blocks:t,shape:i.get(e)},e))]})]})}function RH({kind:e,blocks:t,shape:n}){return t.length===0?null:(0,A.jsxs)(`details`,{className:`lv-blocks`,children:[(0,A.jsxs)(`summary`,{children:[`metrics.`,e,` · `,t.length]}),t.map((t,r)=>(0,A.jsx)(FH,{rows:bw(t,n)},`${e}-${String(r)}`))]})}function zH({prompt:e,cost:t}){let n=Object.entries(e);return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(nh,{ruled:!0,children:`Prompt`}),(0,A.jsxs)(`div`,{className:`lv-pane-body lv-pane-body-tight`,children:[n.length===0&&(0,A.jsx)(`div`,{className:`lv-sub`,children:`The app has written no block yet.`}),n.map(([e,t])=>(0,A.jsxs)(`div`,{className:`lv-prompt-row`,children:[(0,A.jsx)(`span`,{className:`lv-prompt-name`,children:e}),(0,A.jsx)(`span`,{className:`lv-prompt-hash`,title:t.hash,children:t.hash.slice(0,8)}),(0,A.jsxs)(`span`,{className:`lv-prompt-chars`,children:[t.chars.toLocaleString(`en`).replace(/,/g,` `),` chars`]})]},e)),t!==null&&(0,A.jsx)(rh,{label:`cost so far`,children:hg(t.eur)})]})]})}function BH({room:e,from:t,over:n}){return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(nh,{ruled:!0,children:`Room`}),e===null?(0,A.jsx)(`div`,{className:`lv-pane-text`,children:`No room: this session carries no media.`}):(0,A.jsxs)(`div`,{className:`lv-pane-text`,children:[n?`Audio room closed`:`Audio room open`,` · `,e.participants.length,` `,e.participants.length===1?`participant`:`participants`,t!==null&&(0,A.jsxs)(A.Fragment,{children:[` · rang from `,t]}),(0,A.jsx)(`ul`,{className:`lv-people`,children:e.participants.map(e=>(0,A.jsx)(`li`,{className:`lv-person`,children:(0,A.jsxs)(`details`,{children:[(0,A.jsxs)(`summary`,{children:[(0,A.jsx)(bh,{tone:e.speaking?`green`:void 0,small:!0}),(0,A.jsx)(`span`,{children:e.name??e.identity}),(0,A.jsx)(`span`,{className:`lv-person-kind`,children:e.kind})]}),(0,A.jsx)(`pre`,{className:`lv-data`,children:JSON.stringify(e.attributes,null,2)})]})},e.identity))})]})]})}var VH=`***`,HH=`tenant`;function UH({fields:e,declared:t}){let n=Object.keys(e).sort();return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(nh,{children:`State`}),n.length===0?(0,A.jsx)(`div`,{className:`lv-pane-text`,children:`The app has declared no state yet.`}):(0,A.jsx)(`div`,{className:`lv-pane-body`,children:n.map(n=>{let r=WH(e[n],t[n]);return(0,A.jsxs)(rh,{label:n,children:[GH(e[n]),r!==HH&&(0,A.jsx)(`span`,{className:r===`pii`?`lv-seen lv-seen-pii`:`lv-seen`,children:r})]},n)})})]})}function WH(e,t){return e===VH?`pii`:t===`public`?`public`:HH}function GH(e){return typeof e==`string`?e:JSON.stringify(e)}function KH({seq:e,kind:t,tone:n,who:r,said:i,note:a=[],children:o}){let s=a.filter(e=>e!=null&&e!==``),c=(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`lv-seq`,children:e}),(0,A.jsx)(`span`,{className:`lv-kind lv-kind-${n}`,children:t}),(0,A.jsxs)(`span`,{className:n===`turn`?`lv-text lv-text-turn`:n===`quiet`?`lv-text lv-text-quiet`:`lv-text`,children:[r!==void 0&&(0,A.jsx)(`span`,{className:r===`agent`?`lv-who lv-who-agent`:`lv-who`,children:r}),i,s.length>0&&(0,A.jsx)(`span`,{className:`lv-note`,children:s.map((e,t)=>(0,A.jsxs)(`span`,{children:[t>0&&` · `,e]},t))})]})]}),l=`lv-row lv-${n}`;return o==null||o===!1?(0,A.jsx)(`div`,{className:l,children:(0,A.jsx)(`div`,{className:`lv-line`,children:c})}):(0,A.jsxs)(`details`,{className:l,children:[(0,A.jsx)(`summary`,{className:`lv-line`,children:c}),(0,A.jsx)(`div`,{className:`lv-more`,children:o})]})}function qH(e){return e.ops.map(ZH).join(`; `)}function JH(e){return e.ops.flatMap(e=>e.facts.map(e=>e.category?`${e.text} (${e.category})`:e.text))}function YH(e){return`${e.sources.length} sources · ${QH(e.took_ms)}`}function XH(e){return e.sources.map(e=>`${e.heading?`${e.path} › ${e.heading}`:e.path} · ${e.score.toFixed(3)}`)}function ZH(e){return`${e.op} · ${e.facts.length} facts · ${QH(e.took_ms)}`}function QH(e){return`${Math.round(e)} ms`}function $H({ops:e,seq:t}){return(0,A.jsx)(tU,{kind:`memory`,said:qH(e),lines:JH(e),seq:t})}function eU({sources:e,seq:t}){return(0,A.jsx)(tU,{kind:`sources`,said:YH(e),lines:XH(e),seq:t})}function tU({kind:e,said:t,lines:n,seq:r}){return(0,A.jsx)(KH,{seq:r,kind:e,tone:`lookup`,said:t,children:(0,A.jsx)(`ul`,{className:`lv-list`,children:n.map(e=>(0,A.jsx)(`li`,{children:e},e))})})}function nU({changed:e,cause:t,seq:n}){return(0,A.jsx)(KH,{seq:n,kind:`state`,tone:`state`,said:`${e.join(`, `)} ← ${sU(t)}`})}function rU({mark:e,seq:t}){return(0,A.jsx)(KH,{seq:t,kind:`supervisor`,tone:`supervisor`,said:e.said,note:[e.by]})}function iU({confirm:e,seq:t}){let n=[{field:`tool`,value:e.tool,unit:null},{field:`audience`,value:e.audience,unit:null},...e.said==null?[]:[{field:`said`,value:e.said,unit:null}],...e.reason==null?[]:[{field:`reason`,value:e.reason,unit:null}]];return(0,A.jsx)(KH,{seq:t,kind:`confirm`,tone:`confirm`,said:e.phrase,note:[e.status],children:(0,A.jsx)(FH,{rows:n})})}function aU({name:e,source:t,data:n,seq:r}){return(0,A.jsx)(KH,{seq:r,kind:`event`,tone:`event`,said:e,note:[t],children:(0,A.jsx)(`pre`,{className:`lv-data`,children:JSON.stringify(n,null,2)})})}function oU({entries:e}){return(0,A.jsx)(KH,{seq:e[0]?.seq,kind:`quiet`,tone:`quiet`,said:e.length===1?`1 entry`:`${e.length} entries`,children:(0,A.jsx)(`ul`,{className:`lv-list`,children:e.map(e=>(0,A.jsxs)(`li`,{children:[e.seq,` `,e.type]},`${String(e.seq)}-${e.type}`))})})}function sU(e){return e===null?`the app`:e.kind===`tool`?e.tool:`${e.name} (seq ${String(e.seq)})`}function cU({run:e,seq:t}){let n=[{field:`arguments`,value:JSON.stringify(e.arguments,null,2),unit:null},...lU(e.output)?[{field:`output`,value:JSON.stringify(e.output,null,2),unit:null}]:[],...lU(e.error)?[{field:`error`,value:e.error,unit:null}]:[],...lU(e.duration_s)?[{field:`duration_s`,value:Sw(e.duration_s),unit:null}]:[]];return(0,A.jsx)(KH,{seq:t,kind:`tool`,tone:`tool`,said:`${e.name}(${uU(e)})`,note:[(0,A.jsx)(`span`,{className:e.status===`failed`?`lv-failed`:``,children:dU(e)})],children:(0,A.jsx)(FH,{rows:n})})}function lU(e){return e!=null}function uU(e){return Object.entries(e.arguments).map(([e,t])=>`${e}=${fU(t)}`).join(`, `)}function dU(e){return e.status===`running`?`…`:e.error??e.summary??fU(e.output)}function fU(e){let t=typeof e==`string`?e:JSON.stringify(e);return t===void 0?``:t.slice(0,60)}var pU={transcription_delay:`stt`,end_of_turn_delay:`eot`,llm_node_ttft:`ttft`,tts_node_ttfb:`ttfb`,e2e_latency:`e2e`};function mU({turn:e,seq:t,metrics:n}){let r=Tw(n,e.speech_id),i=yw(e).map(e=>`${pU[e.field]??e.field} ${e.value}`),a=[...e.role===`agent`&&e.interrupted?[`interrupted`]:[],...e.role===`user`&&e.language!==void 0&&e.language!==null?[e.language]:[]],o=e.role===`user`?[...i,e.speech_id,...a]:[...i,...a];return(0,A.jsx)(KH,{seq:t,kind:`turn`,tone:`turn`,who:e.role===`agent`?`agent`:`caller`,said:e.text,note:o,children:r.length===0?null:r.map((e,t)=>(0,A.jsxs)(`section`,{children:[(0,A.jsxs)(`h4`,{className:`lv-block-name`,children:[`metrics.`,e.kind]}),(0,A.jsx)(FH,{rows:e.readings})]},`${e.kind}-${String(t)}`))})}var hU=80;function gU({entries:e,state:t,after:n}){let r=t.live.agent,i=(0,D.useRef)(null),a=(0,D.useRef)(!0);return(0,D.useEffect)(()=>{let e=i.current;e!==null&&a.current&&(e.scrollTop=e.scrollHeight)},[e,t.live.user,r]),(0,A.jsxs)(`div`,{className:`lv-rows`,ref:i,onScroll:e=>{let t=e.currentTarget;a.current=t.scrollHeight-t.scrollTop-t.clientHeight<hU},children:[Yw(e,t).map(e=>(0,A.jsx)(_U,{row:e,state:t},`${e.kind}-${String(e.seq)}`)),(0,A.jsx)(vU,{said:t.live.user,who:`caller`}),(0,A.jsx)(vU,{said:r,who:`agent`}),n]})}function _U({row:e,state:t}){switch(e.kind){case`turn`:return(0,A.jsx)(mU,{turn:e.turn,seq:e.seq,metrics:t.metrics});case`tool`:return(0,A.jsx)(cU,{run:e.run,seq:e.seq});case`state`:return(0,A.jsx)(nU,{changed:e.changed,cause:e.cause,seq:e.seq});case`confirm`:return(0,A.jsx)(iU,{confirm:e.confirm,seq:e.seq});case`event`:return(0,A.jsx)(aU,{name:e.name,source:e.source,data:e.data,seq:e.seq});case`supervisor`:return(0,A.jsx)(rU,{mark:e.mark,seq:e.seq});case`memory`:return(0,A.jsx)($H,{ops:e.ops,seq:e.seq});case`sources`:return(0,A.jsx)(eU,{sources:e.sources,seq:e.seq});case`quiet`:return(0,A.jsx)(oU,{entries:e.entries})}}function vU({said:e,who:t}){if(e===null)return null;let n=e.split(/\s+/).filter(e=>e!==``);return(0,A.jsx)(`div`,{className:`lv-saying`,children:(0,A.jsx)(KH,{seq:void 0,kind:`turn`,tone:`turn`,who:t,said:(0,A.jsxs)(A.Fragment,{children:[n.map((e,t)=>(0,A.jsxs)(`span`,{className:t===n.length-1?`lv-word lv-word-now`:`lv-word`,children:[e,` `]},t)),(0,A.jsx)(`span`,{className:`lv-caret`,"aria-hidden":!0})]})})})}function yU({call:e,agent:t}){let n=Fw(e),r=n.state,i=SD(r.agent),a=Kh(),[o,s]=(0,D.useState)(!1),c=r.status===`ended`,l=CD(CU(n.entries)),u=r.room!==null,d=a===null||a.includes(`supervise`),f=Rh({name:`live.call`,initial:360,min:280,max:640,side:`right`});return(0,D.useEffect)(()=>s(!1),[e]),(0,A.jsxs)(`div`,{className:`lv`,style:f.style,children:[f.handle,(0,A.jsxs)(`div`,{className:`lv-middle`,children:[(0,A.jsxs)(bU,{call:e,agent:t,state:r,connection:n.error??n.connection,failed:n.error!==null,children:[(0,A.jsx)(k,{to:`/sessions/${e}`,className:`lv-session`,children:`Open session`}),d&&(0,A.jsxs)(`button`,{type:`button`,className:o?`lv-listen lv-listen-open`:`lv-listen`,disabled:c&&!o,title:c?`the call is over`:void 0,onClick:()=>s(!o),"aria-expanded":o,children:[(0,A.jsx)(`span`,{className:c?`ui-dot ui-dot-small`:`ui-dot ui-dot-small ui-dot-green`}),o?`Close the desk`:u?`Listen in`:`Open the desk`]})]}),o&&(0,A.jsx)(AH,{call:e,live:!c,spoken:u}),(0,A.jsx)(gU,{entries:n.entries,state:r,after:l===null?void 0:(0,A.jsx)(wU,{call:e})})]}),(0,A.jsxs)(`aside`,{className:`lv-pane`,"aria-label":`what the call holds`,children:[(0,A.jsx)(UH,{fields:r.app_state,declared:i}),(0,A.jsx)(BH,{room:r.room,from:r.from,over:c}),(0,A.jsx)(zH,{prompt:r.prompt,cost:r.cost}),(0,A.jsx)(LH,{metrics:r.metrics,entries:n.entries})]})]})}function bU({call:e,agent:t,state:n,connection:r,failed:i,children:a}){let o=SU(n.status!==`ended`),s=n.status===`ended`,c=n.caller?.name??xU(n.direction===`outbound`?n.to:n.from);return(0,A.jsxs)(`div`,{className:`lv-head`,children:[(0,A.jsx)(`span`,{className:`lv-call`,children:e}),n.channel!==null&&(0,A.jsx)(`span`,{className:`lv-tag`,children:n.channel}),n.direction!==null&&(0,A.jsx)(`span`,{className:`lv-tag`,children:n.direction}),(0,A.jsx)(`span`,{className:s?`lv-status lv-status-over`:`lv-status`,children:s?(n.end_reason??`ended`).replace(/_/g,` `):n.status===`active`?`on a call · ${mg(n.started_at,o)}`:n.status}),(0,A.jsxs)(`span`,{className:`lv-sub`,children:[c,` → `,n.agent||t||`—`,` · seq `,n.seq,n.agent_state!==null&&` · agent ${n.agent_state}`,n.user_state!==null&&` · caller ${n.user_state}`,` · `,(0,A.jsx)(`span`,{className:i?`lv-connection-bad`:void 0,children:r})]}),a]})}function xU(e){return e===null?`—`:e.startsWith(`+`)?Eg(e):e}function SU(e){let[t,n]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>n(Date.now()/1e3),1e3);return()=>window.clearInterval(t)},[e]),t}function CU(e){return[...e].reverse().find(e=>e.type===`call.summary`)?.data}function wU({call:e}){let[t,n]=(0,D.useState)(!1),r=(0,D.useCallback)(()=>n(!0),[]);return t?null:(0,A.jsx)(`div`,{className:`lv-recording`,children:(0,A.jsx)(TD,{call:e,onNothing:r})})}var TU=uy.loose(),EU=50,DU=250;function OU(e,t,n,r){let i=j(),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(!1);return(0,D.useEffect)(()=>{if(s)return;let r=!1,a=window.setTimeout(()=>{(async()=>{let a=e===``?`/v1/sessions`:`/v1/agents/${encodeURIComponent(e)}/sessions`,s={limit:EU};t.query.trim()!==``&&(s.q=t.query.trim()),t.agent!==``&&(s.agent=t.agent),t.channel!==``&&(s.channel=t.channel);try{let e=[],t=0,l=null;for(let o=0;o<n&&!(o>0&&l===null);o+=1){let n=await oa(i,a,l===null?s:{...s,before:l});if(r)return;if(typeof n.total!=`number`){c(!0);return}let o=Array.isArray(n.calls)?n.calls:[];e.push(...o.map(e=>TU.parse(e))),t=n.total,l=typeof n.next==`string`?n.next:null}o({rows:e,total:t,next:l})}catch{r||c(!0)}})()},DU);return()=>{r=!0,window.clearTimeout(a)}},[i,e,t.query,t.agent,t.channel,n,s,r]),s?null:a}function kU(e,t){let n=t.trim().toLowerCase();if(n===``)return!0;let r=n.replace(/[^\d]/g,``);if([e.call,e.agent,e.from,e.to,e.caller?.name,e.outcome,e.channel].filter(Boolean).join(` `).toLowerCase().includes(n))return!0;if(r.length>=3){let t=`${e.from??``} ${e.to??``} ${e.call}`.replace(/[^\d ]/g,``);return t.replace(/ /g,``).includes(r)||t.includes(r)}return!1}var AU=80;function jU(){let{lines:e,floorError:t}=wb(),n=Sr().call,[r,i]=Yi(),a=r.get(`agent`),[o,s]=(0,D.useState)(``),c=Rh({name:`live.calls`,initial:300,min:220,max:520,side:`left`}),l=NU(),u=e.filter(e=>(a===null||e.agent===a)&&kU(e,o)),d=u.filter(mC),f=u.filter(e=>!mC(e)).slice(0,AU),p=[...d,...f],m=n??d[0]?.call??p[0]?.call,h=a===null?``:`?agent=${encodeURIComponent(a)}`;return(0,A.jsxs)(`div`,{className:`fl`,style:c.style,children:[c.handle,(0,A.jsxs)(`nav`,{className:`fl-side`,"aria-label":`the floor's calls`,children:[(0,A.jsxs)(`div`,{className:`fl-side-head`,children:[(0,A.jsxs)(`div`,{className:`fl-standing`,children:[(0,A.jsx)(bh,{tone:d.length>0?`green`:void 0}),(0,A.jsx)(`span`,{className:`fl-count`,children:d.length===1?`1 call up`:`${d.length} calls up`}),(0,A.jsxs)(`span`,{className:`fl-asked`,title:`re-asked every ${fC/1e3} s`,children:[u.length,` listed`]})]}),(0,A.jsx)(G,{size:`sm`,className:`fl-search`,placeholder:`Search a number, agent or outcome`,"aria-label":`Search the floor's calls`,value:o,onChange:e=>s(e.target.value)}),a!==null&&(0,A.jsxs)(`div`,{className:`fl-only`,children:[(0,A.jsx)(`span`,{className:`ui-clip`,children:a}),(0,A.jsx)(`button`,{type:`button`,className:`fl-only-clear`,onClick:()=>{r.delete(`agent`),i(r)},children:`every agent`})]})]}),(0,A.jsxs)(`div`,{className:`fl-list`,children:[t!==null&&(0,A.jsx)(`p`,{className:`fl-empty fl-refused`,children:t}),p.length===0&&t===null&&(0,A.jsx)(`p`,{className:`fl-empty`,children:o===``?`No calls yet. Leave this open — a call that reaches any agent shows up here as it rings.`:`No call here matches.`}),d.length>0&&(0,A.jsx)(`div`,{className:`fl-label`,children:`On a call now`}),d.map(e=>(0,A.jsx)(MU,{line:e,on:e.call===m,now:l,to:`/live/${e.call}${h}`},e.call)),f.length>0&&(0,A.jsx)(`div`,{className:`fl-label`,children:`Recent`}),f.map(e=>(0,A.jsx)(MU,{line:e,on:e.call===m,now:l,to:`/live/${e.call}${h}`},e.call)),f.length>0&&(0,A.jsx)(k,{to:`/sessions`,className:`fl-all`,children:`Every session →`})]})]}),m===void 0?(0,A.jsx)(`div`,{className:`fl-nothing`,children:`Nothing to watch yet: the first call the org takes appears on the left, and opens here.`}):(0,A.jsx)(yU,{call:m,agent:p.find(e=>e.call===m)?.agent},m)]})}function MU({line:e,on:t,now:n,to:r}){let i=mC(e);return(0,A.jsxs)(k,{to:r,className:t?`fl-row fl-row-on`:`fl-row`,title:e.call,children:[(0,A.jsx)(`span`,{className:i?`fl-dot fl-dot-live`:`fl-dot`}),(0,A.jsxs)(`span`,{className:`fl-row-words`,children:[(0,A.jsxs)(`span`,{className:`fl-row-top`,children:[(0,A.jsx)(`span`,{className:`fl-id`,children:Dg(e)}),(0,A.jsx)(`span`,{className:i?`fl-meta fl-meta-live`:`fl-meta`,children:i?e.status===`active`?mg(e.started_at,n):e.status:bg(e.started_at,n)})]}),(0,A.jsxs)(`span`,{className:`fl-row-sub`,children:[(0,A.jsxs)(`span`,{className:`ui-clip`,children:[e.agent,e.channel!==null&&` · ${e.channel}`,e.direction===`outbound`&&` · outbound`,!i&&` · ${pg(e)}`]}),e.score!=null&&(0,A.jsx)(`span`,{className:`fl-score`,children:(0,A.jsxs)(vh,{tone:e.score.passed?`green`:`red`,children:[e.score.held,`/`,e.score.judged]})}),e.score==null&&(e.flags??[]).includes(`escalated`)&&(0,A.jsx)(`span`,{className:`fl-score`,children:(0,A.jsx)(vh,{tone:`amber`,children:`escalated`})})]}),!i&&e.outcome!==null&&(0,A.jsx)(`span`,{className:`fl-outcome`,children:e.outcome})]})]})}function NU(){let[e,t]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{let e=window.setInterval(()=>t(Date.now()/1e3),1e3);return()=>window.clearInterval(e)},[]),e}var PU=/^call[_-][\w+-]{6,}$/,FU=`minmax(0,1.3fr) 128px 84px 78px 74px minmax(0,1.5fr)`,IU=`minmax(0,1.3fr) 84px 78px 74px minmax(0,1.6fr)`,LU=[`web`,`phone`,`whatsapp`];function RU({lines:e,error:t,agent:n,agents:r}){let i=vr(),[a,o]=(0,D.useState)({query:``,agent:``,channel:``}),[s,c]=(0,D.useState)(1),l=OU(n,a,s,`${e.length}:${e[0]?.call??``}:${e.filter(mC).length}`),u=n===``,d=l===null?e.filter(e=>kU(e,a.query)&&(a.agent===``||e.agent===a.agent)&&(a.channel===``||e.channel===a.channel)):l.rows,f=[...d.filter(mC),...d.filter(e=>!mC(e))],p=e=>u?`/sessions/${e}`:`/a/${n}/sessions/${e}`,m=e=>{let t=a.query.trim();e.key===`Enter`&&PU.test(t)&&i(p(t))},h=u?FU:IU,g=a.query!==``||a.agent!==``||a.channel!==``;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`sessions-filters`,children:[(0,A.jsx)(G,{size:`sm`,className:`sessions-search`,placeholder:`Search a session id, number or outcome`,"aria-label":`Search a session id, number or outcome`,value:a.query,onChange:e=>o({...a,query:e.target.value}),onKeyDown:m}),u&&(0,A.jsxs)(ch,{size:`sm`,className:`sessions-select`,"aria-label":`Filter by agent`,value:a.agent,onChange:e=>o({...a,agent:e.target.value}),children:[(0,A.jsx)(`option`,{value:``,children:`Every agent`}),r.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]}),u&&(0,A.jsxs)(ch,{size:`sm`,className:`sessions-select`,"aria-label":`Filter by channel`,value:a.channel,onChange:e=>o({...a,channel:e.target.value}),children:[(0,A.jsx)(`option`,{value:``,children:`Every channel`}),LU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]})]}),(0,A.jsx)($m,{children:t}),(0,A.jsxs)(H,{children:[f.length===0?(0,A.jsx)(Qm,{children:g?PU.test(a.query.trim())?(0,A.jsxs)(A.Fragment,{children:[`Not on this page — press Enter to open `,a.query.trim(),` by its id.`]}):(0,A.jsx)(A.Fragment,{children:`No session here matches. The search reads the sessions this page has listed.`}):(0,A.jsxs)(A.Fragment,{children:[`No session recorded yet. The log is written during the call, so one appears here the moment it starts — from the browser, from`,` `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall chat`}),`, or from the telephone.`]})}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:h,labels:u?[`Session`,`Agent`,`Channel`,`Time (UTC)`,`Duration`,`Outcome`]:[`Session`,`Channel`,`Time (UTC)`,`Duration`,`Outcome`]}),VU(f).map(e=>(0,A.jsxs)(D.Fragment,{children:[(0,A.jsxs)(`div`,{className:`sessions-day`,children:[(0,A.jsx)(`span`,{className:`sessions-day-name`,children:e.label}),(0,A.jsxs)(`span`,{className:`sessions-day-count`,children:[e.lines.length,` `,e.lines.length===1?`session`:`sessions`]})]}),e.lines.map(e=>(0,A.jsxs)(Mh,{columns:h,to:p(e.call),children:[(0,A.jsxs)(`div`,{className:`sessions-id`,children:[(0,A.jsxs)(`div`,{className:`sessions-call`,children:[mC(e)&&(0,A.jsx)(bh,{tone:`green`,small:!0}),(0,A.jsx)(`span`,{className:`ui-clip`,children:e.call})]}),(0,A.jsx)(`div`,{className:`sessions-from ui-clip`,children:Dg(e)})]}),u&&(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.agent}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.channel??`—`}),(0,A.jsx)(`span`,{className:`ui-cell`,children:_g(e.started_at)}),(0,A.jsx)(`span`,{className:`ui-cell`,children:mC(e)?(0,A.jsx)(`span`,{className:`sessions-live`,children:`live`}):pg(e)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.outcome??zU(e)})]},e.call))]},e.key))]}),l!==null&&l.total>l.rows.length&&(0,A.jsxs)(Zm,{children:[(0,A.jsxs)(`span`,{children:[l.rows.length,` of `,l.total]}),(0,A.jsx)(`span`,{className:`sessions-more`,children:(0,A.jsx)(W,{size:`sm`,onClick:()=>c(s+1),children:`Load more`})})]})]})]})}function zU(e){return mC(e)?`on a call`:e.end_reason===null?`—`:e.end_reason.replace(/_/g,` `)}var BU=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`];function VU(e){let{today:t,yesterday:n}=Sg(),r=[];for(let i of e){let e=mC(i)?`live`:i.started_at===null?`unknown`:xg(i.started_at),a=r.find(t=>t.key===e);a===void 0&&(a={key:e,label:HU(e,i.started_at,t,n),lines:[]},r.push(a)),a.lines.push(i)}return r}function HU(e,t,n,r){return e===`live`?`On a call now`:e===`unknown`||t===null?`Not started`:e===n?`Today`:e===r?`Yesterday`:`${BU[new Date(t*1e3).getUTCDay()]} ${yg(t)}`}function UU(){let{lines:e,floorError:t,agents:n}=wb(),r=[...new Set([...n.map(e=>e.slug),...e.map(e=>e.agent)])].sort();return(0,A.jsxs)(Dh,{tight:!0,children:[(0,A.jsx)(Oh,{title:`Sessions`,lede:`Every conversation the org has had, newest first, whichever agent handled it.`}),(0,A.jsx)(RU,{lines:e,error:t,agent:``,agents:r})]})}var WU=[`qa`,`supervisor`,`manager`,`admin`,`developer`],GU=z({id:P(),email:P(),name:P(),role:V(WU),agents:R(P()),status:V([`invited`,`active`,`disabled`]),scopes:R(P()),production:L()}),KU=z({member:GU,token:P(),expires_at:P()});async function qU(e){return z({members:R(GU)}).parse(await oa(e,`/v1/members`)).members}async function JU(e,t){return KU.parse(await ca(e,`/v1/members`,t))}async function YU(e,t){return KU.parse(await ca(e,`/v1/members/${encodeURIComponent(t)}/reset`,{}))}async function XU(e,t){await la(e,`/v1/members/${encodeURIComponent(t)}`)}async function ZU(e,t,n){let r=await fetch(new URL(`${e.base.replace(/\/$/,``)}/v1/members/${encodeURIComponent(t)}`,window.location.origin),{method:`PATCH`,headers:{...ra(e),"content-type":`application/json`},body:JSON.stringify(n)});return GU.parse(await pa(r))}var QU=z({configured:L(),issuer:P().nullish(),client_id:P().nullish(),domains:R(P()),role:P().nullish(),required:L(),redirect_uri:P()});async function $U(e){try{return QU.parse(await oa(e,`/v1/org/sso`))}catch(e){if(e instanceof ta&&(e.status===404||e.status===405))return null;throw e}}async function eW(e,t){return QU.parse(await sa(e,`/v1/org/sso`,t))}async function tW(e){await la(e,`/v1/org/sso`)}var nW=z({on:L(),ceiling_eur:F().nullable()});function rW(){let e=j(),t=Kh(),[n,r]=(0,D.useState)(null),i=Bm(Im,`numbers`)&&t!==null&&Eb(t,`numbers`),a=Bm(Im,`team`)&&t!==null&&Eb(t,`team`),[o,s]=(0,D.useState)(0);return(0,D.useEffect)(()=>{if(t===null)return;let n=!1;return(async()=>{let o=[];if(i){let[t,n]=await Promise.all([Ub(e).catch(()=>null),Hb(e).catch(()=>[])]);o.push({done:t!==null,name:`Connect a phone carrier`,action:`Connect`,to:`/numbers`});let r=n.filter(e=>e.route.number!==null).length;o.push({done:r>0,name:r>1?`Point ${r} numbers at an agent`:`Point a number at an agent`,action:`Add`,to:`/numbers`})}let c=await oa(e,`/v1/org/judging`).then(e=>nW.parse(e),()=>null);if(c!==null&&t!==null&&t.includes(`usage`)&&o.push({done:c.on,name:`Add a judge so calls get scored`,action:`Turn on`,run:async()=>{await sa(e,`/v1/org/judging`,{on:!0}),s(e=>e+1)}}),a){let t=await qU(e).catch(()=>[]);o.push({done:t.filter(e=>e.status!==`disabled`).length>1,name:`Invite your team`,action:`Invite`,to:`/team`})}n||r(o)})(),()=>{n=!0}},[e,i,a,t,o]),n===null||n.length===0||n.every(e=>e.done)?null:(0,A.jsxs)(H,{children:[(0,A.jsx)(`div`,{className:`ui-card-head`,children:(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Finish setting up`})}),(0,A.jsx)(`div`,{className:`home-steps`,children:n.map(e=>e.done?(0,A.jsxs)(`div`,{className:`home-step`,children:[(0,A.jsx)(`span`,{className:`home-step-done`,children:`✓`}),(0,A.jsx)(`span`,{className:`home-step-name home-step-name-done`,children:e.name})]},e.name):e.run===void 0?(0,A.jsxs)(k,{to:e.to??`/`,className:`home-step home-step-open`,children:[(0,A.jsx)(`span`,{className:`home-step-todo`}),(0,A.jsx)(`span`,{className:`home-step-name`,children:e.name}),(0,A.jsx)(`span`,{className:`home-step-action`,children:e.action})]},e.name):(0,A.jsxs)(`button`,{type:`button`,className:`home-step home-step-open home-step-button`,onClick:()=>void e.run?.(),children:[(0,A.jsx)(`span`,{className:`home-step-todo`}),(0,A.jsx)(`span`,{className:`home-step-name`,children:e.name}),(0,A.jsx)(`span`,{className:`home-step-action`,children:e.action})]},e.name))})]})}var iW=new Set([`transferred`,`supervisor_ended`]),aW={escalated:{pill:`red`,tint:`red`},"low score":{pill:`amber`,tint:`amber`},"promise made":{pill:`indigo`,tint:`indigo`}},oW={escalated:`escalated`,low_score:`low score`,promise:`promise made`};function sW(){let e=new Date().getHours();return e<12?`Good morning`:e<19?`Good afternoon`:`Good evening`}function cW(e){let t=[];for(let n of e){let{score:e}=n,r=n.line;if(r.flags!==void 0&&r.flags!==null){let e=r.flags.map(e=>oW[e]).find(e=>e!==void 0);e!==void 0&&t.push({row:n,flag:e,reason:r.score?.reason??r.outcome??``});continue}if(r.end_reason!==null&&iW.has(r.end_reason))t.push({row:n,flag:`escalated`,reason:r.outcome??(r.end_reason===`transferred`?`Handed to a person`:`A supervisor ended it`)});else if(e!==null&&e.passed===!1){let i=e.judges.find(e=>e.verdict===`broken`);t.push({row:n,flag:`low score`,reason:i?.reason??r.outcome??`A judge did not hold`})}}return t}function lW(e){let t=e.filter(e=>!e.live);return t.length===0?null:t.filter(e=>e.end_reason===null||!iW.has(e.end_reason)).length/t.length}function uW(){let e=Wh(),{lines:t,live:n,insights:r}=wb(),i=Sg(),a=Cg(t,i.today),o=Cg(t,i.yesterday),s=cW(DE(a)),c=(e?.name??``).split(` `)[0]??``,l=Ag(i.yesterday),u=r?.conversations.today??a.length,d=wg(u,r?.conversations.yesterday??o.length),f=r===null?lW(a):r.resolved_rate,p=r===null?lW(o):l?.resolved_rate??null,m=f===null||p===null?null:Math.round((f-p)*100),h=r?.spend_eur??a.reduce((e,t)=>e+(t.cost?.eur??0),0),g=r?.budget.limit_eur??null,_=n.length===0?`Nobody on a call right now`:n.length===1?`One call on the floor`:`${n.length} calls on the floor`,v=s.length===0?`nothing needs a look`:s.length===1?`one conversation needs a look`:`${s.length} conversations need a look`;return(0,A.jsxs)(Dh,{children:[(0,A.jsx)(Oh,{title:c===``?sW():`${sW()}, ${c}`,lede:`${_}, ${v}, everything else handled.`}),(0,A.jsxs)(kh,{min:190,children:[(0,A.jsx)(Ah,{size:`big`,label:`Conversations`,value:a.length,delta:d?.text,tone:d?.tone}),(0,A.jsx)(Ah,{size:`big`,label:`Resolved without a human`,value:f===null?`—`:Tg(f),delta:m===null?void 0:m===0?`steady`:`${m>0?`+`:`−`}${Math.abs(m)} pts`,tone:m===null||m===0?`flat`:m>0?`up`:`down`}),r!==null&&(0,A.jsx)(fW,{insights:r,before:l}),(0,A.jsx)(Ah,{size:`big`,label:`Spend today`,value:gg(h),delta:g===null?`today`:`of €${g}`,tone:`flat`})]}),(0,A.jsxs)(`div`,{className:`home-split`,children:[(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Needs a look`,meta:`${s.length} of ${u} today`,action:(0,A.jsx)(Xm,{to:`/sessions`,children:`All sessions`})}),s.length===0&&(0,A.jsx)(Qm,{children:`Nothing today needs a look: no call went to a person, and no judge said no.`}),s.map(e=>(0,A.jsx)(eh,{to:`/sessions/${e.row.line.call}`,lead:(0,A.jsx)(Th,{name:Dg(e.row.line),tint:aW[e.flag].tint}),name:Dg(e.row.line),tag:(0,A.jsx)(vh,{tone:aW[e.flag].pill,small:!0,children:e.flag}),sub:e.reason,end:(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`ui-row-end-1`,children:[e.row.line.channel??`—`,` · `,pg(e.row.line)]}),(0,A.jsx)(`div`,{className:`ui-row-end-2`,children:bg(e.row.line.started_at)})]})},e.row.line.call)),(0,A.jsxs)(Zm,{children:[(0,A.jsxs)(`span`,{children:[Math.max(0,u-s.length),` more handled cleanly`]}),(0,A.jsx)(Xm,{to:`/sessions`,children:`See all sessions`})]})]}),(0,A.jsxs)(`div`,{className:`home-side`,children:[(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:(0,A.jsxs)(`span`,{className:`home-floor-title`,children:[(0,A.jsx)(bh,{tone:n.length>0?`green`:void 0}),(0,A.jsx)(`span`,{className:`ui-card-title`,children:`On the floor now`})]})}),(0,A.jsxs)(`div`,{className:`home-floor`,children:[n.length===0&&(0,A.jsx)(`div`,{className:`home-quiet`,children:`Nobody is on a call. A call that rings appears here the moment it does.`}),n.slice(0,4).map(e=>(0,A.jsxs)(`div`,{className:`home-live`,children:[(0,A.jsx)(Th,{name:Dg(e),tint:`green`}),(0,A.jsxs)(`div`,{className:`ui-row-main`,children:[(0,A.jsx)(`div`,{className:`home-live-name`,children:Dg(e)}),(0,A.jsxs)(`div`,{className:`home-live-sub`,children:[e.agent,` · `,e.channel??`—`,` · `,mg(e.started_at)]})]}),(0,A.jsx)(ah,{to:`/live/${e.call}`,size:`xs`,children:`Listen`})]},e.call))]})]}),(0,A.jsx)(pW,{lines:a.length>0?a:t,counted:r!==null&&u>0?r.channels:null}),(0,A.jsx)(rW,{})]})]})]})}var dW=[{channel:`phone`,name:`Phone`,color:`var(--accent)`},{channel:`web`,name:`Web`,color:`var(--accent-2)`},{channel:`whatsapp`,name:`WhatsApp`,color:`var(--accent-3)`}];function fW({insights:e,before:t}){let n=e.median_e2e_s,r=t?.median_e2e_s??null,i=`today`,a=`flat`;if(n!==null&&r!==null){let e=Math.round((n-r)*10)/10;Math.abs(e)<.1?i=`steady`:(i=`${e>0?`+`:`−`}${Math.abs(e).toFixed(1)}s`,a=e>0?`down`:`up`)}return(0,A.jsx)(Ah,{size:`big`,label:`Median answer`,value:n===null?`—`:`${n.toFixed(1)}s`,delta:i,tone:a})}function pW({lines:e,counted:t}){let n=t===null?e.length:t.phone+t.web+t.whatsapp,r=n=>t===null?e.filter(e=>e.channel===n).length:t[n]??0;return(0,A.jsxs)(H,{children:[(0,A.jsx)(`div`,{className:`ui-card-head`,children:(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Where calls arrive`})}),(0,A.jsx)(`div`,{className:`home-channels`,children:dW.map(({channel:e,name:t,color:i})=>{let a=n===0?0:r(e)/n;return(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:`home-channel-line`,children:[(0,A.jsx)(`span`,{className:`home-channel-name`,children:t}),(0,A.jsx)(`span`,{className:`home-channel-share`,children:Tg(a)})]}),(0,A.jsx)(Eh,{share:a,color:i})]},e)})})]})}var mW=`minmax(0,1.2fr) 96px minmax(0,1fr) 150px 92px`;function hW(){let e=j(),t=Wh(),n=Kh(),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(`production`),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(null),_=n!==null&&n.includes(`app`),v=t?.production===!0,y=v?s:`sandbox`,b=async()=>i(await jb(e));(0,D.useEffect)(()=>{let t=!1;return jb(e).then(e=>{t||i(e)},e=>{t||g(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]);let x=async t=>{if(t.preventDefault(),a.trim()===``){g(`Name what the token is for — the server or the job it will run on.`);return}u(!0),g(null);try{f(await Mb(e,{label:a.trim(),env:y})),m(!1),o(``),await b()}catch(e){g(e instanceof ta?e.message:String(e))}finally{u(!1)}},S=async t=>{g(null);try{await Nb(e,t),await b()}catch(e){g(e instanceof ta?e.message:String(e))}},C=async e=>{try{await navigator.clipboard.writeText(e),m(!0)}catch{m(!1)}};return(0,A.jsxs)(Dh,{tight:!0,children:[(0,A.jsx)(Oh,{title:`Tokens`,ledeWidth:640,lede:"Your own keys — one per device, what `pinecall link` writes into a project — and the tokens this org's servers run on. A server's token is the org's: it opens one world, and it stays when the person who made it leaves."}),_&&(0,A.jsx)(H,{pad:!0,children:(0,A.jsxs)(`form`,{className:`keys-form`,onSubmit:e=>void x(e),children:[(0,A.jsxs)(`div`,{className:`keys-label-field`,children:[(0,A.jsx)(`label`,{className:`ui-label`,htmlFor:`token-label`,children:`New server token`}),(0,A.jsx)(G,{id:`token-label`,value:a,placeholder:`maravilla web`,onChange:e=>o(e.target.value)})]}),(0,A.jsxs)(ch,{className:`keys-env-select`,value:y,onChange:e=>c(e.target.value),"aria-label":`which world it opens`,children:[(0,A.jsx)(`option`,{value:`production`,disabled:!v,children:`production`}),(0,A.jsx)(`option`,{value:`sandbox`,children:`sandbox`})]}),(0,A.jsx)(W,{type:`submit`,kind:`primary`,size:`form`,disabled:l,children:l?`Making…`:`Create`}),(0,A.jsx)(`div`,{className:`keys-form-note`,children:v?`It holds the agent in that world and pushes its knowledge base in a release — nothing else.`:`Production's is made by somebody your org lets act in production.`})]})}),d!==null&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`${d.label??`A new token`} · ${d.env}`,meta:`shown once`,action:(0,A.jsxs)(`span`,{className:`keys-minted-actions`,children:[(0,A.jsx)(W,{size:`xs`,onClick:()=>void C(`PINECALL_KEY=${d.key}`),children:p?`Copied`:`Copy`}),(0,A.jsx)(W,{size:`xs`,onClick:()=>f(null),children:`Done`})]})}),(0,A.jsxs)(`pre`,{className:`ui-code`,children:[`PINECALL_KEY=`,d.key]}),(0,A.jsx)(`div`,{className:`keys-minted-warn`,children:`Copy it now and put it in your server's secrets: the gateway keeps its fingerprint, and this token is never shown again.`})]}),(0,A.jsx)($m,{children:h}),(0,A.jsx)(H,{children:r!==null&&r.length===0?(0,A.jsx)(Qm,{children:"No token yet. A server's is made above; yours is made by `pinecall link`."}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:mW,labels:[`Name`,`World`,`Whose`,`Last used`,`Status>`]}),(r??[]).map(e=>(0,A.jsx)(gW,{row:e,stop:S},e.fingerprint))]})})]})}function gW({row:e,stop:t}){let[n,r]=(0,D.useState)(!1),i=e.revoked_at!==null,a=e.kind===`person`?`${e.name??`a person`} · their own`:`the org's${e.created_by===null?``:` · made by ${e.created_by}`}`;return(0,A.jsxs)(`div`,{className:`ui-table-row keys-row`,style:{gridTemplateColumns:mW},onMouseLeave:()=>r(!1),children:[(0,A.jsx)(`span`,{className:i?`keys-name keys-name-gone`:`keys-name`,title:e.fingerprint,children:e.label??e.fingerprint.slice(0,12)}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:e.env??`—`}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:a}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:e.last_used_at===null?`never`:vg(Date.parse(e.last_used_at)/1e3)}),(0,A.jsxs)(`span`,{className:`ui-cell-end`,children:[!i&&(0,A.jsx)(`span`,{className:n?`keys-revoke keys-revoke-sure`:`keys-revoke`,children:(0,A.jsx)(oh,{danger:!0,onClick:()=>n?void t(e.fingerprint):r(!0),children:n?`Revoke it`:`Revoke`})}),i?(0,A.jsx)(vh,{tone:`gray`,children:`revoked`}):(0,A.jsx)(vh,{tone:`green`,children:`active`})]})]})}var _W=`/v1/lexicon`;async function vW(e){return Hy.parse(await oa(e,_W))}async function yW(e,t,n,r,i){return Hy.parse(await sa(e,_W,{lexicon:t,if_version:n,note:r,team:i}))}function bW(e){return e instanceof Error?e.message:String(e)}function xW(e){return{said:[...e?.lexicon.said??[]],heard:[...e?.lexicon.heard??[]]}}var SW={yours:`your copy`,team:`the team's`},CW=[{tab:`said`,name:`Pronunciation`},{tab:`heard`,name:`Recognition`}];function wW(){let e=j(),[t,n]=Yi(),r=t.get(`tab`)===`heard`?`heard`:`said`,[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)({said:[],heard:[]}),[c,l]=(0,D.useState)({said:[],heard:[]}),[u,d]=(0,D.useState)(`yours`),[f,p]=(0,D.useState)(``),[m,h]=(0,D.useState)(!1),[g,_]=(0,D.useState)(!1),[v,y]=(0,D.useState)(null),[b,x]=(0,D.useState)(null),S=Am===`hosted`,C=(e,t)=>{let n=xW(S?e.production:t===`team`?e.team:e.yours??e.team);s(n),l(n)};(0,D.useEffect)(()=>{let t=!1;return vW(e).then(e=>{t||(a(e),C(e,`yours`))},e=>!t&&y(bW(e))),()=>{t=!0}},[e]);let w=i===null?null:S?i.production:u===`team`?i.team:i.yours,T=JSON.stringify(o)!==JSON.stringify(c),ee=e=>{e!==u&&i!==null&&(!T||window.confirm(`Unsaved words in ${SW[u]}. Switching to ${SW[e]} discards them.`))&&(d(e),x(null),C(i,e))},te=async t=>{if(t.preventDefault(),i===null)return;h(!0),y(null),x(null);let n={said:o.said,heard:o.heard};try{let t=await yW(e,n,w?.version??null,f.trim()===``?null:f.trim(),u===`team`);a(t),C(t,u),p(``),x(`Saved. Every agent of the org uses it from its next call.`)}catch(e){y(bW(e))}finally{h(!1)}};return(0,A.jsxs)(Dh,{width:900,tight:!0,children:[(0,A.jsx)(Oh,{title:`Lexicon`,ledeWidth:640,lede:`The org's own words, shared by every agent: how the voice pronounces a brand, a surname or an acronym, and which names the speech recognition must expect. A change applies from the next call — no developer, no deploy.`}),i===null?(0,A.jsx)(Qm,{children:v??`Asking the gateway…`}):(0,A.jsxs)(`form`,{className:`ui-card lex`,onSubmit:e=>void te(e),children:[(0,A.jsxs)(`div`,{className:`lex-where`,children:[S?(0,A.jsxs)(`span`,{className:`lex-where-words`,children:[`Editing `,(0,A.jsx)(`b`,{children:`production`}),` — what customers hear.`]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`lex-where-words`,children:`Editing`}),(0,A.jsx)(dh,{options:[{value:`yours`,label:`Your copy`},{value:`team`,label:`The team's`}],value:u,onChange:ee}),(0,A.jsx)(`span`,{className:`lex-where-hint`,children:u===`yours`?`Only your sandbox copy hears it.`:`Every copy without words of its own hears it.`})]}),(0,A.jsx)(`span`,{className:`lex-version`,children:w===null?`nothing saved yet`:`v${w.version} · ${w.author} · ${vg(w.set_at)}`})]}),(0,A.jsxs)(`div`,{className:`lex-tabs`,children:[(0,A.jsx)(zh,{label:`Lexicon`,tabs:CW.map(e=>({...e,mark:(0,A.jsx)(`span`,{className:`lex-count`,children:e.tab===`said`?o.said.length:o.heard.length})})),on:r,onPick:e=>n(e===`said`?{}:{tab:e})}),(0,A.jsx)(`button`,{type:`button`,className:`lex-help`,onClick:()=>_(!0),children:`How this works`})]}),r===`said`?(0,A.jsx)(EW,{words:o,onChange:s}):(0,A.jsx)(DW,{words:o,onChange:s}),(0,A.jsxs)(`div`,{className:`lex-save`,children:[(0,A.jsx)(G,{className:`lex-note`,value:f,placeholder:`Why, for the history (optional)`,"aria-label":`Why, for the history (optional)`,onChange:e=>p(e.target.value)}),(0,A.jsx)(W,{kind:`primary`,size:`form`,type:`submit`,disabled:m||!T,children:m?`Saving…`:`Save changes`}),(0,A.jsx)(`span`,{className:T?`lex-state lex-state-dirty`:`lex-state`,children:T?`Unsaved changes`:b??`Up to date`})]})]}),g&&(0,A.jsx)(TW,{onClose:()=>_(!1)}),i!==null&&(0,A.jsx)($m,{children:v})]})}function TW({onClose:e}){return(0,D.useEffect)(()=>{let t=t=>{t.key===`Escape`&&e()};return window.addEventListener(`keydown`,t),()=>window.removeEventListener(`keydown`,t)},[e]),(0,A.jsx)(`div`,{className:`lex-veil`,onMouseDown:e,children:(0,A.jsxs)(`div`,{className:`lex-help-box`,role:`dialog`,"aria-label":`How the lexicon works`,onMouseDown:e=>e.stopPropagation(),children:[(0,A.jsxs)(`div`,{className:`lex-help-head`,children:[(0,A.jsx)(`b`,{children:`How this works`}),(0,A.jsx)(`button`,{type:`button`,className:`lex-help-x`,"aria-label":`Close`,onClick:e,children:`×`})]}),(0,A.jsxs)(`section`,{className:`lex-help-part`,children:[(0,A.jsx)(`h3`,{children:`Pronunciation`}),(0,A.jsx)(`p`,{children:`When the voice reads a word as it is written and gets it wrong, write it the way it should sound. The voice says the second spelling every time the first appears.`}),(0,A.jsxs)(`p`,{className:`lex-help-eg`,children:[(0,A.jsx)(`b`,{children:`Vidal`}),` → “Bidal” · `,(0,A.jsx)(`b`,{children:`SQL`}),` → “sequel”`]})]}),(0,A.jsxs)(`section`,{className:`lex-help-part`,children:[(0,A.jsx)(`h3`,{children:`Recognition`}),(0,A.jsx)(`p`,{children:`Words a caller says that the speech recognition would otherwise mishear: brand names, surnames, streets, product codes. The agent's ears expect them on every call.`}),(0,A.jsxs)(`p`,{className:`lex-help-eg`,children:[(0,A.jsx)(`b`,{children:`Maravilla`}),` · `,(0,A.jsx)(`b`,{children:`Coral Gables`}),` · `,(0,A.jsx)(`b`,{children:`Ferrán`})]})]})]})})}function EW({words:e,onChange:t}){let[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(``),o=()=>{n.trim()!==``&&i.trim()!==``&&(t({...e,said:[...e.said.filter(e=>e.word!==n.trim()),{word:n.trim(),spoken:i.trim()}]}),r(``),a(``))};return(0,A.jsxs)(`section`,{className:`lex-panel`,children:[e.said.length===0?(0,A.jsx)(`p`,{className:`lex-none`,children:`No word is pronounced any other way than it is written.`}):(0,A.jsxs)(`div`,{className:`lex-table`,children:[(0,A.jsxs)(`div`,{className:`lex-row lex-row-head`,children:[(0,A.jsx)(`span`,{children:`Written as`}),(0,A.jsx)(`span`,{children:`Said as`}),(0,A.jsx)(`span`,{})]}),e.said.map(n=>(0,A.jsxs)(`div`,{className:`lex-row`,children:[(0,A.jsx)(`span`,{className:`lex-word`,children:n.word}),(0,A.jsxs)(`span`,{className:`lex-spoken`,children:[`“`,n.spoken,`”`]}),(0,A.jsx)(`button`,{type:`button`,className:`lex-x`,"aria-label":`remove ${n.word}`,onClick:()=>t({...e,said:e.said.filter(e=>e.word!==n.word)}),children:`Remove`})]},n.word))]}),(0,A.jsxs)(`div`,{className:`lex-add`,children:[(0,A.jsx)(G,{size:`sm`,value:n,placeholder:`Written as — Vidal`,"aria-label":`Written as`,onChange:e=>r(e.target.value),onKeyDown:e=>e.key===`Enter`&&(e.preventDefault(),o())}),(0,A.jsx)(`span`,{className:`lex-arrow`,"aria-hidden":!0,children:`→`}),(0,A.jsx)(G,{size:`sm`,value:i,placeholder:`Said as — Bidal`,"aria-label":`Said as`,onChange:e=>a(e.target.value),onKeyDown:e=>e.key===`Enter`&&(e.preventDefault(),o())}),(0,A.jsx)(W,{size:`sm`,disabled:n.trim()===``||i.trim()===``,onClick:o,children:`Add`})]})]})}function DW({words:e,onChange:t}){let[n,r]=(0,D.useState)(``),i=()=>{let i=n.split(/[,\n]/).map(e=>e.trim()).filter(t=>t!==``&&!e.heard.includes(t));i.length>0&&t({...e,heard:[...e.heard,...i]}),r(``)};return(0,A.jsxs)(`section`,{className:`lex-panel`,children:[e.heard.length===0?(0,A.jsx)(`p`,{className:`lex-none`,children:`No extra words: the ears know only the names the call's state carries.`}):(0,A.jsx)(`div`,{className:`lex-chips`,children:e.heard.map(n=>(0,A.jsxs)(`span`,{className:`lex-chip`,children:[n,(0,A.jsx)(`button`,{type:`button`,className:`lex-chip-x`,"aria-label":`remove ${n}`,onClick:()=>t({...e,heard:e.heard.filter(e=>e!==n)}),children:`×`})]},n))}),(0,A.jsxs)(`div`,{className:`lex-add`,children:[(0,A.jsx)(G,{size:`sm`,value:n,placeholder:`Add words — several at once, separated by commas`,"aria-label":`Words the ears must expect`,onChange:e=>r(e.target.value),onKeyDown:e=>e.key===`Enter`&&(e.preventDefault(),i())}),(0,A.jsx)(W,{size:`sm`,disabled:n.trim()===``,onClick:i,children:`Add`})]})]})}var OW=[`all`,...tg],kW=`130px minmax(0,1.6fr) 110px 92px`,AW={[Xh]:0,[Qh]:1,[$h]:2,[Zh]:3};function jW(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(`all`),[d,f]=(0,D.useState)(!1),[p,m]=(0,D.useState)(null),h=async()=>i(await ix(e));(0,D.useEffect)(()=>{let t=!1,r=e=>{t||m(e instanceof Error?e.message:String(e))};return rg(e).then(e=>{t||n(e)},r),ix(e).then(e=>{t||i(e)},r),()=>{t=!0}},[e]);let g=async t=>{t.preventDefault(),f(!0),m(null);try{await ax(e,a.trim(),s),c(``),o(``),await h()}catch(e){m(e instanceof ta?e.message:String(e))}finally{f(!1)}},_=async t=>{m(null);try{await ox(e,t),await h()}catch(e){m(e instanceof ta?e.message:String(e))}},v=t?.providers??[],y=new Set(r??[]),b=(l===`all`?v:ig(v,l)).slice().sort((e,t)=>Number(y.has(t.name))-Number(y.has(e.name))||AW[e.standing]-AW[t.standing]||e.name.localeCompare(t.name));return(0,A.jsxs)(Dh,{tight:!0,children:[(0,A.jsx)(Oh,{title:`Providers`,ledeWidth:660,lede:`Every vendor the runtime can reach, and what each one still wants on this box. Nothing reads a key back — not this page, not the CLI, not the log.`}),(0,A.jsxs)(H,{pad:!0,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void g(e),children:[(0,A.jsx)(uh,{label:`Bring one`,minWidth:180,children:(0,A.jsxs)(ch,{value:a,onChange:e=>o(e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`Choose a vendor…`}),v.filter(e=>e.env!==null).map(e=>(0,A.jsxs)(`option`,{value:e.name,children:[e.name,` · `,e.does.join(` `)]},e.name))]})}),(0,A.jsx)(uh,{label:`The key, sent once`,grow:!0,minWidth:220,children:(0,A.jsx)(G,{type:`password`,value:s,placeholder:`sk-…`,autoComplete:`off`,onChange:e=>c(e.target.value)})}),(0,A.jsx)(W,{kind:`primary`,size:`form`,type:`submit`,disabled:d||a.trim()===``||s===``,children:d?`Sending…`:`Bring it`})]}),(0,A.jsx)(`div`,{className:`prov-hint`,children:`A key brought here runs every call of this org from the next one; every vendor nobody brought runs on the box's own key.`})]}),(0,A.jsx)($m,{children:p}),(0,A.jsx)(fh,{options:OW.map(e=>({value:e,label:e===`all`?`All ${v.length}`:`${e.toUpperCase()} ${ig(v,e).length}`})),value:l,onChange:u}),(0,A.jsx)(H,{children:b.map(e=>(0,A.jsxs)(`div`,{className:`prov-row`,style:{gridTemplateColumns:kW},title:e.aliases.length>0?`also ${e.aliases.join(` · `)}`:void 0,children:[(0,A.jsx)(`span`,{className:`prov-name`,children:e.name}),(0,A.jsxs)(`span`,{className:`prov-note`,children:[(0,A.jsx)(`span`,{className:`ui-clip`,children:ag(e)}),y.has(e.name)&&(0,A.jsx)(oh,{danger:!0,onClick:()=>void _(e.name),children:`Give back`})]}),(0,A.jsx)(`span`,{className:`prov-kinds`,children:e.does.join(` `)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(MW,{provider:e,brought:y.has(e.name)})})]},e.name))})]})}function MW({provider:e,brought:t}){return t?(0,A.jsx)(vh,{tone:`green`,children:`your key`}):e.standing===`ready`?(0,A.jsx)(vh,{tone:`green`,children:`ready`}):(0,A.jsx)(vh,{tone:`gray`,children:e.standing})}function NW(e){return`/v1/agents/${encodeURIComponent(e)}/settings`}async function PW(e,t){return Ry.parse(await oa(e,NW(t)))}async function FW(e,t,n){return Ry.parse(await sa(e,NW(t),n))}async function IW(e,t,n){return zy.parse(await oa(e,`${NW(t)}/history`,{team:String(n)}))}async function LW(e,t,n,r){return Ry.parse(await ca(e,`${NW(t)}/rollback`,{version:n,team:r}))}var RW=[`voice`,`tts`,`tts_model`,`stt`,`llm`,`greeting`,`hangup`,`turn`,`memory`,`knowledge`,`bases`],zW={voice:`Voice`,tts:`Voice vendor`,tts_model:`Voice model`,stt:`STT`,llm:`LLM`,greeting:`Opening`,hangup:`Hang up when`,turn:`Turn`,memory:`Memory`,knowledge:`Knowledge`,bases:`Bases`};function BW(e,t){if(t===`greeting`){let t=e.greeting??void 0;if(t===void 0)return;let n=t.say??void 0;return n===void 0?`reply: ${t.reply??``}`:`"${n}"`}if(t===`hangup`){let t=e.hangup??void 0;return t===void 0?void 0:t.when?`when ${t.when}`:`may hang up`}if(t===`turn`){let t=e.turn??void 0;if(t===void 0)return;let n=[];return typeof t.endpointing_ms==`number`&&n.push(`endpointing ${t.endpointing_ms} ms`),typeof t.min_interruption_words==`number`&&n.push(`interrupt at ${t.min_interruption_words} words`),n.join(` · `)}if(t===`memory`){let t=e.memory??void 0;return t===void 0?void 0:`remember ${t.remember?.length??0} · forget ${t.forget?.length??0}`}if(t===`knowledge`){let t=e.knowledge??void 0;return t===void 0?void 0:`${t.length.toLocaleString(`en-US`)} chars`}if(t===`bases`){let t=e.bases??void 0;return t===void 0||t.length===0?void 0:t.map(e=>`${e.base}${typeof e.k==`number`?` (k ${e.k})`:``}`).join(` · `)}let n=e[t];return typeof n==`string`?n:void 0}function VW(e,t){let n=[];for(let r of RW){let i=BW(e,r),a=BW(t,r);i!==a&&n.push(`${zW[r]} ${i??`—`} → ${a??`—`}`)}return n}function HW(e,t){return t?e.team:e.yours}function UW(e){return e instanceof Error?e.message:String(e)}function WW(e){return(Am===`hosted`?e.production:e.yours??e.team)?.config.bases??[]}function GW({agent:e}){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1;return PW(t,e).then(e=>{n||r(WW(e))},e=>{n||a(UW(e))}),()=>{n=!0}},[t,e]),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Attached bases`,meta:`what this agent reads on every call — set in Settings, per corner and versioned`}),i===null?n===null?(0,A.jsx)(Qm,{children:`Asking the gateway…`}):n.length===0?(0,A.jsxs)(Qm,{children:[`No base attached: this agent searches nothing. Attach one in `,(0,A.jsx)(k,{to:`/a/${encodeURIComponent(e)}/settings`,children:`Settings`}),", or `pinecall docs attach <base>`."]}):(0,A.jsxs)(`div`,{className:`kb-attached`,children:[n.map(e=>(0,A.jsxs)(`div`,{className:`kb-attached-row`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e.base}),(0,A.jsxs)(`span`,{className:`ui-cell-faint`,children:[e.mode??`retrieved`,` · k `,e.k??8,e.min_score===void 0||e.min_score===null?``:` · min score ${e.min_score}`]})]},e.base)),(0,A.jsxs)(`div`,{className:`ui-card-foot`,children:[n.length>1&&`They are one search: read together and ranked against each other, so a base with nothing to say about the question takes none of the turn's chunks. `,`Change them in `,(0,A.jsx)(k,{to:`/a/${encodeURIComponent(e)}/settings`,children:`Settings`}),`.`]})]}):(0,A.jsx)(Qm,{children:i})]})}var KW=z({agent:P().nullable(),base:P().nullable(),directory:P().nullable(),files:I(),golden:P().nullable(),questions:I()}),qW=Ty.extend({files:I()});async function JW(e){return Ey.parse(await oa(e,`/v1/knowledge`))}async function YW(e,t){return KW.parse(await wC(e,t,`knowledge.roster`,{agent:t}))}async function XW(e,t,n){return qW.parse(await wC(e,t,`knowledge.push`,{agent:t,...n===``?{}:{base:n}}))}async function ZW(e,t,n){return wy.parse(await wC(e,t,`knowledge.eval`,{agent:t,...n===``?{}:{base:n}}))}async function QW(e,t){await la(e,`/v1/knowledge/${encodeURIComponent(t)}`)}var $W=`minmax(0,1fr) 90px 140px 150px 80px`;function eG(){let e=j(),t=Sr().agent??``,[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(``),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(null),[m,h]=(0,D.useState)(null),[g,_]=(0,D.useState)(null),v=(0,D.useCallback)(async()=>{s((await JW(e)).bases)},[e]);(0,D.useEffect)(()=>{let n=!1;return v().catch(e=>{n||_(nG(e))}),YW(e,t).then(e=>{n||(r(e),l(e.base??t))},e=>{n||a(nG(e))}),()=>{n=!0}},[e,t,v]);let y=async n=>{d(n),_(null);try{n===`push`?(p(await XW(e,t,c)),await v()):h(await ZW(e,t,c))}catch(e){_(nG(e))}finally{d(``)}},b=async t=>{if(window.confirm(`Drop the base ${t}? Nothing brings it back but another push.`)){_(null);try{await QW(e,t),await v()}catch(e){_(nG(e))}}},x=n!==null&&n.agent===t;return(0,A.jsxs)(Dh,{width:1060,tight:!0,children:[(0,A.jsx)(Oh,{title:`Docs`,ledeWidth:620,lede:`The documents this agent searches on a turn — the RAG. A base opens onto its files, read and edited one at a time; a project pushes its folder whole from here. Which bases the agent reads is its Settings; what it knows by heart is Settings ▸ Knowledge, not a document.`}),(0,A.jsx)(GW,{agent:t}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`This directory`,children:x&&(0,A.jsxs)(`label`,{className:`kb-base`,children:[(0,A.jsx)(`span`,{className:`kb-base-label`,children:`base`}),(0,A.jsx)(`input`,{className:`kb-base-input`,value:c,size:Math.max(6,c.length),onChange:e=>l(e.target.value)})]})}),n===null&&i===null&&(0,A.jsxs)(Qm,{children:[`Asking the process that holds `,t,`…`]}),n===null&&i!==null&&(0,A.jsxs)(Qm,{children:[`The directory is read by the process holding `,t,`, and it did not answer: `,i,`. Bases already pushed are listed below.`]}),n!==null&&!x&&(0,A.jsx)(Qm,{children:n.agent===null?"No agent class in the project the agent's `pinecall start` runs in, so there is nothing here to push.":`The process holding the agent runs in ${n.agent}'s project: to push ${t}'s documents, run \`pinecall start\` there.`}),x&&(0,A.jsxs)(`div`,{className:`kb-here`,children:[(0,A.jsx)(`span`,{className:`kb-path`,children:n.directory??`—`}),(0,A.jsxs)(`span`,{className:`kb-count`,children:[n.files,` markdown file`,n.files===1?``:`s`]}),(0,A.jsx)(W,{size:`md`,disabled:u!==``||n.files===0,onClick:()=>void y(`push`),children:u===`push`?`Pushing…`:`Push the folder`}),(0,A.jsx)(`span`,{className:`kb-path`,children:n.golden===null?`no golden beside it`:`${n.questions} questions`}),(0,A.jsx)(W,{size:`md`,disabled:u!==``||n.golden===null,onClick:()=>void y(`eval`),children:u===`eval`?`Asking…`:`Run the golden`})]}),f!==null&&(0,A.jsxs)(`div`,{className:`ui-card-foot`,children:[`Pushed `,f.base,` · `,f.files,` files · `,f.chunks,` chunks · `,Math.round(f.took_ms),` ms`]})]}),(0,A.jsx)($m,{children:g}),m!==null&&(0,A.jsx)(tG,{score:m}),(0,A.jsx)(H,{children:o!==null&&o.length===0?(0,A.jsx)(Qm,{children:"No base pushed yet. Push the folder above, or `pinecall docs push` from the project."}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:$W,labels:[`Base`,`Chunks`,`Embedder`,`Pushed`,``]}),(o??[]).map(e=>(0,A.jsxs)(Mh,{columns:$W,to:`/docs/${encodeURIComponent(e.base)}`,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.base}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:e.chunks}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.model}),(0,A.jsx)(`span`,{className:`ui-cell`,children:vg(e.pushed_at)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(oh,{danger:!0,onClick:()=>void b(e.base),children:`Drop`})})]},e.base))]})})]})}function tG({score:e}){return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`The golden`,meta:`${e.base} · ${e.model} · ${e.questions} questions · ${Math.round(e.took_ms)} ms`}),(0,A.jsxs)(`div`,{className:`kb-figures`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(`div`,{className:`kb-figure-label`,children:[`recall@`,e.k]}),(0,A.jsx)(`div`,{className:`kb-figure`,children:e.recall_at_k.toFixed(2)})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`kb-figure-label`,children:`nDCG@10`}),(0,A.jsx)(`div`,{className:`kb-figure`,children:e.ndcg_at_10.toFixed(2)})]})]}),e.misses.length===0?(0,A.jsx)(`div`,{className:`ui-card-foot`,children:`Every question found what it asked for.`}):e.misses.map(e=>(0,A.jsxs)(`div`,{className:`kb-miss`,children:[(0,A.jsx)(`div`,{className:`kb-miss-asks`,children:e.asks}),(0,A.jsxs)(`div`,{className:`kb-miss-why`,children:[`wanted `,e.expects,` · got `,e.found[0]??`nothing`]})]},e.asks))]})}function nG(e){return e instanceof ta||e instanceof Error?e.message:String(e)}var rG=`150px minmax(0,1fr) 110px 76px`;function iG(e){return e.startsWith(`+`)?Eg(e):e}function aG(){let e=j(),t=Sr().agent??``,[n,r]=(0,D.useState)(void 0),[i,a]=(0,D.useState)(``),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(null),f=(0,D.useCallback)(async()=>{r(await QT(e,t))},[e,t]);(0,D.useEffect)(()=>{let n=!1;return QT(e,t).then(e=>{n||r(e)},e=>{n||(r(null),d(cG(e)))}),()=>{n=!0}},[e,t]);let p=async t=>{t.preventDefault();let n=i.trim();d(null),l(null);try{s({contact:n,facts:(await KT(e,n)).facts})}catch(e){d(cG(e))}},m=async t=>{if(window.confirm(`Erase everything memory kept about ${t}? There is no undo.`)){d(null);try{let r=(await qT(e,t)).forgotten;l(`${r} fact${r===1?``:`s`} about ${iG(t)} forgotten.`),s({contact:t,facts:[]}),n!=null&&await f()}catch(e){d(cG(e))}}},h=async t=>{if(window.confirm(`Drop "${t.text}"? The rest of what memory keeps about ${iG(t.contact)} stays.`)){d(null);try{await $T(e,t.id),await f()}catch(e){d(cG(e))}}},g=n!=null,_=g?n.filter(e=>i.trim()===``||e.contact.includes(i.trim())):[];return(0,A.jsxs)(Dh,{width:900,tight:!0,children:[(0,A.jsx)(Oh,{title:`Memory`,ledeWidth:620,lede:`What this agent carries between calls with the same caller — written by the agent, readable here, and droppable one row at a time.`}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Callers`,children:(0,A.jsxs)(`form`,{className:`mem-look`,onSubmit:e=>void p(e),children:[(0,A.jsx)(G,{size:`sm`,value:i,placeholder:`Look up a caller — a number or an id`,onChange:e=>a(e.target.value)}),!g&&(0,A.jsx)(W,{size:`sm`,type:`submit`,disabled:i.trim()===``,children:`Look up`}),o!==null&&o.facts.length>0&&(0,A.jsx)(W,{size:`sm`,kind:`danger`,onClick:()=>void m(o.contact),children:`Forget`})]})}),c!==null&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:c}),g?_.length===0?(0,A.jsx)(Qm,{children:n.length===0?`Memory keeps nothing about any caller of this agent yet.`:`No caller matches.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:rG,labels:[`Caller`,`Remembered`,`Written`,`Action>`]}),_.map(e=>(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:rG},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,title:e.contact,children:iG(e.contact)}),(0,A.jsx)(`span`,{className:`mem-fact`,children:e.text}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:yg(e.written_at)}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(oh,{danger:!0,onClick:()=>void h(e),children:`Drop`})})]},e.id))]}):o===null?(0,A.jsx)(Qm,{children:`Look up a caller by the number they called from, or by the id your app named them with, to read what memory keeps about them.`}):o.facts.length===0?(0,A.jsxs)(Qm,{children:[`Memory keeps nothing about `,iG(o.contact),`.`]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:rG,labels:[`Caller`,`Remembered`,`Written`,`Category>`]}),o.facts.map((e,t)=>(0,A.jsxs)(`div`,{className:e.invalidated_at===null?`ui-table-row`:`ui-table-row mem-gone`,style:{gridTemplateColumns:rG},children:[(0,A.jsx)(`span`,{className:`mem-caller ui-clip`,children:iG(o.contact)}),(0,A.jsxs)(`span`,{className:`mem-fact`,children:[e.text,e.invalidated_at!==null&&(0,A.jsxs)(`span`,{className:`mem-superseded`,children:[` · superseded `,yg(e.invalidated_at)]})]}),(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:yg(e.valid_from)}),(0,A.jsx)(`span`,{className:`ui-cell-faint ui-clip mem-category`,children:e.category??`—`})]},e.id??`${t}`))]})]}),(0,A.jsx)($m,{children:u}),(0,A.jsx)(oG,{agent:t})]})}function oG({agent:e}){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(null),[f,p]=(0,D.useState)(null);(0,D.useEffect)(()=>{let n=!1;return JT(t,e).then(e=>{n||r(e)},e=>{n||a(cG(e))}),()=>{n=!0}},[t,e]);let m=async n=>{s(n),p(null);try{n===`recall`?l(await YT(t,e)):d(await XT(t,e))}catch(e){p(cG(e))}finally{s(``)}};return n===null?i===null?null:(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`The goldens of this directory`}),(0,A.jsxs)(Qm,{children:[`They are read by the process holding `,e,`, and it did not answer: `,i,`.`]})]}):n.agent===e?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`mem-goldens`,children:[(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Recall`,meta:`${n.questions} questions`}),(0,A.jsxs)(`div`,{className:`mem-run`,children:[(0,A.jsx)(`p`,{className:`mem-say`,children:`Every question asked of the ranking, scored by code with no model. No contact of yours is read: each question brings its own facts to a scratch contact.`}),(0,A.jsx)(W,{size:`md`,disabled:o!==``||n.questions===0,onClick:()=>void m(`recall`),children:o===`recall`?`Asking…`:`Run it`})]}),c!==null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`mem-figures`,children:[(0,A.jsx)(sG,{label:`recall@${c.k}`,value:c.recall_at_k.toFixed(2)}),(0,A.jsx)(sG,{label:`nDCG@10`,value:c.ndcg_at_10.toFixed(2)}),(0,A.jsx)(sG,{label:`missed`,value:String(c.misses.length)})]}),c.misses.map(e=>(0,A.jsxs)(`div`,{className:`mem-miss`,children:[(0,A.jsx)(`div`,{className:`mem-miss-asks`,children:e.asks}),(0,A.jsxs)(`div`,{className:`mem-miss-why`,children:[`wanted `,e.missing.join(`, `),` · got `,e.found[0]??`nothing`]})]},e.asks))]})]}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Extraction`,meta:`${n.cases.length} cases`}),(0,A.jsxs)(`div`,{className:`mem-run`,children:[(0,A.jsx)(`p`,{className:`mem-say`,children:`One call written down per case, and one model call each — the very one a hang-up makes. Which categories got a fact, which never did, what must not survive.`}),(0,A.jsx)(W,{size:`md`,disabled:o!==``||n.cases.length===0,onClick:()=>void m(`extraction`),children:o===`extraction`?`Running…`:`Run them`})]}),u!==null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`mem-figures`,children:[(0,A.jsx)(sG,{label:`held`,value:`${u.held}/${u.cases}`}),(0,A.jsx)(sG,{label:`model`,value:u.model})]}),u.results.filter(e=>!e.held).map(e=>(0,A.jsxs)(`div`,{className:`mem-miss`,children:[(0,A.jsx)(`div`,{className:`mem-miss-asks`,children:e.name}),(0,A.jsx)(`div`,{className:`mem-miss-why`,children:(e.broke??[]).map(e=>`${e.check}: ${e.detail}`).join(` · `)})]},e.name))]})]})]}),(0,A.jsx)($m,{children:f})]}):(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`The goldens of this directory`}),(0,A.jsx)(Qm,{children:n.agent===null?"No agent class in the directory the agent's `pinecall start` runs in, so its goldens are not here.":`The process holding the agent runs in ${n.agent}'s directory: to run ${e}'s memory goldens, run \`pinecall start\` there.`})]})}function sG({label:e,value:t}){return(0,A.jsxs)(`div`,{style:{minWidth:0},children:[(0,A.jsx)(`div`,{className:`mem-figure-label`,children:e}),(0,A.jsx)(`div`,{className:`mem-figure ui-clip`,children:t})]})}function cG(e){return e instanceof ta||e instanceof Error?e.message:String(e)}function lG({carrier:e,agents:t,available:n,busy:r,onImport:i,onBuy:a,onDone:o,onClose:s}){let[c,l]=(0,D.useState)(e===null?`buy`:`import`),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(`US`),[m,h]=(0,D.useState)(``),[g,_]=(0,D.useState)(t[0]?.slug??``),[v,y]=(0,D.useState)(null);(0,D.useEffect)(()=>{g===``&&t[0]!==void 0&&_(t[0].slug)},[t,g]);let b=()=>y(null),x=async e=>c===`import`?i({number:u.trim(),agent:g},e):a({country:f.trim().toUpperCase(),...m.trim()===``?{}:{area_code:m.trim()},agent:g},e),S=async e=>{e.preventDefault(),y(await x(!0).catch(()=>null))},C=async()=>{let e=await x(!1).catch(()=>null);e!==null&&(y(null),d(``),o(e))},w=n!==null&&n.kind===`twilio`?n.numbers.filter(e=>!e.imported):[],T=e=>{l(e),b()};return(0,A.jsxs)(`div`,{className:`num-add`,children:[(0,A.jsxs)(`div`,{className:`num-add-head`,children:[(0,A.jsxs)(`div`,{className:`ui-segmented`,role:`group`,children:[(0,A.jsx)(`button`,{type:`button`,className:c===`import`?`ui-segment ui-segment-on`:`ui-segment`,"aria-pressed":c===`import`,onClick:()=>T(`import`),disabled:e===null,title:e===null?`connect your phone carrier first, in the Carrier tab`:void 0,children:w.length>0?`I already have one · ${w.length}`:`I already have one`}),(0,A.jsx)(`button`,{type:`button`,className:c===`buy`?`ui-segment ui-segment-on`:`ui-segment`,"aria-pressed":c===`buy`,onClick:()=>T(`buy`),children:`Buy a new one`})]}),(0,A.jsx)(`button`,{type:`button`,className:`ui-text-action num-add-close`,onClick:s,children:`Close`})]}),(0,A.jsxs)(`form`,{onSubmit:e=>void S(e),children:[(0,A.jsxs)(`div`,{className:c===`buy`?`num-fields num-fields-3`:`num-fields`,children:[c===`import`?(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Number`}),w.length>0?(0,A.jsxs)(ch,{value:u,onChange:e=>{d(e.target.value),b()},required:!0,children:[(0,A.jsx)(`option`,{value:``,children:`Choose a number…`}),w.map(e=>(0,A.jsxs)(`option`,{value:e.number,children:[Eg(e.number),` — `,e.name]},e.number))]}):(0,A.jsx)(G,{value:u,onChange:e=>{d(e.target.value),b()},placeholder:`+14176743169`,required:!0,autoComplete:`off`})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Country · two letters`}),(0,A.jsx)(G,{value:f,onChange:e=>{p(e.target.value),b()},maxLength:2,required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Area code · optional`}),(0,A.jsx)(G,{value:m,onChange:e=>{h(e.target.value),b()},placeholder:`417`,autoComplete:`off`})]})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Agent that answers`}),t.length>0?(0,A.jsx)(ch,{value:g,onChange:e=>{_(e.target.value),b()},required:!0,children:t.map(e=>(0,A.jsx)(`option`,{value:e.slug,children:e.slug},e.slug))}):(0,A.jsx)(G,{value:g,onChange:e=>{_(e.target.value),b()},placeholder:`the agent's slug`,required:!0,autoComplete:`off`})]})]}),(0,A.jsxs)(`div`,{className:`num-actions`,children:[(0,A.jsx)(W,{kind:`primary`,type:`submit`,disabled:r||v!==null,children:r&&v===null?`Checking…`:`Review`}),(0,A.jsx)(`span`,{className:`num-note`,children:c===`import`?`Nothing changes yet — you will see exactly what is going to happen, and confirm.`:`Nothing is bought yet — you will see the number that was found, and confirm.`})]})]}),v!==null&&(0,A.jsxs)(`div`,{className:`num-plan`,children:[(0,A.jsxs)(`div`,{className:`num-plan-title`,children:[`This is what will happen`,c===`buy`&&v.route.number!==null?(0,A.jsxs)(A.Fragment,{children:[` with `,Eg(v.route.number)]}):null,`. Nothing is deleted.`]}),(0,A.jsx)(uG,{steps:v.steps}),(0,A.jsxs)(`div`,{className:`num-plan-moves`,children:[(0,A.jsx)(W,{kind:`primary`,size:`md`,onClick:()=>void C(),disabled:r,children:r?`Working…`:c===`buy`?`Buy it and connect it`:`Confirm`}),(0,A.jsx)(W,{size:`md`,onClick:b,disabled:r,children:`Cancel`})]})]})]})}function uG({steps:e}){return(0,A.jsx)(`ol`,{className:`num-steps`,children:e.map((e,t)=>{let[n,...r]=e.split(/\s+/);return(0,A.jsxs)(`li`,{children:[(0,A.jsx)(`span`,{className:`num-step-kind`,children:n}),(0,A.jsx)(`span`,{className:`num-step-text`,children:r.join(` `)})]},t)})})}function dG({carrier:e,busy:t,onBring:n,onDrop:r}){let[i,a]=(0,D.useState)(!1);return e!==null&&!i?(0,A.jsxs)(`div`,{className:`ui-card num-carrier`,children:[(0,A.jsx)(`span`,{className:`num-kind`,children:e.kind.toUpperCase()}),(0,A.jsx)(`span`,{className:`num-carrier-standing`,children:e.kind===`twilio`?`Account connected`:`SIP peer connected`}),(0,A.jsx)(`span`,{className:`num-carrier-account`,children:e.account}),(0,A.jsxs)(`span`,{className:`num-carrier-moves`,children:[(0,A.jsx)(W,{size:`xs`,onClick:()=>a(!0),disabled:t,children:`Change`}),(0,A.jsx)(W,{size:`xs`,kind:`danger`,onClick:()=>void r(),disabled:t,children:`Disconnect`})]})]}):(0,A.jsx)(fG,{busy:t,onBring:async e=>{await n(e),a(!1)},onCancel:e===null?null:()=>a(!1)})}function fG({busy:e,onBring:t,onCancel:n}){let[r,i]=(0,D.useState)(`twilio`),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(``),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(``),[p,m]=(0,D.useState)(``),[h,g]=(0,D.useState)(``),[_,v]=(0,D.useState)(``),[y,b]=(0,D.useState)(`auto`),[x,S]=(0,D.useState)(``),[C,w]=(0,D.useState)(``);return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Connect your phone carrier`,children:(0,A.jsxs)(`div`,{className:`ui-segmented num-ways`,role:`group`,children:[(0,A.jsx)(`button`,{type:`button`,className:r===`twilio`?`ui-segment ui-segment-on`:`ui-segment`,onClick:()=>i(`twilio`),children:`Twilio`}),(0,A.jsx)(`button`,{type:`button`,className:r===`sip`?`ui-segment ui-segment-on`:`ui-segment`,onClick:()=>i(`sip`),children:`SIP peer`})]})}),(0,A.jsxs)(`form`,{onSubmit:e=>{e.preventDefault(),t(r===`twilio`?{kind:r,account_sid:a.trim(),user:s.trim()||a.trim(),secret:l}:{kind:r,username:d.trim(),password:p,addresses:h.split(/[\s,]+/).filter(Boolean),..._.trim()===``?{}:{outbound_host:_.trim(),outbound_transport:y,...x.trim()===``?{}:{outbound_username:x.trim()},...C===``?{}:{outbound_password:C}}})},children:[(0,A.jsx)(`div`,{className:`num-fields num-fields-3`,children:r===`twilio`?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Account SID`}),(0,A.jsx)(G,{value:a,onChange:e=>o(e.target.value),placeholder:`AC…`,required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`API key SID · or the account SID`}),(0,A.jsx)(G,{value:s,onChange:e=>c(e.target.value),placeholder:`SK…`,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Secret · the key's, or the auth token`}),(0,A.jsx)(G,{type:`password`,value:l,onChange:e=>u(e.target.value),required:!0,autoComplete:`off`})]})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Username`}),(0,A.jsx)(G,{value:d,onChange:e=>f(e.target.value),required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Password`}),(0,A.jsx)(G,{type:`password`,value:p,onChange:e=>m(e.target.value),required:!0,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Networks its calls come from · CIDR`}),(0,A.jsx)(G,{value:h,onChange:e=>g(e.target.value),placeholder:`203.0.113.0/24`,required:!0,autoComplete:`off`})]})]})}),r===`sip`&&(0,A.jsxs)(`div`,{className:`num-outbound-group`,children:[(0,A.jsx)(`div`,{className:`num-outbound-title`,children:`Outbound`}),(0,A.jsx)(`div`,{className:`num-outbound-say`,children:`Where this box sends a call it places. Leave empty for a peer you only receive from.`}),(0,A.jsxs)(`div`,{className:`num-fields num-fields-4 num-fields-flush`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Host · and port`}),(0,A.jsx)(G,{value:_,onChange:e=>v(e.target.value),placeholder:`sip.carrier.example:5060`,autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Transport`}),(0,A.jsxs)(ch,{value:y,onChange:e=>b(e.target.value),children:[(0,A.jsx)(`option`,{value:`auto`,children:`auto`}),(0,A.jsx)(`option`,{value:`udp`,children:`udp`}),(0,A.jsx)(`option`,{value:`tcp`,children:`tcp`}),(0,A.jsx)(`option`,{value:`tls`,children:`tls`})]})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Username · else the one above`}),(0,A.jsx)(G,{value:x,onChange:e=>S(e.target.value),autoComplete:`off`})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Password · else the one above`}),(0,A.jsx)(G,{type:`password`,value:C,onChange:e=>w(e.target.value),autoComplete:`off`})]})]})]}),(0,A.jsxs)(`div`,{className:`num-actions`,children:[(0,A.jsx)(W,{kind:`primary`,type:`submit`,disabled:e,children:e?`Connecting…`:`Connect`}),n!==null&&(0,A.jsx)(W,{onClick:n,children:`Cancel`}),(0,A.jsx)(`span`,{className:`num-note`,children:r===`twilio`?`The account is checked once. The credentials are stored encrypted and never shown again.`:`Calls are accepted only from these networks, with this username and password.`})]})]})]})}var pG=/^\+[1-9]\d{6,14}$/;function mG(e){let t=e.toLowerCase();return t.includes(`no outbound trunk`)?`Outbound calls are not turned on yet.`:t.includes(`carrier`)?(0,A.jsxs)(A.Fragment,{children:[`Connect a carrier first — `,(0,A.jsx)(k,{to:`/numbers?tab=carrier`,children:`Carrier`}),`.`]}):t.includes(`number`)?(0,A.jsxs)(A.Fragment,{children:[`Add a number first — `,(0,A.jsx)(k,{to:`/numbers`,children:`Numbers`}),`.`]}):e.replace(/:?\s*(POST|PUT|GET|DELETE) \/v1\/\S+.*$/,``).trim()}function hG(e){return[e.dial_anywhere?`Agents can call any number`:`Agents can only call numbers that already contacted you`,`${e.per_minute} a minute`,`${e.per_day} a day`,`${Math.round(e.max_duration_s/60)} min per call`].join(` · `)}function gG({outbound:e,agents:t,busy:n,onProvision:r}){let[i,a]=(0,D.useState)(null);if(e===null)return(0,A.jsx)(H,{children:(0,A.jsxs)(`div`,{className:`num-hero`,children:[(0,A.jsx)(`div`,{className:`num-hero-title`,children:`Let your agents call people back`}),(0,A.jsxs)(`p`,{className:`num-hero-say`,children:[`Calls go out from your own numbers through your carrier account. Connect a carrier first — `,(0,A.jsx)(k,{to:`/numbers?tab=carrier`,children:`Carrier`}),`.`]})]})});let o=()=>void r(!0).then(a,()=>void 0),s=i!==null&&(0,A.jsxs)(`div`,{className:`num-plan`,children:[(0,A.jsx)(`div`,{className:`num-plan-title`,children:`What will happen — on your carrier account and on this gateway. Nothing is deleted.`}),(0,A.jsx)(uG,{steps:i.steps}),(0,A.jsxs)(`div`,{className:`num-plan-moves`,children:[(0,A.jsx)(W,{kind:`primary`,size:`md`,onClick:()=>void r(!1).then(()=>a(null),()=>void 0),disabled:n,children:n?`Working…`:`Confirm`}),(0,A.jsx)(W,{size:`md`,onClick:()=>a(null),disabled:n,children:`Cancel`})]})]});if(!e.ready){let t=e.steps_missing.every(e=>e.toLowerCase().includes(`no outbound trunk`));return(0,A.jsxs)(H,{children:[(0,A.jsxs)(`div`,{className:`num-hero`,children:[(0,A.jsx)(`div`,{className:`num-hero-title`,children:`Let your agents call people back`}),(0,A.jsx)(`p`,{className:`num-hero-say`,children:`Calls go out from your own numbers through your carrier account.`}),e.steps_missing.filter(e=>!e.toLowerCase().includes(`no outbound trunk`)).map(e=>(0,A.jsx)(`p`,{className:`num-hero-missing`,children:mG(e)},e)),t&&(0,A.jsxs)(`div`,{className:`num-hero-move`,children:[(0,A.jsx)(W,{kind:`primary`,onClick:o,disabled:n||i!==null,children:n&&i===null?`Checking…`:`Turn on outbound calls`}),(0,A.jsx)(`span`,{className:`num-note`,children:`You will see what is going to happen, and confirm.`})]})]}),s]})}let[c,...l]=e.from_numbers;return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`num-on`,children:[(0,A.jsx)(bh,{tone:`green`}),(0,A.jsxs)(`span`,{children:[(0,A.jsx)(`b`,{children:`On`}),` — agents call from `,Eg(c),l.length>0&&` and ${l.length} more`]})]}),(0,A.jsx)(_G,{agents:t,from:e.from_numbers}),(0,A.jsxs)(`div`,{className:`num-limits`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`num-limits-say`,children:hG(e.guards)}),(0,A.jsx)(`div`,{className:`num-limits-who`,children:`Limits are set by whoever runs this gateway.`})]}),(0,A.jsx)(oh,{onClick:o,disabled:n||i!==null,children:`Repair the setup`})]}),i!==null&&(0,A.jsx)(H,{children:s})]})}function _G({agents:e,from:t}){let n=j(),[r,i]=(0,D.useState)(e[0]?.slug??``),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(t[0]??``),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(null);(0,D.useEffect)(()=>{r===``&&e[0]!==void 0&&i(e[0].slug)},[e,r]);let h=async e=>{e.preventDefault();let i=a.replace(/[\s()-]/g,``);if(f(null),!pG.test(i)){m(`Write the number with its country code, like +34600000000.`);return}u(!0),m(null);try{f(await tx(n,r,i,t.length>1?s:void 0))}catch(e){m(e instanceof ta?e.message:String(e))}finally{u(!1)}};return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Make a test call`,meta:`the agent rings the number and talks when it is answered`}),(0,A.jsxs)(`form`,{onSubmit:e=>void h(e),children:[(0,A.jsxs)(`div`,{className:t.length>1?`num-fields num-fields-3`:`num-fields`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Agent`}),(0,A.jsx)(ch,{value:r,onChange:e=>i(e.target.value),required:!0,children:e.map(e=>(0,A.jsx)(`option`,{value:e.slug,children:e.slug},e.slug))})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`Number to call`}),(0,A.jsx)(G,{value:a,onChange:e=>o(e.target.value),placeholder:`+34 600 000 000`,required:!0,autoComplete:`off`})]}),t.length>1&&(0,A.jsxs)(`div`,{children:[(0,A.jsx)(sh,{children:`From`}),(0,A.jsx)(ch,{value:s,onChange:e=>c(e.target.value),children:t.map(e=>(0,A.jsx)(`option`,{value:e,children:Eg(e)},e))})]})]}),(0,A.jsxs)(`div`,{className:`num-actions`,children:[(0,A.jsx)(W,{kind:`primary`,type:`submit`,disabled:l||r===``,children:l?`Calling…`:`Call`}),d!==null&&(0,A.jsxs)(`span`,{className:`num-placed`,children:[`Ringing. `,(0,A.jsx)(k,{to:`/live/${d}`,children:`Watch it live`})]})]}),p!==null&&(0,A.jsx)(`div`,{className:`num-refused`,children:(0,A.jsx)($m,{children:p})})]})]})}var vG=[{tab:`numbers`,name:`Numbers`},{tab:`outbound`,name:`Outbound calls`},{tab:`carrier`,name:`Carrier`}];function yG(){let e=j(),{agents:t}=wb(),[n,r]=Yi(),i=vG.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`numbers`,[a,o]=(0,D.useState)(void 0),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null),[d,f]=(0,D.useState)(null),{world:p}=Yh(),[m,h]=(0,D.useState)(!1),[g,_]=(0,D.useState)(null),[v,y]=(0,D.useState)(!1),[b,x]=(0,D.useState)(null),S=(0,D.useCallback)(async()=>{let[t,n]=await Promise.all([Ub(e),Hb(e)]);o(t),c(n),u(t===null?null:await Kb(e)),f(t===null?null:await Qb(e).catch(()=>null))},[e]);(0,D.useEffect)(()=>{let e=!1;return S().catch(t=>{e||_(bG(t))}),()=>{e=!0}},[S]);let C=async e=>{h(!0),_(null);try{let t=await e();return await S(),t}catch(e){throw _(bG(e)),e}finally{h(!1)}},w=(s??[]).filter(e=>e.route.number!==null),T=(s??[]).filter(e=>e.route.number===null);return(0,A.jsxs)(Dh,{width:900,children:[(0,A.jsx)(Oh,{title:`Phone numbers`,lede:`The numbers people call, which agent picks up, and the calls your agents place.`}),(0,A.jsx)(zh,{label:`Phone numbers`,tabs:vG.map(e=>e.tab===`outbound`&&a!==void 0?{...e,mark:(0,A.jsx)(bh,{tone:d?.ready?`green`:`amber`,small:!0})}:e),on:i,onPick:e=>r(e===`numbers`?{}:{tab:e})}),(0,A.jsx)($m,{children:g}),i===`numbers`&&s!==null&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Numbers in ${p}`,action:!v&&a!==void 0?(0,A.jsx)(W,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>{x(null),y(!0)},children:`Add a number`}):void 0}),w.length===0&&(0,A.jsxs)(Qm,{children:[`No phone number rings in `,p,` yet.`]}),w.map(t=>(0,A.jsxs)(`div`,{className:`num-row`,children:[(0,A.jsx)(`span`,{className:`num-number`,children:Eg(t.route.number)}),(0,A.jsx)(`span`,{className:`num-arrow`,"aria-hidden":!0,children:`→`}),(0,A.jsx)(`span`,{className:`num-agent`,children:t.route.agent}),t.route.managed&&(0,A.jsx)(`span`,{title:`bought by the box for this org`,children:(0,A.jsx)(vh,{tone:`violet`,children:`bought`})}),t.source===`operator`&&(0,A.jsx)(W,{kind:`danger`,size:`xs`,className:`num-remove`,disabled:m,title:`The number stops ringing this agent. It stays in your carrier account.`,onClick:()=>void C(()=>Yb(e,t.route.number??``)).catch(()=>void 0),children:`Remove`})]},t.route.number)),b!==null&&(0,A.jsxs)(`div`,{className:`num-added`,children:[`Done. `,Eg(b.route.number),` now rings `,b.route.agent,`.`]}),v&&a!==void 0&&(0,A.jsx)(lG,{carrier:a,agents:t,available:l,busy:m,onImport:(t,n)=>C(()=>qb(e,{...t,channel:`phone`},n)),onBuy:(t,n)=>C(()=>Jb(e,{...t,channel:`phone`},n)),onDone:e=>{x(e),y(!1)},onClose:()=>y(!1)}),T.length>0&&(0,A.jsxs)(`div`,{className:`num-foot`,children:[`Also on the web, with no number needed: `,[...new Set(T.map(e=>e.route.agent))].join(`, `),`.`]})]}),i===`outbound`&&a!==void 0&&(0,A.jsx)(gG,{outbound:d,agents:t,busy:m,onProvision:t=>C(()=>$b(e,t))}),i===`carrier`&&a!==void 0&&(0,A.jsx)(dG,{carrier:a,busy:m,onBring:async t=>{await C(()=>Wb(e,t)).catch(()=>void 0)},onDrop:async()=>{await C(()=>Gb(e)).catch(()=>void 0)}})]})}function bG(e){return e instanceof ta?e.message:String(e)}function xG(){let e=j(),t=dg(Wh()),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)([]);(0,D.useEffect)(()=>{let t=!1;return oa(e,`/v1/line/numbers`).then(e=>{if(t)return;let n=e;r(n.numbers),a(n.calling??[])},()=>void 0),()=>{t=!0}},[e]);let o=wb().held.filter(e=>t!==null&&e.holder?.holder===t);return(0,A.jsxs)(Dh,{width:900,children:[(0,A.jsx)(Oh,{title:`Phone testing`,ledeWidth:660,lede:(0,A.jsxs)(A.Fragment,{children:[`Call the number your customers call, from your own mobile, and `,(0,A.jsx)(`b`,{children:`your copy answers`}),`. Everybody else who calls still reaches production. You do not need a sandbox number.`]})}),(0,A.jsxs)(H,{children:[(0,A.jsx)(nh,{children:`Once per machine`}),(0,A.jsx)(`pre`,{className:`ui-code`,children:`pinecall line from +1XXXXXXXXXX # this mobile is mine`}),(0,A.jsx)(nh,{ruled:!0,children:`While you work`}),(0,A.jsx)(`pre`,{className:`ui-code`,children:`pinecall start --serve # your copies up, and this console
105
+ pinecall line forget # give your calls back to production`}),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:(0,A.jsxs)(`span`,{children:[`The call shows up here, in Sessions, marked `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`diverted_from: production`}),`.`]})})]}),n!==null&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`The numbers to call`}),n.length===0&&(0,A.jsx)(Qm,{children:`This org has no phone number in production yet. The gateway's console adds one, under Numbers.`}),n.map(e=>{let t=o.some(t=>t.slug===e.agent),n=t&&i.length>0;return(0,A.jsxs)(`div`,{className:`num-row`,children:[(0,A.jsx)(`span`,{className:`num-number`,children:Eg(e.number)}),(0,A.jsx)(`span`,{className:`num-arrow`,"aria-hidden":!0,children:`→`}),(0,A.jsx)(`span`,{className:`num-agent`,children:e.agent}),(0,A.jsx)(`span`,{className:`num-end`,children:n?(0,A.jsxs)(vh,{tone:`green`,children:[`your copy answers `,i.map(Eg).join(`, `)]}):t?(0,A.jsx)(vh,{tone:`amber`,children:`production answers: say which phone is yours`}):(0,A.jsx)(vh,{tone:`gray`,children:`production answers: you are not running it`})})]},e.number)})]}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`What a call from your phone reaches right now`}),(0,A.jsx)(`div`,{className:`num-body`,children:o.length===0?(0,A.jsxs)(A.Fragment,{children:[`Nothing: no copy of yours is running, so your calls reach production. Start `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` in the project.`]}):i.length===0?(0,A.jsxs)(A.Fragment,{children:[`Production, still: you are running `,o.map(e=>e.slug).join(`, `),`, and the gateway does not know which phone is yours.`,` `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall line from +1…`}),`, once.`]}):(0,A.jsxs)(A.Fragment,{children:[`Your copy of `,o.map(e=>e.slug).join(`, `),`, from `,i.map(Eg).join(`, `),` — for as long as`,` `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` stays up.`]})})]})]})}var SG=z({vendor:P(),model:P().nullable(),voice_id:P().nullable(),language:P().nullable()}),CG=z({name:V(vw),seconds:F(),turns:I()}),wG=z({say:P().nullable(),reply:P().nullable(),allow_interruptions:L().nullable()}),TG=z({agent:P(),hears:SG,decides:SG,speaks:SG,greeting:wG.nullable(),voices:R(P()),providers:R(eg),defaults:kp(P(),P()),models:kp(P(),R(P())),calls:I(),medians:R(CG),unavailable_reasons:kp(P(),P())});async function EG(e,t){return TG.parse(await oa(e,DG(t)))}function DG(e){return`/v1/agents/${encodeURIComponent(e)}/pipeline`}var OG=z({played:V([`default`,`off`,`custom`]),name:P().nullable(),seconds:F().nullable(),sha256:P().nullable()});async function kG(e,t){return OG.parse(await oa(e,`${DG(t)}/hold-audio`))}async function AG(e,t,n){let r=await fetch(ua(e,`${DG(t)}/hold-audio`,{name:n.name}),{method:`PUT`,headers:{...ra(e),"content-type":n.type||`application/octet-stream`},body:n});return OG.parse(await pa(r))}async function jG(e,t,n){return OG.parse(await sa(e,`${DG(t)}/hold-audio/played`,{played:n}))}async function MG(e,t){let n=await fetch(ua(e,`${DG(t)}/hold-audio/audio`),{headers:ra(e)});return n.ok||await pa(n),URL.createObjectURL(await n.blob())}function NG({agent:e}){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(null),u=(0,D.useRef)(null);(0,D.useEffect)(()=>{let n=!1;return kG(t,e).then(e=>!n&&r(e),e=>!n&&s(e instanceof Error?e.message:String(e))),()=>{n=!0}},[t,e]),(0,D.useEffect)(()=>()=>{c!==null&&URL.revokeObjectURL(c)},[c]);let d=async(e,t)=>{a(e),s(null);try{r(await t()),l(null)}catch(e){s(e instanceof Error?e.message:String(e))}finally{a(null)}},f=async()=>{s(null);try{l(await MG(t,e))}catch(e){s(e instanceof Error?e.message:String(e))}},p=n=>{n!==void 0&&(d(`Converting…`,()=>AG(t,e,n)),u.current!==null&&(u.current.value=``))};return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Hold melody`,meta:`what the caller hears while a tool runs — phone and web alike, from the next call`}),(0,A.jsxs)(`div`,{className:`pipe-hold`,children:[(0,A.jsxs)(`div`,{className:`pipe-hold-now`,children:[(0,A.jsx)(`b`,{children:n===null?`…`:n.played===`off`?`Off`:n.name??`Your file`}),(0,A.jsx)(`span`,{className:`pipe-note`,children:n===null?`Asking the gateway.`:n.played===`off`?`Silence while a tool runs.`:`${n.played==="default"?`The runtime's own`:`Uploaded`} · ${n.seconds??`?`} s, looped under the wait at 60 %, after 0.6 s.`})]}),(0,A.jsxs)(`div`,{className:`pipe-hold-actions`,children:[n!==null&&n.played!==`off`&&(0,A.jsx)(W,{size:`sm`,onClick:()=>void f(),disabled:i!==null,children:`Listen`}),(0,A.jsx)(W,{size:`sm`,onClick:()=>u.current?.click(),disabled:i!==null,children:i??`Upload a file…`}),n!==null&&n.played!=="default"&&(0,A.jsx)(W,{size:`sm`,onClick:()=>void d(`Saving…`,()=>jG(t,e,`default`)),disabled:i!==null,children:`Use the default`}),n!==null&&n.played!==`off`&&(0,A.jsx)(W,{size:`sm`,onClick:()=>void d(`Saving…`,()=>jG(t,e,`off`)),disabled:i!==null,children:`Turn off`}),(0,A.jsx)(`input`,{ref:u,type:`file`,accept:`audio/*,.mp3,.wav,.ogg,.m4a`,hidden:!0,onChange:e=>p(e.target.files?.[0])})]}),c!==null&&(0,A.jsx)(`audio`,{className:`pipe-hold-player`,controls:!0,autoPlay:!0,src:c}),o===null?(0,A.jsx)(`span`,{className:`pipe-save-note`,children:`A wav, an mp3, an ogg or an m4a, up to 20 MB and five minutes: the gateway converts it.`}):(0,A.jsx)(`span`,{className:`pipe-save-error`,children:o})]})]})}function PG({stage:e,unavailable:t}){return(0,A.jsxs)(LG,{job:`hears`,stage:e,unavailable:t,children:[(0,A.jsx)(RG,{label:`Language`,value:e.language??`the vendor's default`,note:`What the ear is told to expect; the runtime adds the names the state carries.`}),e.model!==null&&e.model!==``&&(0,A.jsx)(RG,{label:`Model`,value:e.model}),(0,A.jsx)(RG,{label:`Switchable to`,value:`Any STT provider on file`,note:`Effective on the next session.`})]})}function FG({stage:e,unavailable:t}){return(0,A.jsxs)(LG,{job:`decides`,stage:e,unavailable:t,children:[(0,A.jsx)(RG,{label:`Model`,value:e.model??`the vendor's default`}),(0,A.jsx)(RG,{label:`Prompt`,value:`identity · knowledge · tools · history · view`,note:`Named blocks in two regions, never reordered: the static ones are cached, the dynamic ones rewritten every turn.`}),(0,A.jsx)(RG,{label:`Tools`,value:`The class's @tool methods`})]})}function IG({stage:e,unavailable:t}){return(0,A.jsxs)(LG,{job:`speaks`,stage:e,unavailable:t,children:[(0,A.jsx)(RG,{label:`Voice`,value:e.voice_id??`the vendor's default`,note:`One of the voices this build curates, by name; the id is the vendor's.`}),e.model!==null&&e.model!==``&&(0,A.jsx)(RG,{label:`Model`,value:e.model}),(0,A.jsx)(RG,{label:`Aligned transcript`,value:`On`,note:`Timed words, so the log knows when each word was spoken.`})]})}function LG({job:e,stage:t,unavailable:n,children:r}){return(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`pipe-leg-head`,children:[(0,A.jsx)(`span`,{className:`pipe-leg-vendor`,children:t.vendor}),(0,A.jsx)(`span`,{className:`pipe-leg-job`,children:e})]}),(0,A.jsxs)(`div`,{className:`pipe-leg-body`,children:[r,n!==null&&(0,A.jsxs)(`div`,{className:`pipe-field`,children:[(0,A.jsx)(`div`,{className:`pipe-label`,children:`Not right now`}),(0,A.jsx)(`div`,{className:`pipe-refused`,children:n})]})]})]})}function RG({label:e,value:t,note:n}){return(0,A.jsxs)(`div`,{className:`pipe-field`,children:[(0,A.jsx)(`div`,{className:`pipe-label`,children:e}),(0,A.jsx)(`div`,{className:`pipe-value`,children:t}),n!==void 0&&(0,A.jsx)(`div`,{className:`pipe-note`,children:n})]})}function zG(e){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1;return r(null),EG(t,e).then(e=>{n||r(e)},e=>{n||a(na(e))}),()=>{n=!0}},[e,t]),{report:n,error:i}}var BG={transcription_delay:{label:`Transcription`,note:`from the end of speech to the ear's final transcript`,color:`var(--accent-3)`},end_of_turn_delay:{label:`End of turn`,note:`silence the turn detector waits through before it believes the caller stopped`,color:`var(--accent-3)`},llm_node_ttft:{label:`LLM first token`,note:`to the model's first token`,color:`var(--accent)`},tts_node_ttfb:{label:`Speech starts`,note:`to the voice's first audio byte`,color:`var(--accent-2)`},e2e_latency:{label:`End to end`,note:`what the caller actually waits: their last word to the agent's first audio`,color:`var(--accent-hover)`}};function VG({medians:e,calls:t,agent:n}){let r=new Map(e.map(e=>[e.name,e])),i=Math.max(0,...e.map(e=>e.seconds)),a=Math.max(0,...e.map(e=>e.turns));return(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Anatomy of a turn`}),i>0&&(0,A.jsxs)(`span`,{className:`ui-card-meta`,children:[`medians over the last `,t,` call`,t===1?``:`s`,` · `,a,` turns`]})]}),(0,A.jsx)(`div`,{className:`pipe-anatomy`,children:vw.map((e,t)=>{let n=BG[e],a=r.get(e)?.seconds??null;return(0,A.jsxs)(`div`,{className:t===vw.length-1?`pipe-turn-row pipe-turn-row-last`:`pipe-turn-row`,title:n.note,children:[(0,A.jsx)(`span`,{className:`pipe-turn-label`,children:n.label}),(0,A.jsx)(`span`,{className:`pipe-track`,children:a!==null&&i>0&&(0,A.jsx)(`span`,{className:`pipe-bar`,style:{width:`${Math.max(a/i*100,.8)}%`,background:n.color}})}),(0,A.jsx)(`span`,{className:a===null?`pipe-ms pipe-ms-none`:`pipe-ms`,children:a===null?`—`:`${Math.round(a*1e3)} ms`})]},e)})}),i===0&&(0,A.jsx)(`div`,{className:`ui-card-foot`,children:HG(t,n)})]})}function HG(e,t){return e===0?`No call stored for ${t} yet — place one and the bars fill.`:`${e} stored call${e===1?``:`s`} for ${t}, and not one turn carries a latency — a text session measures none.`}function UG(){let e=Sr().agent??``,{report:t,error:n}=zG(e);return(0,A.jsxs)(Dh,{tight:!0,children:[(0,A.jsx)(Oh,{title:`Pipeline`,ledeWidth:660,lede:`The three legs of a voice turn as data, not prose: what hears, what decides, what speaks — every value read from the gateway with this agent's settings already laid over the class.`}),t===null?(0,A.jsx)(H,{children:(0,A.jsx)(Qm,{children:n??`Asking the gateway what ${e} runs on…`})}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`pipe-legs`,children:[(0,A.jsx)(PG,{stage:t.hears,unavailable:t.unavailable_reasons.hears??null}),(0,A.jsx)(FG,{stage:t.decides,unavailable:t.unavailable_reasons.decides??null}),(0,A.jsx)(IG,{stage:t.speaks,unavailable:t.unavailable_reasons.speaks??null})]}),(0,A.jsx)(VG,{medians:t.medians,calls:t.calls,agent:e}),(0,A.jsx)(H,{children:(0,A.jsxs)(Qm,{children:[`Changing any of it is the `,(0,A.jsx)(k,{to:`/a/${encodeURIComponent(e)}/settings`,children:`Settings`}),` tab: the vendors and models with the opening, the cut of a turn and what is remembered, per corner and versioned.`]})}),(0,A.jsx)(NG,{agent:e},`hold-${e}`)]})]})}function WG(){let e=Sr().agent??``,{lines:t,error:n}=pC(e);return(0,A.jsxs)(Dh,{tight:!0,children:[(0,A.jsx)(Oh,{title:`Sessions`,lede:`Only what ${e} handled, newest first.`}),(0,A.jsx)(RU,{lines:t,error:n,agent:e,agents:[]})]})}var GG={passed:`green`,failed:`red`,deferred:`amber`,skipped:`muted`};function KG({agent:e,call:t}){let n=j(),[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null),d=async r=>{i(r),u(null);try{r===`check`?o(await PT(n,t)):c(await IT(n,e,t))}catch(e){u(e instanceof ta?e.message:String(e))}finally{i(``)}};return(0,A.jsxs)(`div`,{className:`session-acts`,children:[(0,A.jsxs)(`div`,{className:`session-buttons`,children:[(0,A.jsx)(W,{size:`md`,disabled:r!==``,onClick:()=>void d(`check`),children:r===`check`?`Checking…`:`Re-check by code`}),(0,A.jsx)(W,{size:`md`,disabled:r!==``||e===``,onClick:()=>void d(`promote`),children:r===`promote`?`Writing…`:`Promote to a golden`})]}),a!==null&&(0,A.jsxs)(`div`,{className:`session-result`,children:[(0,A.jsx)(`span`,{className:`session-result-lead`,children:a.passed?`Holds by code`:`Does not hold by code`}),a.verdicts.map(e=>(0,A.jsxs)(vh,{tone:GG[e.status]??`muted`,children:[e.check,` `,e.status]},e.check))]}),s!==null&&(0,A.jsxs)(`div`,{className:`session-result`,children:[(0,A.jsx)(`span`,{className:`session-result-lead`,children:`Written down`}),(0,A.jsx)(`span`,{className:`ui-fixed session-path`,children:s.path}),(0,A.jsxs)(`span`,{className:`session-result-note`,children:[s.candidate.input.length,` caller `,s.candidate.input.length===1?`turn`:`turns`]}),s.notes.map(e=>(0,A.jsx)(`span`,{className:`session-result-note session-result-line`,children:e},e))]}),l!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,children:l})]})}var qG=`confirm.`,JG=`tool.call`;function YG(e){let t=new Map;for(let n of e){if(!n.type.startsWith(qG))continue;let e=iK(n,`call_id`),r=t.get(e)??nK(e,iK(n,`tool`));t.set(e,{...r,...tK(n)})}for(let n of e){let e=n.type===JG?t.get(iK(n,`call_id`)):void 0;e!==void 0&&(e.ran=n)}return[...t.values()]}function XG({rows:e}){return e.length===0?null:(0,A.jsx)(`div`,{className:`session-consents`,children:e.map(e=>(0,A.jsx)(ZG,{consent:e},e.callId))})}function ZG({consent:e}){let t=$G(e);return(0,A.jsxs)(`div`,{className:`session-consent`,children:[(0,A.jsxs)(`div`,{className:`session-consent-join`,children:[(0,A.jsx)(`span`,{className:`session-consent-tool`,children:e.tool}),(0,A.jsx)(`span`,{className:`session-consent-seqs`,children:QG(e)}),(0,A.jsx)(`span`,{className:`session-consent-id ui-fixed`,children:e.callId})]}),e.requested!==null&&(0,A.jsx)(`div`,{className:`session-consent-said`,children:iK(e.requested,`phrase`)}),e.granted!==null&&(0,A.jsxs)(`div`,{className:`session-consent-said`,children:[`“`,iK(e.granted,`said`),`”`]}),(0,A.jsxs)(`div`,{className:`session-consent-audience`,children:[`audience `,eK(e)]}),t!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,children:t})]})}function QG(e){return e.granted===null?e.declined===null?`seq ${rK(e.requested)} asked and nothing answered`:`seq ${rK(e.declined)} declined seq ${rK(e.ran)}`:`seq ${e.granted.seq} authorised seq ${rK(e.ran)}`}function $G(e){let{granted:t,ran:n,requested:r}=e;if(t===null||n===null)return null;if(t.seq>n.seq)return`${e.tool} ran at seq ${n.seq}, before its confirm.granted at seq ${t.seq}`;let i=r===null?null:iK(r,`audience`);return i!==null&&i!==iK(t,`audience`)?`${e.tool} was confirmed by another audience than the one asked at seq ${r?.seq??0}`:null}function eK(e){let t=e.granted??e.declined??e.requested;return t===null?`—`:iK(t,`audience`)}function tK(e){return e.type===`confirm.granted`?{granted:e}:e.type===`confirm.declined`?{declined:e}:{requested:e}}function nK(e,t){return{callId:e,tool:t,requested:null,granted:null,declined:null,ran:null}}function rK(e){return e===null?`—`:String(e.seq)}function iK(e,t){let n=e.data[t];return typeof n==`string`?n:``}var aK={held:`green`,broken:`red`,deferred:`amber`,skipped:`muted`};function oK({call:e,base:t,score:n,turns:r,ended:i}){let[a,o]=(0,D.useState)(null),s=a??n;return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Score`,meta:s!==null&&s.passed!=null?`${lK(s)} of ${s.judges.length} held`:void 0}),(0,A.jsx)(`div`,{className:`ui-card-body`,children:s===null?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`session-standing session-standing-amber`,children:`Not scored yet`}),(0,A.jsxs)(`p`,{className:`session-sentence`,children:[`The call is still running, or its log was sealed before the judges existed. Ask for one with`,` `,(0,A.jsxs)(`span`,{className:`ui-fixed`,children:[`pinecall eval `,e]}),`.`]}),i&&(0,A.jsx)(dK,{call:e,onJudged:o})]}):s.passed==null?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:`session-standing session-standing-amber`,children:`No judge was given to this session`}),cK(s.not_judged)&&(0,A.jsx)(`p`,{className:`session-sentence`,children:s.not_judged}),(0,A.jsx)(`p`,{className:`session-sentence`,children:uK(s,r)}),i&&(0,A.jsx)(dK,{call:e,onJudged:o})]}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`div`,{className:s.passed?`session-standing session-standing-green`:`session-standing session-standing-red`,children:s.passed?`Passed`:`Did not pass`}),(0,A.jsxs)(`div`,{className:`session-judges`,children:[s.judges.map(n=>(0,A.jsx)(sK,{base:t,call:e,judgment:n},n.name)),(s.panel??[]).filter(e=>!s.judges.some(t=>t.name===e)).map(e=>(0,A.jsxs)(`div`,{className:`session-judge`,children:[(0,A.jsxs)(`div`,{className:`session-judge-line`,children:[(0,A.jsx)(`span`,{className:`session-judge-name`,children:e}),(0,A.jsx)(vh,{tone:`muted`,children:`on the panel`})]}),(0,A.jsx)(`div`,{className:`session-judge-reason`,children:`Was run over this call and answered nothing.`})]},e))]}),(0,A.jsx)(`p`,{className:`session-sentence`,children:uK(s,r)})]})})]})}function sK({base:e,call:t,judgment:n}){return(0,A.jsxs)(`div`,{className:`session-judge`,children:[(0,A.jsxs)(`div`,{className:`session-judge-line`,children:[(0,A.jsx)(`span`,{className:`session-judge-name`,children:n.name}),(0,A.jsx)(vh,{tone:aK[n.verdict]??`muted`,children:n.verdict}),n.evidence.seqs.map(n=>(0,A.jsxs)(k,{className:`session-seq`,to:`${e}/${t}#seq-${n}`,children:[`seq `,n]},n))]}),(0,A.jsxs)(`div`,{className:`session-judge-reason`,children:[n.reason,n.evidence.said!=null&&(0,A.jsxs)(`span`,{className:`session-judge-said`,children:[` “`,n.evidence.said,`”`]})]})]})}function cK(e){return e!=null&&e.trim().toLowerCase()!==`no judge was given to this session`}function lK(e){return e.judges.filter(e=>e.verdict===`held`).length}function uK(e,t){let n=`${t===1?`One turn`:`${t} turns`} replayed from the log`;return e.judge_calls===0?`${n}; the hard policies alone, and they cost nothing.`:`${n}; ${e.judge_calls} judge call${e.judge_calls===1?``:`s`} for ${hg(e.judge_cost_eur)}.`}function dK({call:e,onJudged:t}){let n=j(),r=Kh(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(null);if(r!==null&&!r.includes(`evals`))return null;let c=async()=>{a(!0),s(null);try{t(gv.parse(await ca(n,`/v1/evals/judge/${encodeURIComponent(e)}`,{})))}catch(e){s(e instanceof ta?e.message:String(e))}finally{a(!1)}};return(0,A.jsxs)(`div`,{className:`session-attach`,children:[(0,A.jsx)(W,{size:`md`,disabled:i,onClick:()=>void c(),children:i?`Judging…`:`Attach a judge`}),o!==null&&(0,A.jsx)(`p`,{className:`session-sentence session-refused-line`,children:o})]})}var fK={llm_node_ttft:`LLM first token`,e2e_latency:`End to end`,tts_node_ttfb:`Speech starts`,transcription_delay:`Transcription`,end_of_turn_delay:`End of turn`},pK=[`llm_node_ttft`,`e2e_latency`];function mK({rows:e}){let t=[...e.filter(e=>pK.includes(e.name)).sort((e,t)=>pK.indexOf(e.name)-pK.indexOf(t.name)),...e.filter(e=>!pK.includes(e.name))];return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Latency across this call`}),t.length===0?(0,A.jsx)(`p`,{className:`session-sentence session-latency-none`,children:`No turn in this session carried a metric — a chat session times nothing, and a voice call that dropped before its first answer has nothing to time.`}):(0,A.jsx)(`div`,{className:`session-latency`,children:t.map(e=>(0,A.jsxs)(`div`,{title:`${e.name} · median over ${e.turns} ${e.turns===1?`turn`:`turns`}`,children:[(0,A.jsx)(`div`,{className:`session-latency-label`,children:fK[e.name]??e.name}),(0,A.jsx)(`div`,{className:`session-latency-value`,children:Sw(e.seconds)}),(0,A.jsxs)(`div`,{className:`session-latency-max`,children:[`max `,Sw(e.max)]})]},e.name))})]})}var hK={"turn.user":`user`,"turn.agent":`agent`},gK=/^#seq-(\d+)$/;function _K({lines:e,turns:t}){let[n,r]=(0,D.useState)(new Set),[i,a]=(0,D.useState)(!1),o=CK(t),s=vK(gr().hash),c=e.length;(0,D.useEffect)(()=>{s!==null&&c>0&&document.getElementById(yK(s))?.scrollIntoView({block:`center`})},[s,c]);let l=e=>r(t=>{let n=new Set(t);return n.delete(e)||n.add(e),n});return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`The log`,meta:`${e.length} entries, append-only, numbered by seq`,action:(0,A.jsx)(`span`,{className:`session-log-action`,children:(0,A.jsx)(W,{size:`sm`,onClick:()=>a(!i),children:i?`Hide the fields`:`Show every field`})})}),(0,A.jsx)(`div`,{className:`session-log`,children:e.map(e=>(0,A.jsx)(bK,{line:e,turn:o.get(wK(e.entry.type,e.entry.data)),open:i||n.has(e.entry.seq),cited:e.entry.seq===s,onToggle:()=>l(e.entry.seq)},e.entry.seq))})]})}function vK(e){let t=gK.exec(e)?.[1];return t===void 0?null:Number(t)}function yK(e){return`seq-${e}`}function bK({line:e,turn:t,open:n,cited:r,onToggle:i}){let a=e.fields.length>0,o=[`session-entry`,`session-entry-${xK(e.entry.type)}`];return a&&o.push(`session-entry-opens`),r&&o.push(`session-entry-cited`),(0,A.jsxs)(`div`,{id:yK(e.entry.seq),className:o.join(` `),onClick:a?i:void 0,children:[(0,A.jsx)(`span`,{className:`session-entry-seq`,children:e.entry.seq}),(0,A.jsx)(`span`,{className:`session-entry-since`,children:e.since}),(0,A.jsxs)(`span`,{className:`session-entry-type`,children:[e.mark!==``&&(0,A.jsxs)(`span`,{className:`session-entry-mark`,children:[e.mark,` `]}),e.entry.type]}),(0,A.jsxs)(`span`,{className:`session-entry-payload`,children:[e.payload,a&&(0,A.jsxs)(`span`,{className:`session-entry-caret`,children:[` `,n?`▾`:`▸`]}),t!==void 0&&(0,A.jsx)(SK,{turn:t}),n&&(0,A.jsx)(`span`,{className:`session-fields`,children:e.fields.map(e=>(0,A.jsxs)(`span`,{className:`session-field`,children:[(0,A.jsx)(`span`,{className:`session-field-name`,children:e.name}),(0,A.jsx)(`span`,{className:`session-field-value`,children:e.value})]},e.name))})]})]})}function xK(e){return e.startsWith(`turn.`)?`turn`:e.startsWith(`state.`)?`state`:e.startsWith(`tool.`)||e.startsWith(`confirm.`)?`tool`:e.startsWith(`call.`)?`call`:`quiet`}function SK({turn:e}){return(0,A.jsx)(`span`,{className:`session-chips`,children:yw(e).map(e=>(0,A.jsxs)(`span`,{className:`session-chip`,children:[e.field,` `,(0,A.jsx)(`b`,{children:e.value})]},e.field))})}function CK(e){return new Map(e.map(e=>[`${e.role}:${e.speech_id}`,e]))}function wK(e,t){let n=t.speech_id;return`${hK[e]??``}:${typeof n==`string`?n:``}`}var TK=[`turn.user`,`turn.agent`],EK=`metrics.`,DK=`memory.ops`,OK=`docs.sources`,kK={"tool.call":`→`,"tool.result":`←`},AK=`!`;function jK(e){let t=lw(e.map(e=>e.type)),n=e[0]?.ts??0;return e.map(e=>NK(e,n,t.get(e.type)))}function MK(e,t){return`+${(e-t).toFixed(3)}`}function NK(e,t,n){return{entry:e,mark:PK(e.type),since:MK(e.ts,t),payload:FK(e,n),fields:IK(e,n)}}function PK(e){return e.startsWith(`confirm.`)?AK:kK[e]??``}function FK(e,t){return TK.includes(e.type)?uw(Object.fromEntries(Object.entries(e.data).filter(([e])=>e!==`metrics`)),t):e.type.startsWith(EK)?``:e.type===DK?qH(e.data):e.type===OK?YH(e.data):uw(e.data,t)}function IK(e,t){if(TK.includes(e.type)){let n=e.data.metrics,r=t?.properties?.metrics;return BK(n)?LK(n,EK,r):[]}return e.type.startsWith(EK)?LK(e.data,``,t):e.type===DK?JH(e.data).map(e=>({name:`fact`,value:e})):e.type===OK?XH(e.data).map(e=>({name:`source`,value:e})):[]}function LK(e,t,n){return RK(e,t,n,zK(e,n))}function RK(e,t,n,r){let i=[];for(let a of r){let r=e[a],o=n?.properties?.[a];BK(r)?i.push(...RK(r,`${t}${a}.`,o,Object.keys(r))):i.push({name:`${t}${a}`,value:dw(r,o)})}return i}function zK(e,t){let n=Object.keys(t?.properties??{}).filter(t=>t in e);return[...n,...Object.keys(e).filter(e=>!n.includes(e))]}function BK(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function VK(e){let t=j(),[n,r]=(0,D.useState)([]),[i,a]=(0,D.useState)(!0),[o,s]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let n=!1;return r([]),a(!0),s(null),(async()=>{try{let i=await $C(t,e);n||r(i)}catch(e){n||s(String(e))}finally{n||a(!1)}})(),()=>{n=!0}},[e,t]),{entries:n,reading:i,error:o}}var HK=`call.summary`;function UK(){let{agent:e=``,call:t=``}=Sr(),{entries:n,reading:r,error:i}=VK(t),a=(0,D.useMemo)(()=>({state:Zy(n),lines:jK(n),latencies:Dw(n),consented:YG(n),recording:CD(ZK(n)?.data),score:QK(n)}),[n]),o=e===``?`/sessions`:`/a/${e}/sessions`,s=lE(o),c=e===``?a.state.agent:e;return(0,A.jsxs)(Dh,{tight:!0,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsxs)(k,{to:s.to,className:`ui-back`,children:[`← `,s.name]}),(0,A.jsx)(`h1`,{className:`session-title`,children:t}),(0,A.jsx)(KG,{agent:c,call:t})]}),i!==null&&(0,A.jsx)(H,{children:(0,A.jsxs)(Qm,{children:[`That session did not load. `,(0,A.jsx)($m,{children:i})]})}),i===null&&n.length===0&&(0,A.jsx)(H,{children:(0,A.jsx)(Qm,{children:r?`Reading ${t}…`:`No call ${t} in the log.`})}),n.length>0&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(KK,{state:a.state,events:n.length}),(0,A.jsxs)(H,{pad:!0,children:[(0,A.jsx)(`div`,{className:`session-outcome-label`,children:`Outcome`}),(0,A.jsx)(`div`,{className:`session-outcome`,children:a.state.outcome??(a.state.end_reason===null?`The call is still going.`:`The call left no outcome sentence.`)})]}),(0,A.jsx)(wD,{call:t,path:a.recording}),(0,A.jsxs)(`div`,{className:`session-split`,children:[(0,A.jsx)(qK,{state:a.state}),(0,A.jsxs)(`div`,{className:`session-side`,children:[(0,A.jsx)(mK,{rows:a.latencies}),(0,A.jsx)(oK,{call:t,base:o,score:a.score,turns:a.state.turns.length,ended:a.state.status===`ended`})]})]}),a.state.cost!==null&&a.state.cost.rows.length>0&&(0,A.jsx)(JK,{cost:a.state.cost}),(0,A.jsxs)(GK,{children:[a.consented.length>0&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Consent proof`,meta:`each grant joined to the tool call it authorised`}),(0,A.jsx)(XG,{rows:a.consented})]}),Object.keys(a.state.prompt).length>0&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`The prompt, block by block`,meta:`by name, hash and length — the text never enters the log`}),(0,A.jsx)(`div`,{className:`session-prompt`,children:Object.entries(a.state.prompt).map(([e,t])=>(0,A.jsxs)(rh,{label:e,children:[(0,A.jsx)(`span`,{className:`ui-fixed session-hash`,children:t.hash}),` · `,t.chars,` chars · seq `,t.seq]},e))}),(0,A.jsxs)(`div`,{className:`session-note`,children:[(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall prompt --state`}),` prints the text offline.`]})]}),(0,A.jsx)(_K,{lines:a.lines,turns:a.state.turns})]})]})]})}var WK=/^#seq-\d+$/;function GK({children:e}){let{hash:t}=gr(),[n,r]=(0,D.useState)(()=>WK.test(t));return(0,D.useEffect)(()=>{WK.test(t)&&r(!0)},[t]),(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(H,{children:(0,A.jsxs)(`button`,{type:`button`,className:`session-details`,"aria-expanded":n,onClick:()=>r(!n),children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Details`}),(0,A.jsx)(`span`,{className:`ui-card-meta`,children:`consent, prompt blocks, the full log`}),(0,A.jsx)(`span`,{className:`session-details-caret`,children:n?`Hide ▴`:`Show ▾`})]})}),n&&e]})}function KK({state:e,events:t}){return(0,A.jsx)(`div`,{className:`session-facts`,children:(0,A.jsxs)(kh,{min:150,children:[(0,A.jsx)(Ah,{size:`fact`,label:`Agent`,value:e.agent}),(0,A.jsx)(Ah,{size:`fact`,label:`Channel`,value:e.direction===`outbound`?`${e.channel??`—`} · outbound`:e.channel??`—`}),(0,A.jsx)(Ah,{size:`fact`,label:`Started`,value:vg(e.started_at)}),(0,A.jsx)(Ah,{size:`fact`,label:`Duration`,value:e.ended_at===null?`still going`:pg(e)}),(0,A.jsx)(Ah,{size:`fact`,label:`Ended`,value:e.end_reason===null?`not yet`:e.end_reason.replace(/_/g,` `)}),(0,A.jsx)(Ah,{size:`fact`,label:`Cost`,value:hg(e.cost?.eur)}),(0,A.jsx)(Ah,{size:`fact`,label:`Turns · events`,value:`${e.turns.length} · ${t}`})]})})}function qK({state:e}){let t=XK(e);return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Transcript · ${e.turns.length} ${e.turns.length===1?`turn`:`turns`}`,meta:t===null?void 0:`with ${t}`}),e.turns.length===0?(0,A.jsx)(Qm,{children:`Nobody said anything a turn was written for.`}):(0,A.jsx)(`div`,{className:`session-turns`,children:e.turns.map((e,t)=>(0,A.jsxs)(`div`,{className:`session-turn`,children:[(0,A.jsx)(`span`,{className:e.role===`agent`?`session-who session-who-agent`:`session-who`,children:e.role===`agent`?`agent`:`caller`}),(0,A.jsxs)(`span`,{className:e.role===`agent`?`session-said session-said-agent`:`session-said`,children:[e.text,e.role===`agent`&&e.interrupted&&(0,A.jsx)(`span`,{className:`session-interrupted`,children:` · interrupted`})]})]},`${t}:${e.role}:${e.speech_id}`))})]})}function JK({cost:e}){return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Cost by model`,children:(0,A.jsx)(`span`,{className:`session-total`,children:hg(e.eur)})}),(0,A.jsx)(`div`,{children:e.rows.map(e=>(0,A.jsxs)(`div`,{className:`session-cost`,children:[(0,A.jsxs)(`span`,{className:`session-cost-model`,children:[e.model,` `,(0,A.jsxs)(`span`,{className:`session-cost-kind`,children:[`· `,e.unit.replace(/_/g,` `)]})]}),(0,A.jsx)(`span`,{className:`session-cost-units`,children:YK(e.quantity)}),(0,A.jsx)(`span`,{className:`session-cost-eur`,children:hg(e.eur)})]},`${e.provider}/${e.model}/${e.unit}`))}),(0,A.jsxs)(`div`,{className:`session-note`,children:[`EUR at `,e.rate.usd_to_eur,` per USD, as of `,e.rate.as_of,e.unpriced.length>0&&` · unpriced: ${e.unpriced.map(e=>`${e.provider}/${e.model}`).join(`, `)}`]})]})}function YK(e){let[t,n]=String(Math.round(e*100)/100).split(`.`),r=(t??``).replace(/\B(?=(\d{3})+(?!\d))/g,` `);return n===void 0?r:`${r}.${n}`}function XK(e){let t=e.caller?.name;if(t!=null&&t!==``)return t;let n=e.direction===`outbound`?e.to:e.from;return n===null?null:n.startsWith(`+`)?Eg(n):n}function ZK(e){return[...e].reverse().find(e=>e.type===HK)}function QK(e){let t=[...e].reverse().find(e=>e.type===ny);return t===void 0?null:gv.parse(t.data)}var $K=e=>`/v1/personas${e===void 0?``:`/${encodeURIComponent(e)}`}`;async function eq(e){return Jy.parse(await oa(e,$K())).personas}async function tq(e,t,n){return Jy.parse(await sa(e,$K(t),n)).personas}async function nq(e,t){return Jy.parse(await la(e,$K(t))).personas}async function rq(e,t,n={}){let r={...n.before===void 0?{}:{before:n.before},...n.limit===void 0?{}:{limit:n.limit}};return Yy.parse(await oa(e,`${$K(t)}/runs`,r))}var iq=/^[a-z0-9]+(?:-[a-z0-9]+)*$/;function aq({was:e,onSaved:t,onCancel:n}){let r=j(),[i,a]=(0,D.useState)(e?.name??``),[o,s]=(0,D.useState)(()=>e===void 0?{about:``,goal:``,style:``,facts:{}}:{about:e.about,goal:e.goal,style:e.style,facts:e.facts}),[c,l]=(0,D.useState)(()=>{let e=Object.entries(o.facts??{});return e.length>0?e:[[``,``]]}),[u,d]=(0,D.useState)(!1),[f,p]=(0,D.useState)(null),m=(e,t)=>s({...o,[e]:t}),h=(e,t)=>l(c.map((n,r)=>r===e?t:n)),g=iq.test(i),_=g&&o.goal.trim()!==``&&o.style.trim()!==``,v=async()=>{d(!0),p(null);try{let n=Object.fromEntries(c.filter(([e])=>e.trim()!==``).map(([e,t])=>[e.trim(),t.trim()])),a={...o,facts:n,state:e?.state??{},...e===void 0||e.name===i?{}:{was:e.name}};t(await tq(r,i,a),i)}catch(e){p(e instanceof ta?e.message:String(e))}finally{d(!1)}};return(0,A.jsxs)(`form`,{className:`psn-doc psn-form`,onSubmit:e=>{e.preventDefault(),_&&v()},children:[(0,A.jsx)(`header`,{className:`psn-doc-head`,children:(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`h1`,{className:`psn-doc-name`,children:e===void 0?`New persona`:`Editing ${e.name}`}),(0,A.jsxs)(`p`,{className:`psn-doc-about`,children:[`Kept by the gateway, one list for the whole org: for this console and for `,(0,A.jsxs)(`code`,{children:[`pinecall simulate --persona `,i||`<name>`]}),`.`]})]})}),(0,A.jsxs)(oq,{title:`Name`,hint:`What pinecall simulate --persona takes, and how the list names them. Lower-case words joined by hyphens.`,children:[(0,A.jsx)(G,{value:i,spellCheck:!1,"aria-label":`Name`,placeholder:`price-shopper`,onChange:e=>a(e.target.value.toLowerCase().replace(/\s+/g,`-`))}),i!==``&&!g&&(0,A.jsx)(`p`,{className:`psn-bad`,children:`Only a–z, 0–9 and single hyphens between words.`})]}),(0,A.jsx)(oq,{title:`Who they are`,hint:`One line for people reading the list. The model is not told it.`,children:(0,A.jsx)(G,{value:o.about??``,"aria-label":`Who they are`,placeholder:`A landlord who only wants a number`,onChange:e=>m(`about`,e.target.value)})}),(0,A.jsx)(oq,{title:`What they want`,hint:`The goal the model pursues on every turn. Say it the way the caller would: specific, with the deadline if there is one.`,children:(0,A.jsx)(lh,{rows:3,value:o.goal,"aria-label":`What they want`,placeholder:`get a price for a deep clean of a three bedroom house before Friday`,onChange:e=>m(`goal`,e.target.value)})}),(0,A.jsx)(oq,{title:`How they talk`,hint:`The manner, not the content: hurried, polite, suspicious, switches into Spanish, answers only what is asked.`,children:(0,A.jsx)(lh,{rows:2,value:o.style,"aria-label":`How they talk`,placeholder:`blunt, impatient, keeps asking for the price`,onChange:e=>m(`style`,e.target.value)})}),(0,A.jsx)(oq,{title:`What they know about themselves`,hint:`The only facts they may state — asked for anything else, they say they do not know. One per row: what it is, and what they say.`,children:(0,A.jsxs)(`div`,{className:`psn-fact-rows`,children:[c.map(([e,t],n)=>(0,A.jsxs)(`div`,{className:`psn-fact-row`,children:[(0,A.jsx)(G,{size:`sm`,value:e,placeholder:`their phone`,"aria-label":`what it is`,onChange:e=>h(n,[e.target.value,t])}),(0,A.jsx)(G,{size:`sm`,value:t,placeholder:`305 555 0101`,"aria-label":`what they say`,onChange:t=>h(n,[e,t.target.value])}),(0,A.jsx)(`button`,{type:`button`,className:`psn-x`,"aria-label":`remove this fact`,onClick:()=>l(c.filter((e,t)=>t!==n)),children:`×`})]},n)),(0,A.jsx)(`button`,{type:`button`,className:`psn-add`,onClick:()=>l([...c,[``,``]]),children:`+ Add a fact`})]})}),(0,A.jsxs)(`footer`,{className:`psn-form-foot`,children:[(0,A.jsx)(W,{type:`submit`,kind:`primary`,disabled:!_||u,children:u?`Saving…`:e===void 0?`Create persona`:`Save`}),(0,A.jsx)(W,{type:`button`,onClick:n,children:`Cancel`}),!_&&(0,A.jsx)(`span`,{className:`psn-form-need`,children:`A name, what they want and how they talk are needed.`})]}),f!==null&&(0,A.jsx)(`p`,{className:`psn-refused`,children:f})]})}function oq({title:e,hint:t,children:n}){return(0,A.jsxs)(`div`,{className:`psn-field`,children:[(0,A.jsxs)(`div`,{className:`psn-field-words`,children:[(0,A.jsx)(`span`,{className:`psn-sec-title`,children:e}),(0,A.jsx)(`span`,{className:`psn-sec-hint`,children:t})]}),(0,A.jsx)(`div`,{className:`psn-field-input`,children:n})]})}function sq({persona:e,onEdit:t,onDropped:n}){let r=j(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(!1),[c,l]=(0,D.useState)(null),u=Object.entries(e.facts),d=async()=>{if(!o){s(!0),a(!1),l(null);try{n(await nq(r,e.name))}catch(e){l(e instanceof ta?e.message:String(e)),s(!1)}}};return(0,A.jsxs)(`article`,{className:`psn-doc`,children:[(0,A.jsxs)(`header`,{className:`psn-doc-head`,children:[(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`h1`,{className:`psn-doc-name`,children:e.name}),e.about!==``&&(0,A.jsx)(`p`,{className:`psn-doc-about`,children:e.about})]}),(0,A.jsxs)(`div`,{className:`psn-doc-actions`,children:[(0,A.jsx)(ah,{kind:`primary`,size:`sm`,to:`/simulations?persona=${encodeURIComponent(e.name)}`,children:`Use in a simulation`}),(0,A.jsx)(W,{size:`sm`,onClick:t,children:`Edit`}),(0,A.jsx)(W,{size:`sm`,kind:`danger`,disabled:o,onClick:()=>i?void d():a(!0),onBlur:()=>a(!1),children:o?`Deleting…`:i?`Delete · sure?`:`Delete`})]})]}),(0,A.jsx)(cq,{title:`What they want`,hint:`The goal the model pursues on every turn, until it has it or sees it will not.`,children:(0,A.jsx)(`p`,{className:`psn-doc-text`,children:e.goal})}),(0,A.jsx)(cq,{title:`How they talk`,hint:`The manner: hurried, polite, switching language mid-sentence. It shapes every line, not what they ask for.`,children:(0,A.jsx)(`p`,{className:`psn-doc-text`,children:e.style})}),(0,A.jsx)(cq,{title:`What they know about themselves`,hint:`The only facts they may state. Asked for anything else, they say they do not know — they never invent.`,children:u.length===0?(0,A.jsx)(`p`,{className:`psn-doc-none`,children:`Nothing: this caller states no fact about themselves.`}):(0,A.jsx)(`dl`,{className:`psn-facts`,children:u.map(([e,t])=>(0,A.jsxs)(`div`,{className:`psn-fact`,children:[(0,A.jsx)(`dt`,{children:e}),(0,A.jsx)(`dd`,{children:t})]},e))})}),(0,A.jsx)(`footer`,{className:`psn-doc-foot`,children:(0,A.jsxs)(`span`,{className:`psn-doc-note`,children:[e.author===``?`Kept by the gateway.`:`Last written by ${e.author}, ${vg(e.set_at)}.`,Object.keys(e.state).length>0&&` It opens the call in a state, written from a project.`]})}),c!==null&&(0,A.jsx)(`p`,{className:`psn-refused`,children:c})]})}function cq({title:e,hint:t,children:n}){return(0,A.jsxs)(`section`,{className:`psn-sec`,children:[(0,A.jsx)(`h2`,{className:`psn-sec-title`,children:e}),(0,A.jsx)(`p`,{className:`psn-sec-hint`,children:t}),n]})}var lq=5;function uq(e){let t=j(),[n,r]=(0,D.useState)({by:{},read:!1}),i=e===null?null:e.join(`\0`);return(0,D.useEffect)(()=>{if(i===null)return;if(i===``){r({by:{},read:!0});return}let e=!1;return r({by:{},read:!1}),Promise.all(i.split(`\0`).map(async e=>{try{let n=await rq(t,e,{limit:lq});return[e,{total:n.total,newest:n.runs}]}catch{return null}})).then(t=>{e||r({by:Object.fromEntries(t.filter(e=>e!==null)),read:!0})}),()=>{e=!0}},[t,i]),n}var dq=`minmax(0,1fr) minmax(0,1fr) 92px 70px 104px`,fq=12;function pq({personas:e,onNew:t}){let n=uq(e.map(e=>e.name)),r=gq(n.by),i=Object.values(n.by).reduce((e,t)=>e+t.total,0),a=e.filter(e=>n.by[e.name]?.total===0),o=r[0];return e.length===0?(0,A.jsx)(mq,{onNew:t}):(0,A.jsxs)(Dh,{children:[(0,A.jsx)(Oh,{title:`Personas`,lede:(0,A.jsxs)(A.Fragment,{children:[`The synthetic callers this org keeps, whichever agent answers them. A model plays one and improvises every line — in Simulations, or in`,` `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall simulate`}),`.`]})}),(0,A.jsxs)(kh,{min:170,children:[(0,A.jsx)(Ah,{label:`Callers`,value:e.length,of:a.length===0?void 0:`· ${a.length} never called`}),(0,A.jsx)(Ah,{label:`Runs`,value:n.read?i:`—`}),(0,A.jsx)(Ah,{label:`Last run`,value:o===void 0?`—`:bg(o.started_at),of:o===void 0?void 0:`· ${o.agent}`}),(0,A.jsx)(Ah,{label:`On a call`,value:r.filter(e=>e.ended_at===null).length})]}),(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Latest runs`,meta:`newest first, whichever caller — a row opens the session`}),n.read&&r.length===0&&(0,A.jsxs)(Qm,{children:[`No caller has been put on an agent yet. `,(0,A.jsx)(k,{to:`/simulations`,children:`Simulations`}),` calls one, and `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall simulate --persona`}),` does the same from a terminal.`]}),r.length>0&&(0,A.jsx)(jh,{columns:dq,padding:`9px 16px`,labels:[`Caller`,`Agent`,`When`,`Turns>`,`How it went`]}),r.slice(0,fq).map(e=>(0,A.jsxs)(Mh,{columns:dq,to:`/sessions/${e.call}`,children:[(0,A.jsx)(`span`,{className:`psn-over-name`,children:e.persona}),(0,A.jsx)(`span`,{className:`psn-over-goal`,children:e.agent}),(0,A.jsx)(`span`,{className:`psn-over-when`,children:bg(e.started_at)}),(0,A.jsx)(`span`,{className:`psn-over-count`,children:e.turns}),(0,A.jsx)(`span`,{children:(0,A.jsx)(hq,{run:e})})]},e.call))]}),a.length>0&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Never called`,meta:`written, and still only a description`}),a.map(e=>(0,A.jsx)(th,{name:e.name,sub:e.goal,to:`/simulations?persona=${encodeURIComponent(e.name)}`,end:(0,A.jsx)(`span`,{className:`psn-over-when`,children:`Call an agent as them →`})},e.name))]})]})}function mq({onNew:e}){return(0,A.jsxs)(Dh,{children:[(0,A.jsx)(Oh,{title:`Personas`,lede:`A persona is somebody who calls this business wanting something: a goal, a manner, and the few facts they may state about themselves. A model plays them against an agent and improvises every line — there is no script to write.`,ledeWidth:640,actions:(0,A.jsx)(W,{kind:`primary`,size:`base`,onClick:e,children:`New persona`})}),(0,A.jsx)(H,{children:(0,A.jsx)(Qm,{children:`No callers yet. The first one takes a minute: what they want, how they talk, and what they know about themselves.`})})]})}function hq({run:e}){return e.ended_at===null?(0,A.jsx)(vh,{tone:`green`,small:!0,children:`on a call`}):e.score===null?(0,A.jsxs)(`span`,{className:`psn-over-when`,children:[pg(e),` · not judged`]}):(0,A.jsxs)(vh,{tone:e.score.passed?`green`:`red`,small:!0,children:[e.score.passed?`held`:`broke`,` `,String(e.score.held),`/`,String(e.score.judged)]})}function gq(e){return Object.entries(e).flatMap(([e,t])=>t.newest.map(t=>({...t,persona:e}))).sort((e,t)=>t.started_at-e.started_at)}function _q({personas:e,asking:t,open:n,onNew:r}){return(0,A.jsxs)(`aside`,{className:`psn-side`,"aria-label":`the org's personas`,children:[(0,A.jsxs)(`div`,{className:`psn-side-head`,children:[(0,A.jsxs)(`div`,{className:`psn-titles`,children:[(0,A.jsx)(`span`,{className:`psn-title`,children:`Personas`}),(0,A.jsx)(`span`,{className:`psn-count`,children:e===null?``:e.length})]}),(0,A.jsxs)(`p`,{className:`psn-lede`,children:[`The callers a model plays against your agents, in Simulations and in `,(0,A.jsx)(`code`,{children:`pinecall simulate`}),`.`]}),(0,A.jsx)(W,{size:`sm`,kind:`primary`,onClick:r,children:`New persona`})]}),(0,A.jsxs)(`div`,{className:`psn-list`,children:[e?.map(e=>(0,A.jsxs)(k,{to:`/personas/${encodeURIComponent(e.name)}`,className:e.name===n?`psn-row psn-row-on`:`psn-row`,children:[(0,A.jsx)(`span`,{className:`psn-row-top`,children:(0,A.jsx)(`span`,{className:`psn-row-name`,children:e.name})}),(0,A.jsx)(`span`,{className:`psn-row-sub`,children:e.about===``?e.goal:e.about})]},e.name)),e!==null&&e.length===0&&t===null&&(0,A.jsx)(`p`,{className:`psn-empty`,children:`No callers yet. Write the first one: somebody who calls this business wanting something.`}),e===null&&(0,A.jsx)(`p`,{className:`psn-empty`,children:t??`Asking the gateway…`})]}),t!==null&&e!==null&&(0,A.jsx)(`p`,{className:`psn-empty psn-bad`,children:t}),(0,A.jsxs)(`p`,{className:`psn-foot`,children:[`Kept by the gateway, one list for the whole org: the same callers the console and `,(0,A.jsx)(`code`,{children:`pinecall simulate`}),` use, whichever agent they are put on.`]})]})}function vq(e){let t=j(),[n,r]=(0,D.useState)(null),[i,a]=(0,D.useState)(0),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(!0),[u,d]=(0,D.useState)(null),f=e=>e instanceof Error?e.message:String(e);(0,D.useEffect)(()=>{let n=!1;return r(null),a(0),s(null),l(!0),d(null),rq(t,e).then(e=>{n||(r(e.runs),a(e.total),s(e.next),l(!1))},e=>{n||(d(f(e)),l(!1))}),()=>{n=!0}},[t,e]);let p=(0,D.useCallback)(()=>{o!==null&&(l(!0),d(null),rq(t,e,{before:o}).then(e=>{r(t=>[...t??[],...e.runs]),a(e.total),s(e.next),l(!1)},e=>{d(f(e)),l(!1)}))},[t,e,o]);return{runs:n,total:i,asking:c,error:u,more:o===null?null:p}}function yq({persona:e}){let{runs:t,total:n,asking:r,error:i,more:a}=vq(e.name);return(0,A.jsxs)(`aside`,{className:`psn-runs`,"aria-label":`what ${e.name} has done`,children:[(0,A.jsxs)(`div`,{className:`psn-runs-head`,children:[(0,A.jsxs)(`div`,{className:`psn-titles`,children:[(0,A.jsx)(`span`,{className:`psn-title`,children:`Runs`}),(0,A.jsx)(`span`,{className:`psn-count`,children:t===null?``:n})]}),(0,A.jsx)(`p`,{className:`psn-lede`,children:`Every simulation this caller has run, newest first. A row opens the session it was.`})]}),(0,A.jsxs)(`div`,{className:`psn-runs-list`,children:[t?.map(e=>(0,A.jsx)(bq,{run:e},e.call)),t!==null&&t.length===0&&!r&&(0,A.jsxs)(`p`,{className:`psn-empty`,children:[`Nobody has called as `,e.name,` yet. Put them on an agent in `,(0,A.jsx)(k,{to:`/simulations?persona=${encodeURIComponent(e.name)}`,children:`Simulations`}),`, or run `,(0,A.jsxs)(`code`,{children:[`pinecall simulate --persona `,e.name]}),`.`]}),t===null&&r&&(0,A.jsx)(`p`,{className:`psn-empty`,children:`Asking the gateway…`}),a!==null&&(0,A.jsx)(`div`,{className:`psn-runs-more`,children:(0,A.jsx)(W,{size:`sm`,disabled:r,onClick:a,children:r?`Reading…`:`Show more (${String(n-(t?.length??0))} older)`})})]}),i!==null&&(0,A.jsx)(`p`,{className:`psn-empty psn-bad`,children:i})]})}function bq({run:e}){let t=e.ended_at===null;return(0,A.jsxs)(k,{to:`/sessions/${e.call}`,className:`psn-run`,children:[(0,A.jsxs)(`span`,{className:`psn-run-top`,children:[(0,A.jsx)(`span`,{className:`psn-run-agent`,children:e.agent}),t&&(0,A.jsx)(bh,{tone:`green`,small:!0}),(0,A.jsx)(`span`,{className:`psn-run-when`,children:bg(e.started_at)})]}),(0,A.jsxs)(`span`,{className:`psn-run-marks`,children:[(0,A.jsx)(xq,{run:e}),(0,A.jsxs)(`span`,{className:`psn-run-fact`,children:[String(e.turns),` `,e.turns===1?`turn`:`turns`]}),!t&&(0,A.jsx)(`span`,{className:`psn-run-fact`,children:pg(e)}),e.cost_eur!==null&&(0,A.jsx)(`span`,{className:`psn-run-fact`,children:hg(e.cost_eur)})]}),e.outcome!==null&&(0,A.jsx)(`span`,{className:`psn-run-outcome`,children:e.outcome}),e.score?.passed===!1&&e.score.reason!==null&&(0,A.jsx)(`span`,{className:`psn-run-broke`,children:e.score.reason})]})}function xq({run:e}){return e.ended_at===null?(0,A.jsx)(vh,{tone:`green`,small:!0,children:`on a call`}):e.score===null?(0,A.jsx)(vh,{tone:`muted`,small:!0,children:e.end_reason===null?`not judged`:e.end_reason.replace(/_/g,` `)}):(0,A.jsxs)(vh,{tone:e.score.passed?`green`:`red`,small:!0,children:[e.score.passed?`held`:`broke`,` `,String(e.score.held),`/`,String(e.score.judged)]})}function Sq(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)(null);return(0,D.useEffect)(()=>{let t=!1;return i(`Asking the gateway…`),eq(e).then(e=>{t||(n(e),i(null))},e=>{t||i(e instanceof Error?e.message:String(e))}),()=>{t=!0}},[e]),{personas:t,asking:r,setPersonas:n}}function Cq(){let e=Sr().call,[t]=Yi(),n=vr(),r=Rh({name:`personas.list`,initial:320,min:260,max:480,side:`left`}),i=Rh({name:`personas.runs`,initial:340,min:280,max:560,side:`right`}),{personas:a,asking:o,setPersonas:s}=Sq(),c=t.get(`new`)===`1`,l=t.get(`edit`)===`1`,u=e??t.get(`persona`)??void 0,d=a?.find(e=>e.name===u),f=d!==void 0&&!c&&!l?d:null,p=(e,t=``)=>{let r=t===``?``:`?${t}=1`;n(`/personas${e===null?``:`/${encodeURIComponent(e)}`}${r}`)},m=(e,t)=>{s(e),p(t)};return(0,A.jsxs)(`div`,{className:`psn`,style:r.style,children:[r.handle,(0,A.jsx)(_q,{personas:a,asking:o,open:d?.name,onNew:()=>p(null,`new`)}),(0,A.jsxs)(`div`,{className:f===null?`psn-right`:`psn-right psn-right-runs`,style:i.style,children:[f!==null&&i.handle,(0,A.jsx)(`main`,{className:`psn-main`,children:c?(0,A.jsx)(aq,{was:void 0,onSaved:m,onCancel:()=>p(u??null)},`new`):d===void 0?(0,A.jsx)(pq,{personas:a??[],onNew:()=>p(null,`new`)}):l?(0,A.jsx)(aq,{was:d,onSaved:m,onCancel:()=>p(d.name)},d.name):(0,A.jsx)(sq,{persona:d,onEdit:()=>p(d.name,`edit`),onDropped:e=>{s(e),p(null)}},d.name)}),f!==null&&(0,A.jsx)(yq,{persona:f},f.name)]})]})}var wq=z({call:P()});async function Tq(e,t){return wq.parse(await wC(e,t.agent,`simulate.start`,t)).call}var Eq=6,Dq=15,Oq=0;function kq({agents:e,agent:t,onAgent:n,personas:r,asking:i,preferred:a,onStarted:o}){let s=j(),[c,l]=(0,D.useState)(``),[u,d]=(0,D.useState)(!0),[f,p]=(0,D.useState)(!1),[m,h]=(0,D.useState)(Eq),[g,_]=(0,D.useState)(Dq),[v,y]=(0,D.useState)(Oq),[b,x]=(0,D.useState)(!1),[S,C]=(0,D.useState)(!1),[w,T]=(0,D.useState)(null),ee=r?.map(e=>e.name).join(`
106
+ `)??``;(0,D.useEffect)(()=>{let e=ee===``?[]:ee.split(`
107
+ `);e.includes(c)||l(a!==void 0&&e.includes(a)?a:e[0]??``)},[ee,c,a]);let te=r?.find(e=>e.name===c),ne=jq(r),re=async e=>{e.preventDefault(),C(!0),T(null);try{o(await Tq(s,{agent:t,persona:c,voice:u,judge:f,turns:m,...u&&b?{background_noise:g,packet_loss:v}:{}}),t,u)}catch(e){T(e instanceof ta?e.message:String(e))}finally{C(!1)}};return(0,A.jsxs)(`form`,{className:`sim`,onSubmit:e=>void re(e),children:[(0,A.jsx)(`div`,{className:`sim-head`,children:(0,A.jsx)(`span`,{className:`sim-title`,children:`Simulate a caller`})}),e.length>0&&(0,A.jsx)(uh,{label:`Agent`,children:(0,A.jsx)(ch,{size:`sm`,"aria-label":`Agent`,value:t,onChange:e=>n(e.target.value),children:e.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),r===null&&i!==null&&(0,A.jsx)(`p`,{className:`sim-note`,children:i}),ne!==null&&(0,A.jsx)(`p`,{className:`sim-note`,children:ne}),r!==null&&ne===null&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(uh,{label:(0,A.jsxs)(`span`,{className:`sim-label-row`,children:[`Persona`,(0,A.jsx)(k,{className:`sim-manage`,to:`/personas?agent=${encodeURIComponent(t)}${c===``?``:`&persona=${encodeURIComponent(c)}`}`,children:`Manage`})]}),children:(0,A.jsx)(ch,{size:`sm`,"aria-label":`Persona`,value:c,onChange:e=>l(e.target.value),children:r.map(e=>(0,A.jsx)(`option`,{value:e.name,children:e.name},e.name))})}),te!==void 0&&(0,A.jsxs)(`p`,{className:`sim-note`,children:[`Goal: `,te.goal]}),(0,A.jsxs)(`div`,{className:`sim-pair`,children:[(0,A.jsxs)(uh,{label:`Max turns`,children:[(0,A.jsx)(G,{size:`sm`,type:`number`,"aria-label":`Max turns`,min:1,max:30,value:m,onChange:e=>h(Number(e.target.value))}),(0,A.jsx)(`p`,{className:`sim-aside sim-under`,children:`the lines the caller says; the agent answers each one`})]}),u&&b&&(0,A.jsx)(uh,{label:`Noise, dB under`,children:(0,A.jsx)(G,{size:`sm`,type:`number`,"aria-label":`Noise, dB under`,min:0,max:60,value:g,onChange:e=>_(Number(e.target.value))})}),u&&b&&(0,A.jsx)(uh,{label:`Packets lost, %`,children:(0,A.jsx)(G,{size:`sm`,type:`number`,"aria-label":`Packets lost, %`,min:0,max:100,value:v,onChange:e=>y(Number(e.target.value))})})]}),(0,A.jsxs)(`div`,{className:`sim-checks`,children:[(0,A.jsx)(Aq,{on:u,onChange:d,name:`Voice`,says:`a real line, and you can listen`}),(0,A.jsx)(Aq,{on:f,onChange:p,name:`Judge at hang-up`,says:`the panel scores the call the moment it ends`}),u&&(0,A.jsx)(Aq,{on:b,onChange:x,name:`Noisy line`,says:`a TV behind the caller, packets lost`})]}),(0,A.jsx)(W,{type:`submit`,kind:`primary`,size:`md`,disabled:S||c===``,children:S?`Calling…`:`Call the agent`})]}),w!==null&&(0,A.jsx)(`p`,{className:`sim-refused`,children:w})]})}function Aq({on:e,onChange:t,name:n,says:r}){return(0,A.jsxs)(`div`,{className:`sim-check`,children:[(0,A.jsx)(hh,{checked:e,onChange:t,children:n}),(0,A.jsx)(`p`,{className:`sim-aside`,children:r})]})}function jq(e){return e===null?null:e.length===0?`No personas yet: write the first caller in Personas.`:null}function Mq(){let{agents:e}=wb(),t=Sr().call,[n]=Yi(),r=vr(),i=Rh({name:`simulations.form`,initial:340,min:280,max:520,side:`left`}),a=n.get(`agent`)??void 0,o=n.get(`spoken`)===`1`,s=n.get(`persona`)??void 0,c=e.map(e=>e.slug),l=a??c[0]??``,u=e=>void r(`/simulations?agent=${encodeURIComponent(e)}`),{personas:d,asking:f}=Sq();return(0,A.jsxs)(`div`,{className:`sims`,style:i.style,children:[i.handle,(0,A.jsxs)(`aside`,{className:`sims-side`,"aria-label":`start a simulation`,children:[e.length===0?(0,A.jsx)(`p`,{className:`sims-note`,children:"No agent is held here yet: run `pinecall start` in the agent's directory, and it shows up to simulate against."}):(0,A.jsx)(A.Fragment,{children:(0,A.jsx)(kq,{agents:c,agent:l,onAgent:u,personas:d,asking:f,preferred:s,onStarted:(e,t,n)=>{let i=new URLSearchParams({agent:t,...n?{spoken:`1`}:{}});r(`/simulations/${e}?${i.toString()}`)}})}),(0,A.jsx)(`p`,{className:`sims-note`,children:`A model plays the persona against the agent, improvising every line from its goal, its manner and its own facts. With Voice on, the call is a real line and you hear both of them here as it happens.`})]}),t===void 0?(0,A.jsx)(`div`,{className:`sims-nothing`,children:`Pick an agent and a persona, then call. The simulation opens here, and you hear it live.`}):(0,A.jsxs)(`div`,{className:`sims-watch`,children:[o&&(0,A.jsx)(Fq,{call:t}),(0,A.jsx)(yU,{call:t,agent:a})]},t)]})}var Nq=1e3,Pq=30;function Fq({call:e}){let t=TH(e),n=(0,D.useRef)(0),r=(0,D.useRef)(!1);(0,D.useEffect)(()=>{if(t.listening===`off`&&!r.current&&n.current===0&&(n.current=1,t.join()),t.listening===`failed`&&!r.current&&n.current<Pq){let e=window.setTimeout(()=>{n.current+=1,t.join()},Nq);return()=>window.clearTimeout(e)}t.listening===`muted`&&!r.current&&(r.current=!0,t.hear(!0))},[t]);let i=(()=>{switch(t.listening){case`on`:return`Listening live · the caller and the agent`;case`muted`:return`Muted`;case`joining`:return`Joining the call…`;case`failed`:return n.current<Pq?`Waiting for the call's room to open…`:`Could not join the call: ${t.error??`no room`}`;case`off`:return r.current?`The call is over`:`Joining the call…`}})();return(0,A.jsxs)(`div`,{className:`sims-ear`,role:`status`,children:[(0,A.jsx)(`span`,{className:t.listening===`on`?`sims-ear-dot sims-ear-dot-on`:`sims-ear-dot`}),(0,A.jsx)(`span`,{className:`sims-ear-said`,children:i}),t.listening===`on`&&(0,A.jsx)(W,{size:`sm`,pill:!0,onClick:()=>t.hear(!1),children:`Mute`}),t.listening===`muted`&&(0,A.jsx)(W,{size:`sm`,pill:!0,onClick:()=>t.hear(!0),children:`Unmute`})]})}var Iq=``,Lq=[`2`,`4`,`6`,`8`,`12`,`16`],Rq=[`0.2`,`0.3`,`0.4`,`0.5`,`0.6`,`0.7`];function zq(e,t){return e===``||t.includes(e)?t:[e,...t]}function Bq({rows:e,offered:t,onChange:n}){let r=new Set(e.map(e=>e.base)),i=(t??[]).filter(e=>!r.has(e.base)),a=(t,r)=>n(e.map((e,n)=>n===t?r:e)),o=t=>n(e.filter((e,n)=>n!==t));return(0,A.jsxs)(`section`,{className:`set-section`,children:[(0,A.jsxs)(`div`,{className:`set-section-head`,children:[(0,A.jsx)(`h2`,{className:`set-section-title`,children:`Bases`}),(0,A.jsx)(`p`,{className:`set-section-blurb`,children:"The documents the agent searches on every turn, by the name each folder was pushed under. A base is pushed from a project with `pinecall docs push`; the Docs tab lists them."})]}),e.length===0?(0,A.jsx)(`p`,{className:`set-help`,children:`Nothing attached: the agent answers from what it knows by heart and from its tools alone. Attach one below, and every turn searches it before the model speaks.`}):(0,A.jsxs)(`div`,{className:`set-bases`,children:[(0,A.jsxs)(`div`,{className:`set-bases-head`,children:[(0,A.jsx)(`span`,{children:`Base`}),(0,A.jsx)(`span`,{children:`Chunks a turn reads`}),(0,A.jsx)(`span`,{children:`Searched by`}),(0,A.jsx)(`span`,{children:`Least score kept`}),(0,A.jsx)(`span`,{})]}),e.map((e,n)=>(0,A.jsxs)(`div`,{className:`set-bases-row`,children:[(0,A.jsxs)(ch,{value:e.base,"aria-label":`Base`,onChange:t=>a(n,{...e,base:t.target.value}),children:[(t??[]).some(t=>t.base===e.base)?null:(0,A.jsxs)(`option`,{value:e.base,children:[e.base,` · not pushed in this world`]}),(t??[]).map(t=>(0,A.jsxs)(`option`,{value:t.base,disabled:t.base!==e.base&&r.has(t.base),children:[t.base,` · `,t.chunks,` chunks`]},t.base))]}),(0,A.jsxs)(ch,{value:e.k,"aria-label":`Chunks a turn reads`,onChange:t=>a(n,{...e,k:t.target.value}),children:[(0,A.jsx)(`option`,{value:``,children:`Runtime default · 8`}),zq(e.k,Lq).map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]}),(0,A.jsxs)(ch,{value:e.mode,"aria-label":`Searched by`,onChange:t=>a(n,{...e,mode:t.target.value===`tool`?`tool`:`retrieved`}),children:[(0,A.jsx)(`option`,{value:`retrieved`,children:`The platform, before every turn`}),(0,A.jsx)(`option`,{value:`tool`,children:`The model, when it decides`})]}),(0,A.jsxs)(ch,{value:e.min_score,"aria-label":`Least score kept`,onChange:t=>a(n,{...e,min_score:t.target.value}),children:[(0,A.jsx)(`option`,{value:``,children:`Keep them all`}),zq(e.min_score,Rq).map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]}),(0,A.jsx)(W,{size:`xs`,onClick:()=>o(n),children:`Detach`})]},`${e.base}-${n}`))]}),e.length>1&&(0,A.jsxs)(`p`,{className:`set-help`,children:[`Several bases are one search, not several: they are read together and ranked against each other, so a collection with nothing to say about the question takes none of the turn's chunks. The turn is handed the most generous `,(0,A.jsx)(`strong`,{children:`chunks a turn reads`}),` of the rows above, and each `,(0,A.jsx)(`strong`,{children:`least score kept`}),` is read against the base that set it.`]}),(0,A.jsx)(`div`,{className:`set-row`,children:(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(sh,{children:`Attach a base`}),(0,A.jsxs)(ch,{value:Iq,"aria-label":`Attach a base`,disabled:i.length===0,onChange:t=>t.target.value!==Iq&&n([...e,{base:t.target.value,k:``,mode:`retrieved`,min_score:``}]),children:[(0,A.jsx)(`option`,{value:Iq,children:t===null?`Asking the gateway…`:i.length===0?`Every pushed base is attached`:`Pick one…`}),i.map(e=>(0,A.jsxs)(`option`,{value:e.base,children:[e.base,` · `,e.chunks,` chunks`]},e.base))]}),(0,A.jsx)(`p`,{className:`set-help`,children:`Only bases pushed in this world appear. A base a colleague pushed to their own corner is theirs until they push it for the team.`})]})})]})}var Vq=[{value:`say`,label:`Say these words`},{value:`reply`,label:`Let the model open`}],Hq=[`500`,`700`,`1000`,`1500`,`2000`,`3000`],Uq=[`1`,`2`,`3`,`4`,`5`];function Wq({typed:e,wordsOnly:t,change:n}){return(0,A.jsxs)(`section`,{className:`set-section`,children:[(0,A.jsxs)(`div`,{className:`set-section-head`,children:[(0,A.jsx)(`h2`,{className:`set-section-title`,children:`Conversation`}),(0,A.jsx)(`p`,{className:`set-section-blurb`,children:`The first thing a caller hears, when the agent may hang up, and how quickly a turn is cut.`})]}),(0,A.jsxs)(`div`,{className:`set-field set-wide`,children:[(0,A.jsx)(sh,{children:`Opening`}),!t&&(0,A.jsx)(dh,{options:Vq,value:e.opening,onChange:e=>n(`opening`,e)}),e.opening===`say`||t?(0,A.jsx)(lh,{value:e.say,rows:2,"aria-label":`Opening`,placeholder:`The exact words the caller hears first`,onChange:e=>n(`say`,e.target.value)}):(0,A.jsx)(lh,{value:e.reply,rows:2,"aria-label":`Opening`,placeholder:`What the model is told about how to open the call`,onChange:e=>n(`reply`,e.target.value)}),(0,A.jsx)(`p`,{className:`set-help`,children:e.opening===`say`||t?`Said exactly as written, before the model runs: the caller hears it at once.`:`An instruction the model reads to find its own opening. It costs a model round trip before the caller hears anything.`})]}),!t&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`set-field set-wide`,children:[(0,A.jsx)(sh,{children:`May hang up when`}),(0,A.jsx)(G,{value:e.hangup,"aria-label":`May hang up when`,placeholder:`the person has what they came for, or asks you to end the call`,onChange:e=>n(`hangup`,e.target.value)}),(0,A.jsx)(`p`,{className:`set-help`,children:`In your words. Empty: the agent never ends the call itself.`})]}),(0,A.jsxs)(`div`,{className:`set-row`,children:[(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(sh,{children:`Silence that ends a turn`}),(0,A.jsxs)(ch,{value:e.endpointing_ms,"aria-label":`Silence that ends a turn`,onChange:e=>n(`endpointing_ms`,e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`Runtime default · 1 second`}),Gq(Hq,e.endpointing_ms).map(e=>(0,A.jsxs)(`option`,{value:e,children:[Number(e)/1e3,` s`]},e))]}),(0,A.jsx)(`p`,{className:`set-help`,children:`How long the caller stays quiet before the agent answers. Shorter answers faster, and cuts off a slow speaker.`})]}),(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(sh,{children:`Words before an interruption counts`}),(0,A.jsxs)(ch,{value:e.min_interruption_words,"aria-label":`Words before an interruption counts`,onChange:e=>n(`min_interruption_words`,e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`Runtime default · 2 words`}),Gq(Uq,e.min_interruption_words).map(e=>(0,A.jsx)(`option`,{value:e,children:e===`1`?`1 word`:`${e} words`},e))]}),(0,A.jsx)(`p`,{className:`set-help`,children:`How many words a caller says over the agent before it stops talking. A cough is not an interruption.`})]})]})]})]})}function Gq(e,t){return t===``||e.includes(t)?e:[t,...e]}var Kq=`elevenlabs`,qq=`not on this box`;function Jq({modality:e,title:t,blurb:n,knob:r,providers:i,defaults:a,models:o,onChange:s,children:c}){let l=ig(i,e).filter(t=>t.ready&&(o[`${e}/${t.name}`]??[]).length>0),u=a[e]??``,d=r.vendor===``?u:r.vendor,f=l.some(e=>e.name===r.vendor)||r.vendor===``?l:[{name:r.vendor,ready:!1},...l],p=o[`${e}/${d}`]??[],m=p.includes(r.model)||r.model===``?p:[r.model,...p];return(0,A.jsxs)(`section`,{className:`set-section`,children:[(0,A.jsxs)(`div`,{className:`set-section-head`,children:[(0,A.jsx)(`h2`,{className:`set-section-title`,children:t}),(0,A.jsx)(`p`,{className:`set-section-blurb`,children:n})]}),(0,A.jsxs)(`div`,{className:`set-row`,children:[(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(sh,{children:`Vendor`}),(0,A.jsxs)(ch,{value:r.vendor,"aria-label":`Vendor`,onChange:e=>s({vendor:e.target.value,model:``}),children:[(0,A.jsxs)(`option`,{value:``,children:[`Runtime default · `,u]}),f.map(e=>(0,A.jsxs)(`option`,{value:e.name,children:[e.name,e.ready?``:` · ${qq}`]},e.name))]}),(0,A.jsx)(`p`,{className:`set-help`,children:`The vendors this box has a key for. Another one appears here once its key is added in Providers.`})]}),(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(sh,{children:`Model`}),(0,A.jsxs)(ch,{value:r.model,"aria-label":`Model`,onChange:e=>s({...r,model:e.target.value}),children:[(0,A.jsxs)(`option`,{value:``,children:[d,`'s default`,p[0]===void 0?``:` · ${p[0]}`]}),m.map(e=>(0,A.jsxs)(`option`,{value:e,children:[e,p.includes(e)?``:` · as set`]},e))]}),(0,A.jsx)(`p`,{className:`set-help`,children:p.length===0?`${d} runs its own default; there is no model to pick.`:`The models that run on this box. The default is the one tuned for phone calls.`})]})]}),c]})}function Yq({vendor:e,voice:t,voices:n,onChange:r}){if(e!==`elevenlabs`)return(0,A.jsx)(`div`,{className:`set-row`,children:(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(sh,{children:`Voice`}),(0,A.jsxs)(`p`,{className:`set-help`,children:[t===``?`${e} speaks in its model's own voice: there is no voice to pick here.`:`${e} speaks as ${t}, set from the terminal.`,` The voices to pick from are `,Kq,`'s.`]})]})});let i=n.includes(t)||t===``?n:[t,...n];return(0,A.jsx)(`div`,{className:`set-row`,children:(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(sh,{children:`Voice`}),(0,A.jsxs)(ch,{value:t,"aria-label":`Voice`,onChange:e=>r(e.target.value),children:[(0,A.jsx)(`option`,{value:``,children:`Runtime default`}),i.map(e=>(0,A.jsxs)(`option`,{value:e,children:[e,n.includes(e)?``:` · as set`]},e))]}),(0,A.jsx)(`p`,{className:`set-help`,children:`Hear each one in the Talk tab before a caller does.`})]})})}function Xq(e,t){if(e==null||e===``)return{vendor:``,model:``};let n=e.lastIndexOf(`/`);return n>=0?{vendor:e.slice(0,n),model:e.slice(n+1)}:t.has(e)?{vendor:e,model:``}:{vendor:``,model:e}}function Zq(e){return e.vendor===``?e.model:e.model===``?e.vendor:`${e.vendor}/${e.model}`}function Qq(e,t){let n=e.turn??void 0,r=e.memory??void 0,i=Xq(e.tts,t),a=e.tts_model??void 0,o=e.greeting?.reply??``;return{stt:Xq(e.stt,t),llm:Xq(e.llm,t),tts:a===void 0||a===``?i:{...i,model:a},voice:e.voice??``,opening:o===``?`say`:`reply`,say:e.greeting?.say??``,reply:o,hangup:e.hangup?.when??``,endpointing_ms:typeof n?.endpointing_ms==`number`?String(n.endpointing_ms):``,min_interruption_words:typeof n?.min_interruption_words==`number`?String(n.min_interruption_words):``,remember:(r?.remember??[]).join(`
108
+ `),forget:(r?.forget??[]).join(`
109
+ `),knowledge:e.knowledge??``,bases:(e.bases??[]).map(e=>({base:e.base,k:typeof e.k==`number`?String(e.k):``,mode:e.mode===`tool`?`tool`:`retrieved`,min_score:typeof e.min_score==`number`?String(e.min_score):``})),note:``}}function $q(e,t,n){let r=t?{...n}:{};if(!t){for(let t of[`stt`,`llm`,`tts`]){let n=Zq(e[t]);n!==``&&(r[t]=n)}let t=e.voice.trim();t!==``&&(r.voice=t);let n=e.hangup.trim();n!==``&&(r.hangup={when:n});let i={};e.endpointing_ms.trim()!==``&&(i.endpointing_ms=Number(e.endpointing_ms)),e.min_interruption_words.trim()!==``&&(i.min_interruption_words=Number(e.min_interruption_words)),Object.keys(i).length>0&&(r.turn=i),r.bases=e.bases.filter(e=>e.base.trim()!==``).map(eJ)}let i=e.say.trim(),a=e.reply.trim();e.opening===`say`&&i!==``?r.greeting={say:i}:e.opening===`reply`&&a!==``&&!t?r.greeting={reply:a}:delete r.greeting;let o=tJ(e.remember),s=tJ(e.forget);return o.length>0||s.length>0?r.memory={remember:o,forget:s}:delete r.memory,e.knowledge.trim()===``?delete r.knowledge:r.knowledge=e.knowledge,r}function eJ(e){let t={base:e.base.trim()};return e.k.trim()!==``&&(t.k=Number(e.k)),e.mode===`tool`&&(t.mode=`tool`),e.min_score.trim()!==``&&(t.min_score=Number(e.min_score)),t}function tJ(e){return e.split(`
110
+ `).map(e=>e.trim()).filter(e=>e!==``)}function nJ({typed:e,change:t}){return(0,A.jsxs)(`section`,{className:`set-section`,children:[(0,A.jsxs)(`div`,{className:`set-section-head`,children:[(0,A.jsx)(`h2`,{className:`set-section-title`,children:`Memory`}),(0,A.jsx)(`p`,{className:`set-section-blurb`,children:`What the agent writes down about a caller when the call ends, and hands back the next time that number calls.`})]}),(0,A.jsxs)(`div`,{className:`set-row`,children:[(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(sh,{children:`Remember`}),(0,A.jsx)(lh,{value:e.remember,rows:5,"aria-label":`Remember`,placeholder:`their name and phone
111
+ allergies
112
+ the morning or the afternoon they prefer`,onChange:e=>t(`remember`,e.target.value)}),(0,A.jsx)(`p`,{className:`set-help`,children:`One kind of fact per line, in your words. The extraction keeps only these.`})]}),(0,A.jsxs)(`div`,{className:`set-field`,children:[(0,A.jsx)(sh,{children:`Never keep`}),(0,A.jsx)(lh,{value:e.forget,rows:5,"aria-label":`Never keep`,placeholder:`card numbers
113
+ anything about payment`,onChange:e=>t(`forget`,e.target.value)}),(0,A.jsx)(`p`,{className:`set-help`,children:`One per line. What is named here is never written down, whatever a caller says.`})]})]})]})}function rJ({typed:e,change:t}){return(0,A.jsxs)(`section`,{className:`set-section`,children:[(0,A.jsxs)(`div`,{className:`set-section-head`,children:[(0,A.jsx)(`h2`,{className:`set-section-title`,children:`Knowledge`}),(0,A.jsx)(`p`,{className:`set-section-blurb`,children:`What the agent knows by heart: the business as you would tell a new receptionist. Read whole on every call, so keep it to what every call may need.`})]}),(0,A.jsxs)(`div`,{className:`set-field set-wide`,children:[(0,A.jsx)(sh,{children:`By heart, in Markdown`}),(0,A.jsx)(lh,{value:e.knowledge,"aria-label":`By heart, in Markdown`,rows:16,spellCheck:!1,placeholder:`# Clínica Norte
114
+
115
+ ## Hours
116
+ Monday to Friday, 9:00 to 20:00.
117
+
118
+ ## Prices
119
+ A first visit is 60 euros.
120
+
121
+ ## Needs an authorisation
122
+ An X-ray, an extraction, anything over 300 euros.`,onChange:e=>t(`knowledge`,e.target.value)}),(0,A.jsxs)(`p`,{className:`set-help`,children:[e.knowledge.length.toLocaleString(`en-US`),` characters. The documents it searches are not this: those are the Docs tab, attached under Bases.`]})]})]})}var iJ=[{tab:`hears`,name:`STT`},{tab:`decides`,name:`LLM`},{tab:`speaks`,name:`Voice`},{tab:`conversation`,name:`Conversation`},{tab:`memory`,name:`Memory`},{tab:`knowledge`,name:`Knowledge`},{tab:`bases`,name:`Bases`}],aJ=[`conversation`,`memory`,`knowledge`];function oJ(e){return e?iJ.filter(e=>aJ.includes(e.tab)):iJ}function sJ({standing:e,version:t,wordsOnly:n,voices:r,providers:i,defaults:a,models:o,bases:s,section:c,onPickSection:l,saving:u,error:d,onSave:f}){let p=new Set(i.map(e=>e.name)),[m,h]=(0,D.useState)(()=>Qq(e,p)),[g,_]=(0,D.useState)(!1),v=(e,t)=>{_(!1),h({...m,[e]:t})},y=e=>t=>{_(!1),h(e===`tts`&&t.vendor!==m.tts.vendor?{...m,tts:t,voice:``}:{...m,[e]:t})},b=m.tts.vendor===``?a.tts??`elevenlabs`:m.tts.vendor,x=async r=>{r.preventDefault(),await f($q(m,n,e),t,m.note.trim()===``?null:m.note.trim()),_(!0)};return(0,A.jsxs)(`form`,{className:`ui-card set-form`,onSubmit:e=>void x(e),children:[(0,A.jsx)(`div`,{className:`set-tabs`,children:(0,A.jsx)(zh,{label:`Settings`,tabs:oJ(n),on:c,onPick:l})}),c===`hears`&&(0,A.jsx)(Jq,{modality:`stt`,title:`Speech to text`,blurb:`What turns the caller's voice into words.`,knob:m.stt,providers:i,defaults:a,models:o,onChange:y(`stt`)}),c===`decides`&&(0,A.jsx)(Jq,{modality:`llm`,title:`Language model`,blurb:`The model that reads what the caller said and writes the answer.`,knob:m.llm,providers:i,defaults:a,models:o,onChange:y(`llm`)}),c===`speaks`&&(0,A.jsx)(Jq,{modality:`tts`,title:`Voice`,blurb:`What says the answer out loud, and in which voice.`,knob:m.tts,providers:i,defaults:a,models:o,onChange:y(`tts`),children:(0,A.jsx)(Yq,{vendor:b,voice:m.voice,voices:r,onChange:e=>v(`voice`,e)})}),c===`conversation`&&(0,A.jsx)(Wq,{typed:m,wordsOnly:n,change:v}),c===`memory`&&(0,A.jsx)(nJ,{typed:m,change:v}),c===`knowledge`&&(0,A.jsx)(rJ,{typed:m,change:v}),c===`bases`&&(0,A.jsx)(Bq,{rows:m.bases,offered:s,onChange:e=>{_(!1),h({...m,bases:e})}}),(0,A.jsxs)(`div`,{className:`set-save`,children:[(0,A.jsx)(G,{className:`set-save-note`,value:m.note,placeholder:`Why, for the history (optional)`,"aria-label":`Why, for the history (optional)`,onChange:e=>v(`note`,e.target.value)}),(0,A.jsx)(W,{kind:`primary`,size:`form`,type:`submit`,disabled:u,children:u?`Saving…`:t===null?`Save as the first version`:`Save as v${t+1}`}),(0,A.jsx)(`span`,{className:d===null?`set-save-said`:`set-save-said set-save-error`,children:d===null?g?`Kept. The next call runs on it.`:`Every section is saved together, as one version. An empty field is the runtime's default.`:d})]})]})}function cJ({kept:e,canRollBack:t,onRollBack:n}){return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`History`,meta:e===null?void 0:e.holder===``?`the org's own corner`:`corner ${e.holder}`}),e===null?(0,A.jsx)(Qm,{children:`Asking the gateway…`}):e.rows.length===0?(0,A.jsx)(Qm,{children:`Nothing set in this corner yet: the next call runs on what the corner falls back to.`}):e.rows.map((r,i)=>{let a=e.rows[i+1],o=VW(a?.config??{},r.config);return(0,A.jsxs)(`div`,{className:`set-version`,children:[(0,A.jsxs)(`div`,{className:`set-version-head`,children:[(0,A.jsxs)(`b`,{children:[`v`,r.version]}),(0,A.jsxs)(`span`,{className:`ui-cell-faint`,children:[r.author,` · `,vg(r.set_at)]}),r.note!==null&&(0,A.jsxs)(`span`,{className:`set-version-note`,children:[`“`,r.note,`”`]}),t&&i>0&&(0,A.jsx)(W,{size:`xs`,onClick:()=>void n(r.version),children:`Roll back to this`})]}),o.length>0&&(0,A.jsx)(`div`,{className:`set-version-changes`,children:o.join(` · `)})]},r.version)})]})}var lJ={yours:`Yours`,team:`Team`,production:`Production`};function uJ({answer:e,corners:t,first:n}){let[r,i]=(0,D.useState)(n),a=e[r];return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`What is set now`,meta:e.world}),t.length>1&&(0,A.jsx)(`div`,{className:`set-now-pick`,children:(0,A.jsx)(dh,{options:t.map(e=>({value:e,label:lJ[e]})),value:r,onChange:i})}),(0,A.jsx)(`dl`,{className:`set-now`,children:RW.map(e=>(0,A.jsxs)(`div`,{className:`set-now-row`,children:[(0,A.jsx)(`dt`,{children:zW[e]}),(0,A.jsx)(`dd`,{className:fJ(a,e,r)===dJ[r]?`set-now-none`:void 0,children:fJ(a,e,r)})]},e))}),(0,A.jsx)(`div`,{className:`set-now-foot`,children:a===null?`Nothing saved in this corner yet.`:pJ(a)})]})}var dJ={yours:`the team's`,team:`—`,production:`—`};function fJ(e,t,n){return e===null?dJ[n]:BW(e.config,t)??dJ[n]}function pJ(e){return`v${e.version} · ${e.author} · ${vg(e.set_at)}${e.note===null?``:` · “${e.note}”`}`}function mJ(e){return e instanceof Error?e.message:String(e)}function hJ(){let e=j(),t=Sr().agent??``,n=Kh(),[r,i]=Yi(),[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null),[d,f]=(0,D.useState)(null),[p,m]=(0,D.useState)(!1),[h,g]=(0,D.useState)(!1),[_,v]=(0,D.useState)(null),[y,b]=(0,D.useState)(null),x=n!==null&&!n.includes(`pipeline`),S=Am===`hosted`,C=oJ(x),w=r.get(`section`),T=C.some(e=>e.tab===w)?w:C[0].tab,ee=(0,D.useCallback)(async()=>{o(await PW(e,t)),c(await IW(e,t,S||p)),v(null)},[e,t,p,S]);(0,D.useEffect)(()=>{let n=!1;return ee().catch(e=>{n||v(mJ(e))}),EG(e,t).then(e=>!n&&u(e),e=>{!n&&!(e instanceof ta&&(e.status===403||e.status===404))&&v(mJ(e))}),JW(e).then(e=>!n&&f(e.bases),()=>!n&&f([])),()=>{n=!0}},[e,t,ee]),(0,D.useEffect)(()=>{let e=()=>void ee().catch(()=>void 0);return window.addEventListener(`focus`,e),()=>window.removeEventListener(`focus`,e)},[ee]);let te=async(n,r,i)=>{g(!0),v(null);try{o(await FW(e,t,{config:n,if_version:r,note:i,team:p})),c(await IW(e,t,S||p))}catch(e){v(mJ(e))}finally{g(!1)}},ne=async n=>{v(null);try{o(await LW(e,t,n,S||p)),c(await IW(e,t,S||p)),b(`v${n} is the newest again, as a new version.`)}catch(e){v(mJ(e))}},re=a===null?null:HW(a,S||p),E=re??(a===null||S||p?null:a.team),ie=Rh({name:`settings.now`,initial:340,min:280,max:560,side:`right`}),ae=S?[`production`]:[`yours`,`team`,`production`];return(0,A.jsxs)(`div`,{className:`set-grid`,style:ie.style,children:[ie.handle,(0,A.jsxs)(Dh,{width:1060,children:[(0,A.jsx)(Oh,{title:`Settings`,ledeWidth:660,lede:S?`What this agent runs on in production. Every save is a new version with your name on it, and any version can be rolled back.`:`What this agent runs on in the sandbox: yours to try in your own corner, or the team's, which every corner falls back to. Every save is a version; production has its own page.`}),a===null&&(0,A.jsx)(Qm,{children:_??`Asking the gateway…`}),a!==null&&(0,A.jsxs)(`div`,{className:`set-main`,children:[!x&&!S&&(0,A.jsx)(`div`,{className:`set-corner-pick`,children:(0,A.jsx)(hh,{checked:p,onChange:m,children:`Write the team's corner, which every corner falls back to — not only yours`})}),(0,A.jsx)(sJ,{standing:E?.config??{},version:re?.version??null,wordsOnly:x,voices:l?.voices??[],providers:l?.providers??[],defaults:l?.defaults??{},models:l?.models??{},bases:d,section:T,onPickSection:e=>i(e===C[0].tab?{}:{section:e}),saving:h,error:_,onSave:te},`${t}-${p}-${re?.version??0}-${E?.version??0}-${l===null?`asking`:`read`}`)]}),y!==null&&(0,A.jsx)(`div`,{className:`ui-empty`,children:y}),a!==null&&(0,A.jsx)($m,{children:_})]}),(0,A.jsx)(`aside`,{className:`set-pane`,"aria-label":`what is set, and its history`,children:a===null?(0,A.jsx)(`p`,{className:`set-pane-empty`,children:`Asking the gateway…`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(uJ,{answer:a,corners:ae,first:S?`production`:p?`team`:`yours`},p?`team`:`yours`),(0,A.jsx)(cJ,{kept:s,canRollBack:!x,onRollBack:ne})]})})]})}var gJ=`lk.transcription`,_J=`lk.transcription_final`,vJ=`lk.chat`,yJ=1500,bJ=`→`,xJ=`←`,SJ=`✗`;function CJ(e,t){let n=e.findIndex(e=>e.id===t.id);if(n===-1)return[...e,t];let r=e.slice();return r[n]=t,r}function wJ(e){return e.split(/(\s+)/).filter(e=>e.length>0)}function TJ(e){let t=Kw(e);if(t!==null)return{kind:`mark`,id:`mark-${e.seq}`,tone:`supervisor`,text:t.said};let n=e.data;switch(e.type){case`tool.call`:return{kind:`mark`,id:`mark-${e.seq}`,tone:`tool`,text:`${bJ} ${String(n.name)}(${DJ(n.arguments)})`};case`tool.result`:return{kind:`mark`,id:`mark-${e.seq}`,tone:`tool`,text:`${xJ} ${String(n.name)} ${EJ(n)}`};case`error`:return{kind:`mark`,id:`mark-${e.seq}`,tone:`error`,text:`${SJ} ${String(n.message)}`};default:return null}}function EJ(e){return e.error!==void 0&&e.error!==null?`error: ${DJ(e.error)}`:typeof e.summary==`string`?e.summary:e.output===void 0?`nothing`:DJ(e.output)}function DJ(e,t=80){let n=typeof e==`string`?e:JSON.stringify(e)??String(e);return n.length>t?`${n.slice(0,t-1)}…`:n}function OJ({lines:e,mode:t,head:n,children:r}){let i=(0,D.useRef)(null);return(0,D.useEffect)(()=>{let e=i.current;e&&(e.scrollTop=e.scrollHeight)},[e]),(0,A.jsxs)(`div`,{className:`ui-card talk-window`,children:[n??(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`This call`}),(0,A.jsx)(`span`,{className:`ui-card-meta`,children:`spoken or written, as the room says it`})]}),(0,A.jsxs)(`div`,{className:`talk-lines`,ref:i,children:[e.length===0&&(0,A.jsxs)(`p`,{className:`talk-quiet`,children:[`Nothing said yet. `,t===`talk`?`What you say and what you write both land here.`:`What you write and the agent's replies land here.`]}),e.map(e=>e.kind===`said`?(0,A.jsx)(kJ,{line:e},e.id):(0,A.jsx)(AJ,{mark:e},e.id))]}),r]})}function kJ({line:e}){return(0,A.jsx)(`div`,{className:e.speaker===`user`?`talk-said talk-said-you`:`talk-said`,children:(0,A.jsxs)(`p`,{className:`talk-bubble${e.speaker===`user`?` talk-bubble-you`:``}${!e.final||e.pending===!0?` talk-bubble-unsettled`:``}`,children:[wJ(e.text).map((e,t)=>(0,A.jsx)(`span`,{className:`talk-word`,children:e},t)),!e.final&&(0,A.jsx)(`span`,{className:`talk-cursor`,"aria-hidden":!0})]})})}function AJ({mark:e}){return(0,A.jsx)(`p`,{className:`talk-mark talk-mark-${e.tone}`,children:e.text})}function jJ({open:e,mode:t,onWrite:n}){let[r,i]=(0,D.useState)(``);return(0,A.jsxs)(`form`,{className:`talk-composer`,onSubmit:t=>{t.preventDefault();let a=r.trim();a!==``&&e&&(i(``),n(a))},children:[(0,A.jsx)(`input`,{className:`talk-write`,"aria-label":`Write to the agent`,value:r,disabled:!e,placeholder:e?t===`talk`?`Write to the agent — or just speak`:`Write to the agent`:`Call or Write first`,onChange:e=>i(e.target.value)}),(0,A.jsx)(`button`,{type:`submit`,className:`talk-send`,disabled:!e||r.trim()===``,children:`Send`})]})}var MJ=new Set;function NJ(e){MJ.add(e)}function PJ(e){return MJ.has(e)}var FJ=z({server_url:P(),participant_token:P(),call:P()});function IJ(e){let t=j(),[n,r]=(0,D.useState)(`idle`),[i,a]=(0,D.useState)(`talk`),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(null),[f,p]=(0,D.useState)([]),[m,h]=(0,D.useState)(null),g=(0,D.useRef)(null),_=(0,D.useRef)(new Set),v=(0,D.useRef)(null),y=(0,D.useRef)([]),b=(0,D.useRef)(null),x=(0,D.useCallback)(()=>{b.current!==null&&(window.clearTimeout(b.current),b.current=null);let e=y.current;y.current=[],e.length>0&&p(t=>[...t,...e])},[]),S=(0,D.useCallback)(e=>{if(!_.current.has(e.id)){_.current.add(e.id),e.speaker===`user`&&x(),p(t=>CJ(t,e)),v.current=e.speaker,e.speaker===`agent`&&x();return}p(t=>CJ(t,e))},[x]),C=(0,D.useRef)(0),w=(0,D.useCallback)(async e=>{let t=g.current;if(t===null)return;C.current+=1;let n=`typed-${C.current}`;x(),p(t=>[...t,{kind:`said`,id:n,speaker:`user`,text:e,final:!0,pending:!0}]),v.current=`user`;try{await t.localParticipant.sendText(e,{topic:vJ})}catch(e){p(e=>e.filter(e=>e.id!==n)),h(e instanceof Error?e.message:String(e))}},[x]),T=(0,D.useCallback)(e=>{if(e.type===`turn.user`){let t=String(e.data.text??``).trim();p(e=>{let n=e.findIndex(e=>e.kind===`said`&&e.pending===!0&&e.text.trim()===t);if(n===-1)return e;let r=e.slice();return r[n]={...e[n],pending:!1},r});return}let t=TJ(e);if(t!==null){if(v.current===`agent`){p(e=>[...e,t]);return}y.current.push(t),b.current!==null&&window.clearTimeout(b.current),b.current=window.setTimeout(x,yJ)}},[x]),ee=(0,D.useCallback)(async n=>{r(`connecting`),a(n),l(!1),s(null),h(null),p([]),_.current.clear(),v.current=null,y.current=[];try{let i=FJ.parse(await ca(t,`/v1/tokens`,{agent:e,scope:n})),a=new yH;g.current=a,a.registerTextStreamHandler(gJ,(e,t)=>{LJ(a,e,t.identity,S)}),n===`talk`&&a.on(Y.TrackSubscribed,RJ),a.on(Y.TrackUnsubscribed,e=>e.detach().forEach(e=>e.remove())),a.on(Y.Disconnected,()=>r(`ended`)),NJ(i.call),d(i.call),await a.connect(i.server_url,i.participant_token),n===`talk`&&await a.localParticipant.setMicrophoneEnabled(!0),s(Date.now()/1e3),r(`live`)}catch(e){h(e instanceof Error?e.message:String(e)),r(`failed`)}},[e,t,S]),te=(0,D.useCallback)(async()=>{await g.current?.disconnect()},[]),ne=(0,D.useCallback)(async()=>{let e=g.current;e!==null&&(await e.localParticipant.setMicrophoneEnabled(c),l(!c))},[c]);return(0,D.useEffect)(()=>()=>{g.current?.disconnect()},[]),{phase:n,mode:i,call:u,lines:f,error:m,since:o,muted:c,open:ee,close:te,toggleMic:ne,write:w,heard:T}}async function LJ(e,t,n,r){let i=t.info.attributes?.[`lk.segment_id`]??t.info.id,a=e.remoteParticipants.get(n)?.kind===dA.AGENT?`agent`:`user`,o=``;for await(let e of t)o+=e,r({kind:`said`,id:i,speaker:a,text:o,final:!1});r({kind:`said`,id:i,speaker:a,text:o,final:t.info.attributes?.[_J]===`true`})}function RJ(e){if(e.kind!==$.Kind.Audio)return;let t=e.attach();t.style.display=`none`,document.body.append(t)}function zJ(){let e=Sr().agent??``,t=IJ(e),n=Wh(),{world:r}=Yh(),i=t.phase===`live`||t.phase===`connecting`,a=Rh({name:`agent.inspector`,initial:330,min:260,max:620,side:`right`}),o=n?.name??n?.label??`this key`;return(0,A.jsxs)(`div`,{className:`talk-grid`,style:a.style,children:[a.handle,(0,A.jsxs)(Dh,{width:760,children:[(0,A.jsx)(Oh,{title:`Chat with ${e}`,lede:`Reach the agent as a customer would: call it with this machine's microphone and hear it answer, or write to it. On a call you can also type — a number, an address, a name nobody spells out loud.`}),(0,A.jsxs)(`div`,{className:`talk-facts`,children:[(0,A.jsxs)(`div`,{className:`talk-fact`,children:[(0,A.jsx)(`div`,{className:`talk-fact-label`,children:`You are`}),(0,A.jsxs)(`div`,{className:`talk-fact-value`,children:[o,` · you`]})]}),(0,A.jsxs)(`div`,{className:`talk-fact`,children:[(0,A.jsx)(`div`,{className:`talk-fact-label`,children:`Lands in`}),(0,A.jsxs)(`div`,{className:`talk-fact-value`,children:[r,` · counts in usage`]})]})]}),(0,A.jsx)($m,{children:t.error}),(0,A.jsx)(OJ,{lines:i||t.phase===`ended`?t.lines:[],mode:t.mode,head:(0,A.jsx)(BJ,{agent:e,live:t}),children:(0,A.jsx)(jJ,{open:t.phase===`live`,mode:t.mode,onWrite:t.write})}),t.call!==null&&(0,A.jsx)(VJ,{call:t.call,heard:t.heard})]}),(0,A.jsx)(Iw,{agent:e,call:t.call})]})}function BJ({agent:e,live:t}){let n=WJ(t.phase===`live`),r=t.phase===`live`||t.phase===`connecting`,i=t.mode===`talk`;return(0,A.jsxs)(`div`,{className:`ui-card-head talk-bar`,children:[r&&i&&(0,A.jsx)(`button`,{type:`button`,className:`talk-door talk-door-on`,disabled:t.phase===`connecting`,onClick:()=>void t.close(),"aria-label":`Hang up`,children:(0,A.jsx)(_h,{name:`phone`,size:17})}),r&&!i&&(0,A.jsx)(`span`,{className:t.phase===`live`?`talk-light talk-light-on`:`talk-light`,"aria-hidden":!0}),(0,A.jsxs)(`div`,{className:`talk-standing`,children:[(0,A.jsxs)(`div`,{className:`talk-phase`,children:[HJ(t),t.phase===`live`&&(0,A.jsx)(`span`,{className:`talk-clock`,children:mg(t.since,n)})]}),(0,A.jsx)(`div`,{className:`talk-hint`,children:UJ(t)})]}),(0,A.jsxs)(`div`,{className:`talk-moves`,children:[t.phase===`live`&&i&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`span`,{className:t.muted?`talk-bars`:`talk-bars talk-bars-on`,"aria-hidden":!0,children:[(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{}),(0,A.jsx)(`span`,{})]}),(0,A.jsx)(W,{size:`sm`,onClick:()=>void t.toggleMic(),children:t.muted?`Unmute`:`Mute`})]}),r&&!i&&(0,A.jsx)(W,{kind:`danger`,size:`sm`,disabled:t.phase===`connecting`,onClick:()=>void t.close(),children:`End chat`}),t.phase===`ended`&&t.call!==null&&(0,A.jsx)(ah,{size:`sm`,to:`/a/${e}/sessions/${t.call}`,children:`Open the session`}),!r&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(W,{kind:`primary`,size:`sm`,onClick:()=>void t.open(`talk`),children:[(0,A.jsx)(_h,{name:`phone`,size:14}),`Call`]}),(0,A.jsxs)(W,{size:`sm`,onClick:()=>void t.open(`chat`),children:[(0,A.jsx)(_h,{name:`words`,size:14}),`Write`]})]})]})]})}function VJ({call:e,heard:t}){return Mw(e,{onEntry:t}),null}function HJ(e){let t=e.mode===`talk`;switch(e.phase){case`idle`:return`Call or write`;case`connecting`:return`Joining the room…`;case`live`:return t?e.muted?`On a call — muted`:`On a call`:`Writing`;case`ended`:return t?`The call ended`:`The chat ended`;case`failed`:return`The room did not open`}}function UJ(e){let t=e.mode===`talk`;switch(e.phase){case`idle`:return`Call: the browser asks for the microphone and the agent answers out loud. Write: text only, no audio.`;case`connecting`:return t?`The microphone opens as soon as the room does.`:`Opening a written room with the agent.`;case`live`:return t?`Speak, or type below. Everything lands in the log beside you.`:`Write below; the agent answers in writing.`;case`ended`:return`Judged at hang-up. Call or write to start another.`;case`failed`:return`Nothing reached the agent. The reason is above.`}}function WJ(e){let[t,n]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>n(Date.now()/1e3),1e3);return()=>window.clearInterval(t)},[e]),t}var GJ=z({device:P().nullable(),expires_at:F(),answered:L()}),KJ=z({device:P().nullable(),org:P()});function qJ(e){return`/v1/login/pairings/${encodeURIComponent(e)}`}async function JJ(e,t){return GJ.parse(await oa(e,qJ(t)))}async function YJ(e,t){return KJ.parse(await ca(e,qJ(t),{})).org}var XJ=`c`,ZJ=`a terminal`;function QJ(){let e=j(),[t]=Yi(),n=t.get(XJ),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(!1),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(null);(0,D.useEffect)(()=>{if(n===null)return;let t=!1;return JJ(e,n).then(e=>{t||i(e)},e=>{t||u(e instanceof ta?e.message:String(e))}),()=>{t=!0}},[e,n]);let d=async()=>{if(n!==null){o(!0),u(null);try{c(await YJ(e,n))}catch(e){u(e instanceof ta?e.message:String(e))}finally{o(!1)}}};return n===null?(0,A.jsx)(eY,{title:`No terminal is asking`,lede:$J}):s===null?l!==null&&r===null?(0,A.jsx)(eY,{title:`That link is no good`,lede:l}):(0,A.jsxs)(eY,{title:`Sign this terminal in?`,lede:`A terminal calling itself ${r?.device??ZJ} asked to be signed in as you. Approve it only if you just ran "pinecall login" on that machine yourself.`,children:[(0,A.jsx)(W,{kind:`primary`,size:`lg`,onClick:()=>void d(),disabled:a||r===null,children:a?`Signing in…`:`Yes, that is my terminal`}),l!==null&&(0,A.jsx)(`p`,{className:`terminal-refused`,children:l})]}):(0,A.jsx)(eY,{title:`Your terminal is signed in`,lede:`Go back to it. You are in ${s}.`})}var $J="Run `pinecall login` in your terminal — it prints a link, and that link comes back here.";function eY({title:e,lede:t,children:n}){return(0,A.jsx)(`div`,{className:`terminal`,children:(0,A.jsxs)(`div`,{className:`terminal-card`,children:[(0,A.jsx)(`img`,{className:`terminal-mark`,src:`/pinecall-mark.png`,alt:``}),(0,A.jsx)(`h1`,{className:`terminal-title`,children:e}),(0,A.jsx)(`p`,{className:`terminal-lede`,children:t}),n]})})}var tY=`minmax(0,1fr) minmax(0,1.3fr) 110px 110px 96px 90px 230px`,nY={active:`green`,invited:`amber`,disabled:`gray`};function rY({member:e,onChange:t,onResend:n,onReset:r,onRemove:i,yourself:a=!1}){let[o,s]=(0,D.useState)(!1),[c,l]=(0,D.useState)(null),[u,d]=(0,D.useState)(e.agents.join(` `)),[f,p]=(0,D.useState)(!1),m=async e=>{p(!0);try{await e()}finally{p(!1)}},h=()=>{l(null);let n=u.split(/[\s,]+/).filter(e=>e!==``);n.join(` `)!==e.agents.join(` `)&&m(()=>t({agents:n}))};return(0,A.jsxs)(`div`,{className:`ui-table-row`,style:{gridTemplateColumns:tY},children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.name}),(0,A.jsx)(`span`,{className:`ui-cell ui-clip`,children:e.email}),c===`role`?(0,A.jsx)(ch,{size:`sm`,autoFocus:!0,value:e.role,onBlur:()=>l(null),onChange:e=>{l(null),m(()=>t({role:e.target.value}))},"aria-label":`${e.name}'s role`,children:WU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))}):(0,A.jsx)(`button`,{type:`button`,className:`team-editable team-role`,onClick:()=>l(`role`),title:`Change the role`,children:e.role}),c===`agents`?(0,A.jsx)(G,{size:`sm`,autoFocus:!0,value:u,placeholder:`every agent`,onChange:e=>d(e.target.value),onBlur:h,onKeyDown:t=>{t.key===`Enter`&&h(),t.key===`Escape`&&(d(e.agents.join(` `)),l(null))},"aria-label":`${e.name}'s agents`}):(0,A.jsx)(`button`,{type:`button`,className:`team-editable team-agents ui-clip`,onClick:()=>l(`agents`),title:`Change the agents`,children:e.agents.length===0?`every agent`:e.agents.join(`, `)}),(0,A.jsx)(`span`,{className:`ui-cell`,children:e.role===`admin`?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`always`}):(0,A.jsx)(mh,{on:e.production,label:`${e.name} acts in production`,onChange:e=>void m(()=>t({production:e}))})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:(0,A.jsx)(vh,{tone:nY[e.status],children:e.status})}),(0,A.jsx)(`span`,{className:`ui-cell-end`,children:o?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`span`,{className:`team-sure`,children:`Remove for good?`}),(0,A.jsx)(oh,{danger:!0,disabled:f,onClick:()=>void m(i),children:`Remove`}),(0,A.jsx)(oh,{disabled:f,onClick:()=>s(!1),children:`Keep`})]}):(0,A.jsxs)(A.Fragment,{children:[e.status===`active`&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(oh,{disabled:f,onClick:()=>void m(r),title:`A one-use link to choose a new password`,children:`Reset password`}),!a&&(0,A.jsx)(oh,{disabled:f,onClick:()=>void m(()=>t({status:`disabled`})),children:`Disable`})]}),e.status===`disabled`&&(0,A.jsx)(oh,{disabled:f,onClick:()=>void m(()=>t({status:`active`})),children:`Bring back`}),e.status===`invited`&&(0,A.jsx)(oh,{disabled:f,onClick:()=>void m(n),children:`Resend invite`}),!a&&(0,A.jsx)(oh,{danger:!0,disabled:f,onClick:()=>s(!0),title:`Out of the org for good: every key revoked, the seat freed`,children:`Remove`})]})})]})}var iY={qa:{who:`Reads finished calls and the suites`,opens:`calls · evals`},supervisor:{who:`Sits beside a live call: listens, whispers, takes it over`,opens:`calls · evals · supervise · talk · memory · words`},manager:{who:`Runs the floor and the org's accounts, never the agent's declaration`,opens:`calls · evals · supervise · talk · memory · numbers · keys · providers · usage · team · words`},developer:{who:`Writes and runs the agent`,opens:`app · calls · talk · supervise · pipeline · knowledge · memory · evals · words`},admin:{who:`The org's owner`,opens:`every door`}},aY=[`qa`,`supervisor`,`manager`,`developer`,`admin`],oY=`110px minmax(0,1fr) minmax(0,1.4fr)`;function sY(){return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Roles`,meta:`a preset of what a person's keys open — and where: the sandbox always, production when their switch is on (an admin's always is)`}),(0,A.jsx)(jh,{columns:oY,labels:[`Role`,`Who`,`Opens`]}),aY.map(e=>(0,A.jsxs)(Mh,{columns:oY,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong`,children:e}),(0,A.jsx)(`span`,{className:`ui-cell-ink`,children:iY[e].who}),(0,A.jsx)(`span`,{className:`ui-cell-faint team-role-opens`,children:iY[e].opens})]},e))]})}var cY=``;function lY(){let e=j(),[t,n]=(0,D.useState)(null),[r,i]=(0,D.useState)(null),[a,o]=(0,D.useState)(!1),[s,c]=(0,D.useState)(!1);if((0,D.useEffect)(()=>{let t=!1;return $U(e).then(e=>{t||n(e)},e=>{t||i(fY(e))}),()=>{t=!0}},[e]),t===null)return r===null?null:(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Single sign-on`}),(0,A.jsx)(`div`,{className:`ui-card-body`,children:(0,A.jsx)($m,{children:r})})]});let l=async()=>{if(!s){c(!0);return}i(null);try{await tW(e),n(await $U(e)),c(!1)}catch(e){i(fY(e))}};return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`Single sign-on`,meta:t.configured?`this org's people sign in with its identity provider`:`sign in with Google Workspace, Okta or Entra instead of a password`,children:t.configured&&!a&&(0,A.jsxs)(`span`,{className:`team-link-moves`,children:[(0,A.jsx)(W,{size:`xs`,onClick:()=>o(!0),children:`Change`}),(0,A.jsx)(W,{size:`xs`,kind:`danger`,onClick:()=>void l(),onBlur:()=>c(!1),children:s?`Remove · sure?`:`Remove`})]})}),t.configured&&!a?(0,A.jsxs)(`div`,{className:`team-sso-values`,children:[(0,A.jsx)(rh,{label:`Issuer`,children:t.issuer}),(0,A.jsx)(rh,{label:`Client ID`,children:t.client_id}),(0,A.jsx)(rh,{label:`Client secret`,children:`kept, and never shown`}),(0,A.jsx)(rh,{label:`Allowed domains`,children:t.domains.join(`, `)||`—`}),(0,A.jsx)(rh,{label:`Arriving new`,children:t.role??`nobody: invite first`}),(0,A.jsx)(rh,{label:`Passwords`,children:t.required?`stopped for this org`:`still work beside it`})]}):(0,A.jsx)(uY,{sso:t,onSaved:e=>{n(e),o(!1)},onCancel:t.configured?()=>o(!1):void 0}),(0,A.jsx)(dY,{uri:t.redirect_uri}),r!==null&&(0,A.jsx)(`div`,{className:`ui-card-body`,children:(0,A.jsx)($m,{children:r})})]})}function uY({sso:e,onSaved:t,onCancel:n}){let r=j(),[i,a]=(0,D.useState)(e.issuer??``),[o,s]=(0,D.useState)(e.client_id??``),[c,l]=(0,D.useState)(``),[u,d]=(0,D.useState)(e.domains.join(` `)),[f,p]=(0,D.useState)(e.role??cY),[m,h]=(0,D.useState)(e.required),[g,_]=(0,D.useState)(!1),[v,y]=(0,D.useState)(null),b=async e=>{e.preventDefault(),_(!0),y(null);try{t(await eW(r,{issuer:i.trim(),client_id:o.trim(),client_secret:c,domains:u.split(/[\s,]+/).filter(e=>e!==``),role:f===cY?null:f,required:m}))}catch(e){y(fY(e))}finally{_(!1)}};return(0,A.jsxs)(`form`,{className:`team-sso-form`,onSubmit:e=>void b(e),children:[(0,A.jsxs)(`div`,{className:`team-sso-grid`,children:[(0,A.jsx)(uh,{label:`Issuer URL`,children:(0,A.jsx)(G,{type:`url`,placeholder:`https://accounts.google.com`,value:i,onChange:e=>a(e.target.value),required:!0})}),(0,A.jsx)(uh,{label:`Client ID`,children:(0,A.jsx)(G,{value:o,onChange:e=>s(e.target.value),required:!0})}),(0,A.jsx)(uh,{label:`Client secret, sent once`,children:(0,A.jsx)(G,{type:`password`,autoComplete:`off`,placeholder:`never shown again`,value:c,onChange:e=>l(e.target.value),required:!0})}),(0,A.jsx)(uh,{label:`Allowed domains`,children:(0,A.jsx)(G,{placeholder:`company.com other.com`,value:u,onChange:e=>d(e.target.value),required:!0})}),(0,A.jsx)(uh,{label:`Role for people who arrive new`,children:(0,A.jsxs)(ch,{value:f,onChange:e=>p(e.target.value),children:[(0,A.jsx)(`option`,{value:cY,children:`nobody: invite first`}),WU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))]})}),(0,A.jsxs)(`div`,{className:`team-sso-required`,children:[(0,A.jsx)(`span`,{className:`team-sso-required-words`,children:`Passwords stop working for this org`}),(0,A.jsx)(mh,{on:m,onChange:h,label:`Passwords stop working for this org`})]})]}),(0,A.jsxs)(`div`,{className:`team-sso-moves`,children:[(0,A.jsx)(W,{kind:`primary`,size:`form`,type:`submit`,disabled:g,children:g?`Asking the issuer…`:`Save`}),n!==void 0&&(0,A.jsx)(W,{size:`form`,onClick:n,children:`Cancel`}),(0,A.jsx)(`span`,{className:`ui-note`,children:`The gateway asks the issuer for its discovery document before it keeps anything.`})]}),(0,A.jsx)($m,{children:v})]})}function dY({uri:e}){let[t,n]=(0,D.useState)(!1);return(0,A.jsxs)(`div`,{className:`team-sso-redirect`,children:[(0,A.jsxs)(`div`,{className:`team-sso-redirect-head`,children:[(0,A.jsx)(`span`,{className:`ui-note`,children:`Register this at your identity provider as the redirect URI`}),(0,A.jsx)(W,{size:`xs`,onClick:()=>{navigator.clipboard.writeText(e).then(()=>n(!0))},children:t?`Copied`:`Copy`})]}),(0,A.jsx)(`pre`,{className:`ui-code`,children:e})]})}function fY(e){return e instanceof ta?e.message:String(e)}var pY=[{tab:`people`,name:`People`},{tab:`roles`,name:`Roles`},{tab:`sso`,name:`Single sign-on`}];function mY(){let e=j(),t=dg(Wh()),[n,r]=Yi(),i=pY.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`people`,[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(!1),[l,u]=(0,D.useState)(null),[d,f]=(0,D.useState)(null),p=async()=>o(await qU(e)),m=e=>r(e===`people`?{}:{tab:e});(0,D.useEffect)(()=>{let t=!1;return qU(e).then(e=>{t||o(e)},e=>{t||f(_Y(e))}),()=>{t=!0}},[e]);let h=async(t,n)=>{f(null);try{await ZU(e,t,n),await p()}catch(e){f(_Y(e))}},g=async t=>{f(null);try{return u({link:await JU(e,t),kind:`invitation`}),await p(),!0}catch(e){return f(_Y(e)),!1}},_=async t=>{f(null);try{await XU(e,t),await p()}catch(e){f(_Y(e))}},v=async t=>{f(null);try{u({link:await YU(e,t),kind:`reset`})}catch(e){f(_Y(e))}},y=e=>(a??[]).filter(t=>t.status===e).length;return(0,A.jsxs)(Dh,{width:1060,tight:!0,children:[(0,A.jsx)(Oh,{title:`Team`,lede:`The org's people: who they are, what their keys may do, and how they sign in.`}),(0,A.jsx)(zh,{label:`Team`,tabs:pY,on:i,onPick:m}),i===`people`&&(0,A.jsxs)(A.Fragment,{children:[l!==null&&(0,A.jsx)(hY,{invited:l.link,kind:l.kind,onClose:()=>u(null)}),(0,A.jsx)($m,{children:d}),a!==null&&(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:`People`,meta:[`${y(`active`)} active`,y(`invited`)>0&&`${y(`invited`)} invited`,y(`disabled`)>0&&`${y(`disabled`)} disabled`].filter(Boolean).join(` · `),action:s?void 0:(0,A.jsx)(W,{kind:`primary`,size:`sm`,className:`ui-card-action`,onClick:()=>c(!0),children:`Invite someone`})}),s&&(0,A.jsx)(gY,{onInvite:async e=>{await g(e)&&c(!1)},onClose:()=>c(!1),onRoles:()=>m(`roles`)}),a.length===0?(0,A.jsx)(Qm,{children:`Nobody is a member yet: the org's machine key alone opens its doors. Invite the first person.`}):(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(jh,{columns:`minmax(0,1fr) minmax(0,1.3fr) 110px 110px 96px 90px 230px`,labels:[`Name`,`Email`,`Role`,`Agents`,`Production`,`Status>`,``]}),a.map(e=>(0,A.jsx)(rY,{member:e,onChange:t=>h(e.id,t),onResend:async()=>{await g({email:e.email,name:e.name,role:e.role,agents:e.agents,production:e.production})},onReset:()=>v(e.id),onRemove:()=>_(e.id),yourself:e.id===t},e.id))]})]})]}),i===`roles`&&(0,A.jsx)(sY,{}),i===`sso`&&(0,A.jsx)(lY,{})]})}function hY({invited:e,kind:t,onClose:n}){let r=vY(e.token),[i,a]=(0,D.useState)(!1);return(0,A.jsxs)(H,{children:[(0,A.jsx)(U,{title:t===`reset`?`A new password for ${e.member.name}`:`${e.member.name} is invited`,meta:`copy it now: the table keeps the fingerprint, and it is never shown again`,children:(0,A.jsxs)(`span`,{className:`team-link-moves`,children:[(0,A.jsx)(W,{size:`xs`,onClick:()=>{navigator.clipboard.writeText(r).then(()=>a(!0))},children:i?`Copied`:`Copy`}),(0,A.jsx)(W,{size:`xs`,onClick:n,children:`Done`})]})}),(0,A.jsx)(`pre`,{className:`ui-code`,children:r}),(0,A.jsx)(`div`,{className:`ui-card-foot`,children:t===`reset`?`One use · dies ${e.expires_at} · hand it to them: it opens the card where they choose a new password. Any older link of theirs no longer opens.`:`One use · dies ${e.expires_at} · it opens a card where they choose their password and take their first key.`})]})}function gY({onInvite:e,onClose:t,onRoles:n}){let[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(`qa`),[l,u]=(0,D.useState)(``),[d,f]=(0,D.useState)(!1),[p,m]=(0,D.useState)(!1),h=async t=>{t.preventDefault(),m(!0);try{await e({email:r.trim(),name:a.trim(),role:s,agents:l.split(/[\s,]+/).filter(e=>e!==``),production:d})}finally{m(!1)}};return(0,A.jsxs)(`div`,{className:`team-invite`,children:[(0,A.jsxs)(`form`,{className:`ui-form`,onSubmit:e=>void h(e),children:[(0,A.jsx)(uh,{label:`Email`,grow:!0,minWidth:180,children:(0,A.jsx)(G,{placeholder:`name@company.com`,type:`email`,value:r,onChange:e=>i(e.target.value),required:!0,autoFocus:!0})}),(0,A.jsx)(uh,{label:`Name`,grow:!0,minWidth:150,children:(0,A.jsx)(G,{placeholder:`Full name`,value:a,onChange:e=>o(e.target.value),required:!0})}),(0,A.jsx)(uh,{label:`Role`,minWidth:130,children:(0,A.jsx)(ch,{value:s,onChange:e=>c(e.target.value),children:WU.map(e=>(0,A.jsx)(`option`,{value:e,children:e},e))})}),(0,A.jsx)(uh,{label:`Agents`,minWidth:150,children:(0,A.jsx)(G,{placeholder:`every agent`,value:l,onChange:e=>u(e.target.value)})}),(0,A.jsx)(uh,{label:`Production`,minWidth:90,children:s===`admin`?(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:`always`}):(0,A.jsx)(mh,{on:d,label:`acts in production`,onChange:f})}),(0,A.jsx)(W,{kind:`primary`,size:`form`,type:`submit`,disabled:p,children:p?`Inviting…`:`Invite`})]}),(0,A.jsxs)(`div`,{className:`team-roles`,children:[`A role is a preset of what their keys open — `,(0,A.jsx)(oh,{onClick:n,children:`see what each one does`}),(0,A.jsx)(`span`,{className:`team-invite-close`,children:(0,A.jsx)(oh,{onClick:t,children:`Close`})})]})]})}function _Y(e){return e instanceof ta?e.message:String(e)}function vY(e){return`${window.location.origin}/invitations/${encodeURIComponent(e)}`}var yY=z({cursor:F(),org:P(),agent:P(),call:P(),type:P(),at:F(),minutes:F(),messages:F(),input_tokens:F(),output_tokens:F(),characters:F(),judge_calls:F(),cost_eur:F()}),bY=z({minutes:F(),messages:F(),input_tokens:F(),output_tokens:F(),characters:F(),judge_calls:F(),cost_eur:F(),calls:F()}),xY=z({rows:R(yY),totals:bY.nullable(),next:F().nullable()});async function SY(e,t=0){return xY.parse(await oa(e,`/v1/usage`,{after:t}))}function CY(e){let t=new Map;for(let n of e){let e=t.get(n.call)??{call:n.call,agent:n.agent,at:n.at,calls:1,minutes:0,messages:0,judge_calls:0,cost_eur:0};e.minutes+=n.minutes,e.messages+=n.messages,e.judge_calls+=n.judge_calls,e.cost_eur+=n.cost_eur,e.at=Math.min(e.at,n.at),t.set(n.call,e)}return[...t.values()].sort((e,t)=>t.at-e.at)}function wY(e,t){let n=new Map;for(let r of e){let e=t(r),i=n.get(e)??{name:e,calls:0,minutes:0,messages:0,judge_calls:0,cost_eur:0};i.calls+=1,i.minutes+=r.minutes,i.messages+=r.messages,i.judge_calls+=r.judge_calls,i.cost_eur+=r.cost_eur,n.set(e,i)}return[...n.values()]}function TY(e){return wY(e,e=>xg(e.at)).sort((e,t)=>t.name.localeCompare(e.name))}function EY(e){return wY(e,e=>e.agent).sort((e,t)=>t.cost_eur-e.cost_eur)}function DY(e){return wY(e,()=>``)[0]??{calls:0,minutes:0,messages:0,judge_calls:0,cost_eur:0}}var OY=[{tab:`days`,name:`By day`},{tab:`agents`,name:`By agent`},{tab:`calls`,name:`Call by call`}],kY=`minmax(0,1.2fr) 70px 80px 90px minmax(0,1fr) 90px`,AY=`130px 140px minmax(0,1fr) 70px 80px 90px`,jY=40;function MY(){let e=j(),t=Ag(),[n,r]=Yi(),i=OY.some(e=>e.tab===n.get(`tab`))?n.get(`tab`):`days`,[a,o]=(0,D.useState)(null),[s,c]=(0,D.useState)(null);(0,D.useEffect)(()=>{let t=!1;return(async()=>{try{let n=[],r=0;for(let i=0;i<jY;i+=1){let i=await SY(e,r);if(t)return;if(n.push(...i.rows),o([...n]),i.next===null)break;r=i.next}}catch(e){t||c(e instanceof ta?e.message:String(e))}})(),()=>{t=!0}},[e]);let l=CY(a??[]),u=DY(l),d=TY(l),f=d.find(e=>e.name===Sg().today)?.cost_eur??0,p=t?.budget??null;return(0,A.jsxs)(Dh,{tight:!0,children:[(0,A.jsx)(Oh,{title:`Usage`,lede:`What this org spent: the providers' bill as the call log knows it, never a price of ours.`}),(0,A.jsx)($m,{children:s}),a!==null&&(0,A.jsxs)(kh,{min:150,children:[(0,A.jsx)(Ah,{size:`small`,label:p===null?`Spent in all`:`Spent this month`,value:hg(p===null?u.cost_eur:p.spent_eur_month),of:p!==null&&p.limit_eur!==null?`of ${hg(p.limit_eur)}`:void 0,accent:!0}),(0,A.jsx)(Ah,{size:`small`,label:`Today`,value:hg(f)}),(0,A.jsx)(Ah,{size:`small`,label:`Calls`,value:u.calls}),(0,A.jsx)(Ah,{size:`small`,label:`Minutes`,value:u.minutes.toFixed(1)}),(0,A.jsx)(Ah,{size:`small`,label:`Per call`,value:u.calls===0?`—`:hg(u.cost_eur/u.calls)}),(0,A.jsx)(Ah,{size:`small`,label:`Per minute`,value:u.minutes===0?`—`:hg(u.cost_eur/u.minutes)})]}),(0,A.jsx)(zh,{label:`Usage`,tabs:OY,on:i,onPick:e=>r(e===`days`?{}:{tab:e})}),a!==null&&l.length===0&&(0,A.jsx)(H,{children:(0,A.jsx)(Qm,{children:`Nothing metered yet: the first call to end writes the first row.`})}),l.length>0&&i!==`calls`&&(0,A.jsx)(NY,{label:i===`days`?`Day`:`Agent`,groups:i===`days`?d:EY(l)}),l.length>0&&i===`calls`&&(0,A.jsxs)(H,{children:[(0,A.jsx)(jh,{columns:AY,labels:[`Started`,`Agent`,`Call`,`Min>`,`Messages>`,`Cost>`]}),l.map(e=>(0,A.jsxs)(Mh,{columns:AY,children:[(0,A.jsx)(`span`,{className:`ui-cell-faint`,children:vg(e.at)}),(0,A.jsx)(`span`,{className:`ui-cell-ink ui-clip`,children:e.agent}),(0,A.jsx)(k,{to:`/sessions/${e.call}`,className:`usage-call ui-clip`,children:e.call}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.minutes.toFixed(1)}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.messages}),(0,A.jsx)(`span`,{className:`usage-cost`,children:hg(e.cost_eur)})]},e.call)),(0,A.jsx)(Zm,{children:(0,A.jsxs)(`span`,{children:[l.length,` calls`,u.judge_calls>0&&` · ${u.judge_calls} judge calls`,` · a call's judging is folded into its line`]})})]})]})}function NY({label:e,groups:t}){let n=Math.max(...t.map(e=>e.cost_eur),0);return(0,A.jsxs)(H,{children:[(0,A.jsx)(jh,{columns:kY,labels:[e,`Calls>`,`Min>`,`Per call>`,``,`Cost>`]}),t.map(e=>(0,A.jsxs)(Mh,{columns:kY,children:[(0,A.jsx)(`span`,{className:`ui-cell-strong ui-clip`,children:e.name}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.calls}),(0,A.jsx)(`span`,{className:`ui-cell-ink usage-right`,children:e.minutes.toFixed(1)}),(0,A.jsx)(`span`,{className:`ui-cell-faint usage-right`,children:hg(e.cost_eur/e.calls)}),(0,A.jsx)(`span`,{className:`usage-bar`,children:(0,A.jsx)(Eh,{share:n===0?0:e.cost_eur/n})}),(0,A.jsx)(`span`,{className:`usage-cost`,children:hg(e.cost_eur)})]},e.name))]})}var PY=z({title:P().nullable(),tagline:P().nullable(),greeting:P().nullable(),accent:P().nullable(),autostart:L()});async function FY(e,t){try{return PY.parse(await oa(e,`/v1/agents/${encodeURIComponent(t)}/widget`))}catch(e){if(e instanceof ta&&e.status===404)return null;throw e}}async function IY(e,t,n){return PY.parse(await sa(e,`/v1/agents/${encodeURIComponent(t)}/widget`,n))}function LY(){return`${jm()}/widget/pinecall-widget.js`}var RY=null;function zY(){return RY??=yi(()=>import(LY()).then(()=>void 0,e=>{throw RY=null,Error(`the widget did not load from ${LY()}: ${e instanceof Error?e.message:String(e)}`)}),[]),RY}function BY(e,t,n,r){let i=document.createElement(`pinecall-widget`);i.setAttribute(`agent`,n);for(let[e,t]of Object.entries(r))i.setAttribute(e,t);return i.tokenProvider=e=>ca(t,`/v1/tokens`,{agent:n,scope:e,ttl_s:60,metadata:{page:`console preview`,scope:e}}),e.replaceChildren(i),i}var VY=[`#5b3df5`,`#101014`,`#0f766e`,`#be185d`];function HY(){let e=j(),t=Sr().agent??``,[n,r]=(0,D.useState)(`Assistant`),[i,a]=(0,D.useState)(``),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(``),[u,d]=(0,D.useState)(``),[f,p]=(0,D.useState)(!1),[m,h]=(0,D.useState)(VY[0]),[g,_]=(0,D.useState)(null),[v,y]=(0,D.useState)(!1),[b,x]=(0,D.useState)(null),[S,C]=(0,D.useState)(!1),[w,T]=(0,D.useState)(!1),ee={greeting:b!==null,autostart:b!==null},te=Kh(),ne=b!==null&&(te===null||te.includes(`pipeline`)),re=(0,D.useRef)(null);(0,D.useEffect)(()=>{let n=!1;return FY(e,t).then(e=>{n||e===null||(x(e),e.title!==null&&r(e.title),e.tagline!==null&&s(e.tagline),e.greeting!==null&&d(e.greeting),e.accent!==null&&h(e.accent),p(e.autostart))},()=>void 0),()=>{n=!0}},[e,t]),(0,D.useEffect)(()=>{let n=!1;return Hb(e).then(e=>{let r=e.find(e=>e.route.agent===t&&e.route.number!==null)?.route.number;!n&&r!=null&&l(e=>e===``?Eg(r):e)},()=>void 0),()=>{n=!0}},[e,t]);let E={title:n.trim()===``?null:n.trim(),tagline:o.trim()===``?null:o.trim(),greeting:u.trim()===``?null:u.trim(),accent:m,autostart:f},ie=b!==null&&((b.title??`Assistant`)!==n.trim()||(b.tagline??``)!==o.trim()||(b.greeting??``)!==u.trim()||(b.accent??VY[0])!==m||b.autostart!==f),ae=async()=>{C(!0),_(null);try{x(await IY(e,t,E)),T(!0),window.setTimeout(()=>T(!1),1500)}catch(e){_(e instanceof ta?e.message:String(e))}finally{C(!1)}};(0,D.useEffect)(()=>{let r=!1;return zY().then(()=>{if(r||re.current===null)return;let a={name:n,position:`inline`};i&&(a.company=i),o&&(a.tagline=o),c&&(a.phone=c),u&&(a.greeting=u),BY(re.current,e,t,a).style.setProperty(`--pc-accent`,m),_(null)},e=>{r||_(e instanceof Error?e.message:String(e))}),()=>{r=!0}},[e,t,n,i,o,c,u,m]);let oe=[`agent="${t}"`,`name="${n}"`,i&&`company="${i}"`,o&&`tagline="${o}"`,c&&`phone="${c}"`,ee.greeting&&u&&`greeting="${u}"`,ee.autostart&&f&&`autostart`,`token-url="/pinecall/token"`,`log-url="/pinecall/log"`].filter(Boolean),se=m===VY[0]?``:`\n<style>pinecall-widget { --pc-accent: ${m}; }</style>`,O=`<script type="module" src="${LY()}"><\/script>\n<pinecall-widget ${oe.join(`
123
+ `)}></pinecall-widget>${se}`,ce=new URLSearchParams({name:n,company:i,tagline:o,phone:c,accent:m,...ee.greeting&&u?{greeting:u}:{}});return(0,A.jsxs)(Dh,{width:900,tight:!0,children:[(0,A.jsx)(Oh,{title:`Widget`,ledeWidth:620,lede:`The web door for ${t} — one script tag on your site, and the call lands in the same log as the phone.`}),(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Embed`}),(0,A.jsx)(W,{size:`xs`,className:`widget-copy`,onClick:()=>{navigator.clipboard.writeText(O).then(()=>{y(!0),window.setTimeout(()=>y(!1),1500)})},children:v?`Copied`:`Copy`})]}),(0,A.jsx)(`pre`,{className:`ui-code`,children:O}),(0,A.jsxs)(`div`,{className:`widget-endpoints`,children:[(0,A.jsx)(`span`,{className:`ui-fixed`,children:`token-url`}),` and `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`log-url`}),` are your site's: the first mints a visit token at `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`/v1/tokens`}),` with a key holding `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`talk`}),`, the second relays the call's log with a key holding `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`calls`}),`. Ready-made PHP and Laravel endpoints:`,` `,(0,A.jsx)(`a`,{href:`https://github.com/pinecall/widget`,target:`_blank`,rel:`noreferrer`,children:`github.com/pinecall/widget`}),`.`]})]}),(0,A.jsxs)(`div`,{className:`widget-split`,children:[(0,A.jsxs)(`div`,{className:`ui-card`,children:[(0,A.jsxs)(`div`,{className:`ui-card-head`,children:[(0,A.jsx)(`span`,{className:`ui-card-title`,children:`Appearance`}),ne&&(0,A.jsx)(W,{kind:ie?`primary`:`secondary`,size:`xs`,className:`widget-copy`,disabled:S||!ie,onClick:()=>void ae(),children:S?`Saving…`:w?`Saved`:`Save`})]}),(0,A.jsxs)(`div`,{className:`widget-fields`,children:[(0,A.jsx)(uh,{label:`Name`,children:(0,A.jsx)(G,{value:n,onChange:e=>r(e.target.value)})}),(0,A.jsx)(uh,{label:`Tagline`,children:(0,A.jsx)(G,{value:o,placeholder:`the line under the name`,onChange:e=>s(e.target.value)})}),ee.greeting&&(0,A.jsx)(uh,{label:`Greeting`,children:(0,A.jsx)(G,{value:u,placeholder:`what the widget says before the call starts`,onChange:e=>d(e.target.value)})}),(0,A.jsxs)(`div`,{className:`widget-pair`,children:[(0,A.jsx)(uh,{label:`Company`,children:(0,A.jsx)(G,{value:i,placeholder:`whose agent it is`,onChange:e=>a(e.target.value)})}),(0,A.jsx)(uh,{label:`Phone`,children:(0,A.jsx)(G,{value:c,placeholder:`the number it answers, if it has one`,onChange:e=>l(e.target.value)})})]}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`widget-accent-label`,children:`Accent`}),(0,A.jsx)(`div`,{className:`widget-accents`,role:`group`,"aria-label":`accent`,children:(VY.includes(m)?VY:[...VY,m]).map(e=>(0,A.jsx)(`button`,{type:`button`,className:`widget-accent`,style:{background:e,boxShadow:e===m?`0 0 0 2px var(--ground),0 0 0 4px ${e}`:void 0},onClick:()=>h(e),"aria-label":e,"aria-pressed":e===m},e))})]}),ee.autostart&&(0,A.jsxs)(`div`,{className:`widget-toggle`,children:[(0,A.jsx)(`span`,{className:`widget-toggle-label`,children:`Open with the microphone ready`}),(0,A.jsx)(mh,{on:f,onChange:p,label:`Open with the microphone ready`})]})]})]}),(0,A.jsxs)(`div`,{className:`widget-preview`,children:[(0,A.jsx)(`div`,{className:`widget-preview-label`,children:`Preview`}),(0,A.jsx)(`div`,{className:`widget-stage`,ref:re}),(0,A.jsx)($m,{children:g}),(0,A.jsx)(k,{className:`widget-open`,to:`/a/${t}/widget/preview?${ce.toString()}`,target:`_blank`,children:`Open on a blank page ↗`})]})]})]})}function UY(){let e=j(),t=Sr().agent??``,[n]=Yi(),[r,i]=(0,D.useState)(null),a=(0,D.useRef)(null);return(0,D.useEffect)(()=>{let r=!1;return zY().then(()=>{if(r||a.current===null)return;let i={};for(let e of[`name`,`company`,`tagline`,`phone`,`greeting`]){let t=n.get(e);t&&(i[e]=t)}let o=BY(a.current,e,t,i),s=n.get(`accent`);s&&o.style.setProperty(`--pc-accent`,s)},e=>{r||i(e instanceof Error?e.message:String(e))}),()=>{r=!0}},[e,t,n]),(0,A.jsxs)(`div`,{className:`widget-blank`,children:[(0,A.jsx)(`div`,{ref:a}),(0,A.jsxs)(`span`,{className:`widget-blank-mark`,children:[`pinecall · `,t,` · preview`]}),r!==null&&(0,A.jsx)(`p`,{className:`widget-blank-refused`,children:r})]})}function WY({agent:e}){let{agents:t,live:n}=wb(),r=Kh(),i=t.find(t=>t.slug===e),a=n.filter(t=>t.agent===e).length,o=zm(Rm).filter(e=>r===null||Eb(r,e.key));return(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`agenthead`,children:[(0,A.jsxs)(`div`,{className:`agenthead-name`,children:[(0,A.jsx)(bh,{tone:i===void 0?void 0:`green`}),(0,A.jsx)(`span`,{className:`agenthead-slug`,children:e}),a>0?(0,A.jsx)(`span`,{className:`agenthead-status ui-pill-green`,children:a===1?`on a call`:`on ${a} calls`}):i!==void 0&&(0,A.jsx)(`span`,{className:`agenthead-status ui-pill-muted`,children:`idle`})]}),(0,A.jsx)(`span`,{className:`agenthead-doors`,children:i?.channels.join(` · `)||`no doors`})]}),(0,A.jsx)(`nav`,{className:`agenttabs`,"aria-label":`${e}'s screens`,children:o.map(t=>(0,A.jsx)(Wi,{to:`/a/${e}/${t.path}`,className:({isActive:e})=>e?`agenttab agenttab-on`:`agenttab`,children:t.name},t.key))})]})}var GY=/^call_[\w+-]{6,}$/,KY=40;function qY({agent:e,onClose:t}){let[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(0),{agents:o,lines:s,operator:c}=wb(),l=Kh(),u=vr(),d=(0,D.useRef)(null);(0,D.useEffect)(()=>d.current?.focus(),[]);let f=(0,D.useMemo)(()=>{let t=e=>l===null||Eb(l,e),r=n.trim().toLowerCase(),i=[];if(GY.test(n.trim())){let e=s.find(e=>e.call===n.trim());i.push({group:`Open`,label:n.trim(),sub:e?.agent??`by its id`,to:`/sessions/${n.trim()}`})}for(let e of zm(Im).filter(e=>t(e.key)))i.push({group:`Screens`,label:e.name,sub:``,to:`/${e.path}`});for(let e of zm(Lm,Am,c===!0))i.push({group:`Box`,label:e.name,sub:``,to:`/${e.path}`});for(let e of o)i.push({group:`Agents`,label:e.slug,sub:e.channels.join(` · `),to:`/a/${e.slug}/talk`});let a=e===``?o[0]?.slug:e;if(a!==void 0)for(let e of zm(Rm).filter(e=>t(e.key)))i.push({group:`${a}`,label:e.name,sub:a,to:`/a/${a}/${e.path}`});for(let e of s){let t=e.caller?.name??e.from??``;i.push({group:`Sessions`,label:e.call,sub:[e.agent,e.channel,t,e.outcome].filter(Boolean).join(` · `),to:`/sessions/${e.call}`})}return r===``?i.filter(e=>e.group!==`Sessions`).slice(0,KY):i.filter(e=>`${e.label} ${e.sub}`.toLowerCase().includes(r)).slice(0,KY)},[n,o,s,e,l,c]);(0,D.useEffect)(()=>a(0),[n]);let p=e=>{e!==void 0&&(t(),u(e.to))},m=e=>{e.key===`Escape`&&t(),e.key===`ArrowDown`&&(e.preventDefault(),a(e=>Math.min(f.length-1,e+1))),e.key===`ArrowUp`&&(e.preventDefault(),a(e=>Math.max(0,e-1))),e.key===`Enter`&&p(f[i])},h=``;return(0,A.jsx)(`div`,{className:`palette-veil`,onMouseDown:t,children:(0,A.jsxs)(`div`,{className:`palette`,role:`dialog`,"aria-label":`Search`,onMouseDown:e=>e.stopPropagation(),children:[(0,A.jsxs)(`div`,{className:`palette-input-row`,children:[(0,A.jsx)(_h,{name:`search`,size:16}),(0,A.jsx)(`input`,{ref:d,className:`palette-input`,placeholder:`Search a screen, an agent, a session id, a number or an outcome`,value:n,onChange:e=>r(e.target.value),onKeyDown:m})]}),(0,A.jsxs)(`div`,{className:`palette-list`,children:[f.length===0&&(0,A.jsx)(`div`,{className:`palette-none`,children:`Nothing here matches — the sessions searched are the ones the floor has listed.`}),f.map((e,t)=>{let n=e.group===h?null:e.group;return h=e.group,(0,A.jsxs)(`div`,{children:[n!==null&&(0,A.jsx)(`div`,{className:`palette-group`,children:n}),(0,A.jsxs)(`button`,{type:`button`,className:t===i?`palette-item palette-item-on`:`palette-item`,onMouseEnter:()=>a(t),onClick:()=>p(e),children:[(0,A.jsx)(`span`,{className:`ui-clip`,children:e.label}),e.sub!==``&&(0,A.jsx)(`span`,{className:`palette-item-sub`,children:e.sub})]})]},`${e.group}:${e.to}`)})]})]})})}var JY=3,YY=5e3;function XY(){let{live:e,lines:t}=wb(),n=vr(),r=gr().pathname,i=(0,D.useRef)(null),[a,o]=(0,D.useState)([]),s=$Y(a.length>0);(0,D.useEffect)(()=>{if(i.current===null){if(t.length===0&&e.length===0)return;i.current=new Set(e.map(e=>e.call));return}let n=i.current,r=e.filter(e=>!n.has(e.call)&&!PJ(e.call));e.forEach(e=>n.add(e.call)),r.forEach(e=>n.add(e.call)),o(e=>{let n=e.map(e=>{let n=t.find(t=>t.call===e.call);return n===void 0?e:{...e,line:n,ended:!n.live}});return[...r.map(e=>({call:e.call,line:e,ended:!1})),...n].slice(0,JY)})},[e,t]),(0,D.useEffect)(()=>{if(!a.some(e=>e.ended))return;let e=window.setTimeout(()=>o(e=>e.filter(e=>!e.ended)),YY);return()=>window.clearTimeout(e)},[a]);let c=e=>o(t=>t.filter(t=>t.call!==e)),l=a.filter(e=>r!==`/live/${e.call}`);return l.length===0?null:(0,A.jsx)(`div`,{className:`ring-stack`,role:`region`,"aria-label":`Calls coming in`,"aria-live":`polite`,children:l.map(e=>(0,A.jsxs)(`div`,{className:e.ended?`ring ring-ended`:`ring`,children:[(0,A.jsxs)(`button`,{type:`button`,className:`ring-body`,onClick:()=>{c(e.call),n(`/live/${e.call}`)},children:[(0,A.jsx)(`span`,{className:e.ended?`ring-icon ring-icon-ended`:`ring-icon`,"aria-hidden":!0,children:(0,A.jsx)(QY,{})}),(0,A.jsxs)(`span`,{className:`ring-words`,children:[(0,A.jsxs)(`span`,{className:`ring-top`,children:[(0,A.jsx)(`span`,{className:`ring-kicker`,children:ZY(e)}),!e.ended&&(0,A.jsx)(`span`,{className:`ring-watch`,children:`Watch live →`})]}),(0,A.jsx)(`span`,{className:`ring-who`,children:Dg(e.line)}),(0,A.jsxs)(`span`,{className:`ring-sub`,children:[e.line.agent,e.line.channel!==null&&` · ${e.line.channel}`,e.line.direction===`outbound`&&` · outbound`,!e.ended&&e.line.started_at!==null&&` · ${mg(e.line.started_at,s)}`]})]})]}),(0,A.jsx)(`button`,{type:`button`,className:`ring-close`,"aria-label":`Dismiss`,onClick:()=>c(e.call),children:`×`})]},e.call))})}function ZY(e){return e.ended?`Call ended`:e.line.direction===`outbound`?`Calling out`:e.line.channel===`web`?`New conversation`:e.line.channel===`whatsapp`?`New WhatsApp chat`:e.line.status===`active`?`New call · answered`:`New call ringing`}function QY(){return(0,A.jsx)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 24 24`,fill:`none`,stroke:`currentColor`,strokeWidth:`2`,strokeLinecap:`round`,strokeLinejoin:`round`,children:(0,A.jsx)(`path`,{d:`M22 16.9v3a2 2 0 0 1-2.2 2 19.8 19.8 0 0 1-8.6-3.1 19.5 19.5 0 0 1-6-6A19.8 19.8 0 0 1 2.1 4.2 2 2 0 0 1 4.1 2h3a2 2 0 0 1 2 1.7c.1.9.4 1.8.7 2.7a2 2 0 0 1-.5 2.1L8 9.8a16 16 0 0 0 6 6l1.3-1.3a2 2 0 0 1 2.1-.5c.9.3 1.8.6 2.7.7a2 2 0 0 1 1.7 2z`})})}function $Y(e){let[t,n]=(0,D.useState)(()=>Date.now()/1e3);return(0,D.useEffect)(()=>{if(!e)return;let t=window.setInterval(()=>n(Date.now()/1e3),1e3);return()=>window.clearInterval(t)},[e]),t}var eX=[{group:`gateway`,label:Am===`local`?`Sandbox`:`Gateway`},{group:`settings`,label:`Settings`},{group:`box`,label:`Box`}];function tX({agent:e,onSearch:t}){let[n,r]=(0,D.useState)(!1),i=Kh(),a=Wh(),{agents:o,live:s,lines:c,here:l,insights:u,operator:d}=wb(),f=e=>i===null||Eb(i,e.key),p=a?.name??a?.label??``,m=l?.role??(a===null?``:a.subject===null||a.subject===void 0?`a machine's key`:``),h=e=>e.key===`agents`&&o.length>0?{text:String(o.length),live:!1}:e.key===`live`&&s.length>0?{text:`${s.length} live`,live:!0}:e.key===`sessions`&&u!==null?{text:String(u.sessions_total),live:!1}:e.key===`sessions`&&c.length>0?{text:c.length>=200?`200+`:String(c.length),live:!1}:null;return(0,A.jsxs)(`aside`,{className:n?`side side-folded`:`side`,"aria-label":`Screens`,children:[(0,A.jsx)(rX,{}),(0,A.jsx)(`div`,{className:`side-search-wrap`,children:(0,A.jsxs)(`button`,{type:`button`,className:`side-search`,onClick:t,title:`Search`,children:[(0,A.jsx)(_h,{name:`search`,size:15}),(0,A.jsx)(`span`,{className:`side-label`,children:`Search`}),(0,A.jsx)(`span`,{className:`side-kbd`,children:`⌘K`})]})}),(0,A.jsxs)(`nav`,{className:`side-nav`,children:[(0,A.jsx)(`div`,{className:`side-group side-group-first`,children:`Agents`}),o.length===0&&(0,A.jsx)(`div`,{className:`side-none side-name`,children:`none held here`}),o.map(t=>{let n=s.some(e=>e.agent===t.slug),r=t.slug===e;return(0,A.jsxs)(Wi,{to:`/a/${t.slug}/talk`,title:t.slug,className:r?`side-link side-link-on`:`side-link`,children:[(0,A.jsx)(`span`,{className:n&&!r?`side-icon side-icon-live`:`side-icon`,children:(0,A.jsx)(_h,{name:`bot`})}),(0,A.jsx)(`span`,{className:`side-name side-name-agent`,children:t.slug}),n&&(0,A.jsx)(`span`,{className:`side-badge side-badge-live`,children:`live`})]},t.slug)}),eX.map(({group:t,label:n})=>{let r=zm([...Im,...Lm],Am,d===!0).filter(e=>e.group===t&&f(e));return r.length===0?null:(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`side-group`,children:n}),r.map(t=>{let n=h(t);return(0,A.jsxs)(Wi,{to:`/${t.path}`,end:t.path===``,title:t.name,className:({isActive:t})=>t&&e===``?`side-link side-link-on`:`side-link`,children:[(0,A.jsx)(`span`,{className:`side-icon`,children:t.icon!==void 0&&(0,A.jsx)(_h,{name:t.icon})}),(0,A.jsx)(`span`,{className:`side-name`,children:t.name}),n!==null&&(0,A.jsx)(`span`,{className:n.live?`side-badge side-badge-live`:`side-badge`,children:n.text})]},t.key)})]},t)})]}),(0,A.jsxs)(`div`,{className:`side-foot`,children:[(0,A.jsxs)(`div`,{className:`side-user`,title:p,children:[(0,A.jsx)(`span`,{className:`side-user-avatar`,children:wh(p||(a===null?`?`:Gh(a)))}),(0,A.jsxs)(`span`,{className:`side-label`,children:[(0,A.jsx)(`span`,{className:`side-user-name`,children:p||`—`}),(0,A.jsx)(`span`,{className:`side-user-role`,children:nX(m)})]})]}),(0,A.jsx)(`button`,{type:`button`,className:`side-fold`,onClick:()=>r(!n),title:n?`Open the sidebar`:`Collapse the sidebar`,children:(0,A.jsx)(_h,{name:`panel`,size:15})})]})]})}function nX(e){return e===``?``:e.charAt(0).toUpperCase()+e.slice(1)}function rX(){let e=Wh(),{agents:t,orgs:n}=wb(),{moveTo:r}=Yh(),[i,a]=(0,D.useState)(!1),[o,s]=(0,D.useState)(null),[c,l]=(0,D.useState)(!1),u=(0,D.useRef)(null),d=gr().pathname;(0,D.useEffect)(()=>a(!1),[d]),(0,D.useEffect)(()=>{if(!i)return;let e=e=>{u.current!==null&&!u.current.contains(e.target)&&a(!1)};return document.addEventListener(`mousedown`,e),()=>document.removeEventListener(`mousedown`,e)},[i]);let f=e===null?``:Gh(e),p=Am===`hosted`&&n!==null&&n.length>1,m=async e=>{l(!0),s(null);try{await r(e)}catch(e){s(e instanceof ta?e.message:String(e)),l(!1)}};return(0,A.jsxs)(`div`,{ref:u,className:`side-workspace-wrap`,children:[(0,A.jsxs)(`button`,{type:`button`,className:`side-workspace`,onClick:()=>p&&a(!i),title:f,"aria-expanded":i,children:[(0,A.jsx)(`span`,{className:`side-tile`,children:wh(f||`?`).slice(0,1)}),(0,A.jsxs)(`span`,{className:`side-label`,children:[(0,A.jsx)(`span`,{className:`side-org`,children:f||`…`}),(0,A.jsxs)(`span`,{className:`side-org-sub`,children:[e?.visiting===!0?`visiting as operator · `:``,t.length,` `,t.length===1?`agent`:`agents`]})]}),(0,A.jsx)(`span`,{className:`side-caret`,children:`▾`})]}),i&&n!==null&&(0,A.jsxs)(`div`,{className:`side-orgs`,role:`menu`,children:[[{label:`Your organizations`,rows:n.filter(e=>e.member!==!1)},{label:`Every other org on this box · as operator`,rows:n.filter(e=>e.member===!1)}].filter(e=>e.rows.length>0).map(e=>(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`side-orgs-label`,children:e.label}),e.rows.map(e=>(0,A.jsxs)(`button`,{type:`button`,className:`side-org-row`,disabled:c||e.here,onClick:()=>void m(e.org),children:[(0,A.jsx)(`span`,{className:`side-tile`,children:wh(e.slug??e.name??e.org).slice(0,1)}),(0,A.jsx)(`span`,{className:`ui-clip`,children:e.slug??e.name??e.org}),(0,A.jsx)(`span`,{className:`side-org-role`,children:e.here?`here`:e.role})]},e.org))]},e.label)),o!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,style:{padding:`6px 8px`},children:o})]})]})}var iX=new Set(Rm.map(e=>e.path)),aX=`http://localhost:4100`;function oX({agent:e}){let t=Wh(),n=dg(t),{world:r,corner:i,lookInto:a}=Yh(),{held:o,agentsLoaded:s}=wb(),[c,l]=(0,D.useState)(!1),u=vr(),{pathname:d}=gr(),f=(0,D.useRef)(null),p=d.split(`/`).filter(Boolean),m=e!==``&&iX.has(p[2]??``)?p[2]:`talk`;(0,D.useEffect)(()=>l(!1),[d]),(0,D.useEffect)(()=>{if(!c)return;let e=e=>{f.current!==null&&!f.current.contains(e.target)&&l(!1)},t=e=>{e.key===`Escape`&&l(!1)};return document.addEventListener(`mousedown`,e),document.addEventListener(`keydown`,t),()=>{document.removeEventListener(`mousedown`,e),document.removeEventListener(`keydown`,t)}},[c]);let h=t?.name??t?.label??``,g=t===null?`this org`:Gh(t),_=r===`production`,v=!_&&t?.scopes.includes(`team`)===!0,y=e=>e.holder?.holder??null,b=e=>_?y(e)===null:y(e)!==null&&(y(e)===n||v),x=t=>t.slug===e&&(_?y(t)===null:y(t)===(i??n)),S=e=>{let t=y(e);return t===null?_?`${g} · deployed on the box`:`${g} · shared`:t===n?`${h||`you`} · you`:`${e.holder?.name??t} · theirs`},C=[...o].sort((e,t)=>e.slug.localeCompare(t.slug)||Number(sg(e,n))-Number(sg(t,n))),w=i===null?void 0:o.find(e=>y(e)===i),T=()=>{let e=Am===`hosted`?aX:jm();window.open(`${e}${d}`,`_blank`,`noopener`)};return(0,A.jsxs)(`div`,{ref:f,style:{position:`relative`},children:[(0,A.jsxs)(`button`,{type:`button`,className:c?`switch-trigger switch-trigger-open`:`switch-trigger`,onClick:()=>l(!c),"aria-expanded":c,"aria-haspopup":`dialog`,children:[(0,A.jsx)(bh,{tone:_?`green`:`amber`}),(0,A.jsx)(`span`,{className:`switch-agent`,children:e===``?`choose an agent`:e}),(0,A.jsx)(vh,{tone:_?`green`:`amber`,children:r}),t!==null&&(0,A.jsx)(Th,{name:h||g,tint:`violet`,size:20}),(0,A.jsx)(`span`,{className:`switch-caret`,"aria-hidden":!0,children:`▾`})]}),c&&(0,A.jsxs)(`div`,{className:`switch-panel`,role:`dialog`,"aria-label":`what this console is looking at`,children:[t!==null&&(0,A.jsxs)(`div`,{className:`switch-who`,children:[(0,A.jsx)(Th,{name:h||g,tint:`violet`,size:36}),(0,A.jsxs)(`div`,{style:{minWidth:0},children:[(0,A.jsx)(`div`,{className:`switch-who-name`,children:h||`an org's key`}),(0,A.jsxs)(`div`,{className:`switch-who-sub`,children:[g,` · key `,t.key_id]})]})]}),i!==null&&(0,A.jsxs)(`div`,{className:`switch-looking`,children:[(0,A.jsxs)(`span`,{style:{flex:1},children:[`Looking at `,(0,A.jsx)(`b`,{children:w?.holder?.name??i}),`'s copy`]}),(0,A.jsx)(`button`,{type:`button`,className:`ui-text-action`,onClick:()=>a(null),children:`Back to yours`})]}),(0,A.jsxs)(`div`,{className:`switch-where`,children:[(0,A.jsx)(sX,{}),(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`switch-label`,children:`Environment`}),(0,A.jsxs)(`div`,{className:`switch-choices`,children:[(0,A.jsx)(ph,{on:_,onClick:_?void 0:T,children:`production`}),(0,A.jsx)(ph,{on:!_,onClick:_?T:void 0,children:`sandbox`})]}),(0,A.jsx)(`div`,{className:`switch-note`,children:_?(0,A.jsxs)(A.Fragment,{children:[`Your sandbox copies are watched on your machine: `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall serve`}),`, then sandbox.`]}):(0,A.jsx)(A.Fragment,{children:`Production is watched on the gateway's console, signed in to.`})})]})]}),(0,A.jsxs)(`div`,{className:`switch-agents`,children:[(0,A.jsxs)(`div`,{className:`switch-label`,children:[`agents in `,g,` · `,r]}),s&&C.length===0&&(0,A.jsx)(`div`,{className:`switch-empty`,children:Am===`local`?(0,A.jsxs)(A.Fragment,{children:[`Nothing is running here. `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start`}),` in a project puts its agents on this list.`]}):(0,A.jsxs)(A.Fragment,{children:[`Nothing is running in production: `,(0,A.jsx)(`span`,{className:`ui-fixed`,children:`pinecall start --prod`}),` on your server holds it, on a server token.`]})}),(0,A.jsx)(`div`,{className:`switch-list`,children:C.map(t=>{let r=y(t),i=b(t),o=x(t);return(0,A.jsxs)(`button`,{type:`button`,className:o?`switch-card switch-card-here`:`switch-card`,disabled:!i,title:i?void 0:`their copy: it answers them, and they open it from their own console`,onClick:()=>{l(!1),_||a(r===n?null:r),t.slug!==e&&u(`/a/${t.slug}/${m}`)},children:[(0,A.jsx)(bh,{tone:`green`}),(0,A.jsxs)(`span`,{style:{minWidth:0,flex:1},children:[(0,A.jsx)(`span`,{className:`switch-card-name`,children:t.slug}),(0,A.jsxs)(`span`,{className:`switch-card-sub`,children:[S(t),` · `,t.channels.join(` · `)||`no doors`]})]}),(0,A.jsx)(`span`,{className:`switch-card-open`,children:o?`Viewing`:i?`Open`:`Theirs`})]},`${t.slug}:${r??`org`}`)})})]})]})]})}function sX(){let{orgs:e}=wb(),{moveTo:t}=Yh(),[n,r]=(0,D.useState)(!1),[i,a]=(0,D.useState)(null);if(Am!==`hosted`||e===null||e.length<2)return null;let o=async e=>{r(!0),a(null);try{await t(e)}catch(e){a(e instanceof ta?e.message:String(e)),r(!1)}};return(0,A.jsxs)(`div`,{children:[(0,A.jsx)(`div`,{className:`switch-label`,children:`Organization`}),(0,A.jsx)(`div`,{className:`switch-choices`,children:e.map(e=>(0,A.jsx)(ph,{on:e.here,disabled:n,title:e.member===!1?`as the box's operator`:e.role,onClick:()=>!e.here&&void o(e.org),children:e.slug??e.name??e.org},e.org))}),i!==null&&(0,A.jsx)(`div`,{className:`ui-refused`,style:{marginTop:6},children:i})]})}function cX(){let e=(0,D.useSyncExternalStore)(Da,Ta)===`dark`?`light`:`dark`;return(0,A.jsx)(`button`,{type:`button`,className:`top-theme`,onClick:()=>Ea(),"aria-label":`Switch to the ${e} theme`,title:`${e===`dark`?`Dark`:`Light`} theme`,children:(0,A.jsx)(_h,{name:e===`dark`?`moon`:`sun`})})}function lX(e,t){let n=e.split(`/`).filter(Boolean);if(t!==``){let e=Rm.find(e=>e.path===n[2]);return e===void 0?`Talk`:e.key===`sessions`&&n[3]!==void 0?`Session`:e.name}if(n[0]===`cli`)return`Sign in a terminal`;if(n[0]===`box`){let e=Lm.find(e=>e.path===`box/${n[1]??``}`);return e===void 0?`Box`:e.key===`box-orgs`&&n[2]!==void 0?`Organization`:e.name}let r=Im.find(e=>e.path===(n[0]??``));return r===void 0?`Home`:r.key===`sessions`&&n[1]!==void 0?`Session`:r.key===`numbers`?`Phone numbers`:r.name}function uX({agent:e}){let t=Wh(),n=km(),{pathname:r}=gr(),i=e===``?r.startsWith(`/box/`)?`box`:t===null?``:Gh(t):e;return(0,A.jsxs)(`header`,{className:`top`,children:[i!==``&&(0,A.jsxs)(`span`,{className:`top-crumb`,children:[i,` /`]}),(0,A.jsx)(`span`,{className:`top-title`,children:lX(r,e)}),(0,A.jsxs)(`div`,{className:`top-right`,children:[(0,A.jsx)(oX,{agent:e}),(0,A.jsx)(cX,{}),Am===`hosted`&&(0,A.jsx)(`button`,{type:`button`,className:`top-leave`,onClick:n,children:`Sign out`})]})]})}var dX=`No agent called {agent} is held here`;function fX(){return(0,A.jsx)(Cb,{children:(0,A.jsx)(sE,{children:(0,A.jsx)(pX,{})})})}function pX(){let e=Sr().agent??``,{agents:t,agentsLoaded:n}=wb(),[r,i]=(0,D.useState)(!1),a=e!==``&&n&&!t.some(t=>t.slug===e);return(0,D.useEffect)(()=>{let e=e=>{(e.metaKey||e.ctrlKey)&&e.key.toLowerCase()===`k`&&(e.preventDefault(),i(e=>!e))};return document.addEventListener(`keydown`,e),()=>document.removeEventListener(`keydown`,e)},[]),(0,A.jsxs)(`div`,{className:`frame`,children:[(0,A.jsx)(tX,{agent:a?``:e,onSearch:()=>i(!0)}),(0,A.jsxs)(`div`,{className:`frame-main`,children:[(0,A.jsx)(uX,{agent:e}),e!==``&&!a&&(0,A.jsx)(WY,{agent:e}),(0,A.jsx)(`div`,{className:`frame-screen`,children:a?(0,A.jsx)(mX,{agent:e}):(0,A.jsx)(Zr,{})})]}),(0,A.jsx)(XY,{}),r&&(0,A.jsx)(qY,{agent:a?``:e,onClose:()=>i(!1)})]})}function mX({agent:e}){return(0,A.jsxs)(`p`,{className:`missing`,children:[dX.replace(`{agent}`,e),Am===`local`?" — no copy of yours is running. Start `pinecall start` in the project, and it appears.":" — nothing by that name is deployed in this org. Check the org you signed in with; a copy you are running yourself is on your own machine, at `pinecall serve`."]})}var hX={home:(0,A.jsx)(uW,{}),agents:(0,A.jsx)(lx,{}),live:(0,A.jsx)(jU,{}),sessions:(0,A.jsx)(UU,{}),personas:(0,A.jsx)(Cq,{}),simulations:(0,A.jsx)(Mq,{}),"org-evals":(0,A.jsx)(UT,{}),"org-memory":(0,A.jsx)(aE,{}),"org-docs":(0,A.jsx)(wE,{}),numbers:(0,A.jsx)(yG,{}),phone:(0,A.jsx)(xG,{}),tokens:(0,A.jsx)(hW,{}),providers:(0,A.jsx)(jW,{}),team:(0,A.jsx)(mY,{}),usage:(0,A.jsx)(MY,{}),lexicon:(0,A.jsx)(wW,{})},gX={"box-orgs":(0,A.jsx)(dC,{children:(0,A.jsx)(kS,{})}),"box-fleet":(0,A.jsx)(dC,{children:(0,A.jsx)(Nx,{})}),"box-routes":(0,A.jsx)(dC,{children:(0,A.jsx)(NS,{})}),"box-usage":(0,A.jsx)(dC,{children:(0,A.jsx)(cC,{})}),"box-settings":(0,A.jsx)(dC,{children:(0,A.jsx)(rC,{})})},_X={talk:(0,A.jsx)(zJ,{}),devchat:(0,A.jsx)(mT,{}),calls:(0,A.jsx)(nw,{}),sessions:(0,A.jsx)(WG,{}),settings:(0,A.jsx)(hJ,{}),pipeline:(0,A.jsx)(UG,{}),docs:(0,A.jsx)(eG,{}),memory:(0,A.jsx)(aG,{}),evals:(0,A.jsx)(bD,{}),widget:(0,A.jsx)(HY,{})},vX={devchat:(0,A.jsx)(mT,{}),calls:(0,A.jsx)(nw,{}),sessions:(0,A.jsx)(UK,{})},yX={live:(0,A.jsx)(jU,{}),sessions:(0,A.jsx)(UK,{}),simulations:(0,A.jsx)(Mq,{}),personas:(0,A.jsx)(Cq,{})};function bX(e,t){return zm(e,Am,!0).flatMap(e=>{let n=t[e.key];if(e.path===``)return[{index:!0,element:n}];let r=(t===_X?vX:yX)[e.key];return r===void 0?[{path:e.path,element:n}]:[{path:e.path,element:n},{path:`${e.path}/:call`,element:r}]})}var xX=Vi([{path:`/`,element:(0,A.jsx)(fX,{}),children:[...bX(Im,hX),...bX(Lm,gX),...Am===`hosted`?[{path:`box/orgs/:org`,element:(0,A.jsx)(dC,{children:(0,A.jsx)(DS,{})})}]:[],...Am===`hosted`?[{path:`cli`,element:(0,A.jsx)(QJ,{})}]:[],{path:`docs/:base`,element:(0,A.jsx)(yE,{})}]},{path:`/a/:agent`,element:(0,A.jsx)(fX,{}),children:[{index:!0,element:(0,A.jsx)(Xr,{to:`talk`,replace:!0})},...bX(Rm,_X)]},{path:`/a/:agent/widget/preview`,element:(0,A.jsx)(UY,{})},{path:`*`,element:(0,A.jsx)(Xr,{to:`/`,replace:!0})}],{basename:`/`}),SX=yp({version:P(),cloud:L(),signup:L(),min_password:F(),mail:L().optional(),google:L().optional()});async function CX(e){try{let t=await fetch(new URL(`${e.replace(/\/$/,``)}/.well-known/pinecall`,window.location.origin));return SX.parse(await pa(t))}catch{return{version:``,cloud:!1,signup:!1,min_password:0}}}function wX({base:e,onSigned:t}){let[n,r]=(0,D.useState)(``),[i,a]=(0,D.useState)(``),[o,s]=(0,D.useState)(``),[c,l]=(0,D.useState)(!1),[u,d]=(0,D.useState)(()=>new URLSearchParams(window.location.search).get(`refused`)),[f,p]=(0,D.useState)(!1),[m,h]=(0,D.useState)(!1),[g,_]=(0,D.useState)(null),[v,y]=(0,D.useState)(!0),b=(0,D.useRef)(``),[x,S]=(0,D.useState)(!1),[C,w]=(0,D.useState)(null),[T,ee]=(0,D.useState)(null),[te,ne]=(0,D.useState)(!1);(0,D.useEffect)(()=>{let t=!1;return gm(e).then(e=>{t||S(e)}),CX(e).then(e=>{t||h(e.google===!0)}),()=>{t=!0}},[e]);let re=async()=>{if(ee(null),w(null),i.trim()===``){ee(`Type your work email first: it says which workspace signs you in.`);return}ne(!0);try{let t=await _m(e,i.trim()),n=t[0];t.length===1&&n!==void 0?window.location.assign(vm(e,n.slug??n.org)):t.length===0?ee(`No workspace signs in with a provider for that address.`):w(t)}catch(e){ee(e instanceof ta?e.message:String(e))}finally{ne(!1)}},E=async()=>{let t=`${i.trim()}\n${o}`;if(i.trim()!==``&&o!==``&&t!==b.current){b.current=t;try{let t=await pm(e,i.trim(),o);if(t===null){y(!1);return}_(t);let a=t[0];t.length>0&&!t.some(e=>(e.slug??e.org)===n)&&a!==void 0&&r(a.slug??a.org)}catch{_(null)}}},ie=async r=>{r.preventDefault(),l(!0),d(null);try{t(await sm(e,{org:n.trim(),email:i.trim(),password:o}))}catch(e){d(e instanceof ta?e.message:String(e))}finally{l(!1)}};return(0,A.jsx)(Cm,{children:(0,A.jsxs)(`form`,{onSubmit:e=>void ie(e),children:[(0,A.jsx)(`h1`,{className:`login-title`,children:`Sign in`}),(0,A.jsx)(`p`,{className:`login-lede`,children:`Use the email and password you were invited with.`}),(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-email`,children:`Email`}),(0,A.jsx)(`input`,{id:`login-email`,className:`login-input`,type:`email`,value:i,onChange:e=>a(e.target.value),autoComplete:`username`,autoFocus:!0,required:!0}),(0,A.jsxs)(`div`,{className:`login-label-row`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-password`,children:`Password`}),(0,A.jsx)(`button`,{type:`button`,className:`login-link`,onClick:()=>p(!f),children:`Forgot password`})]}),(0,A.jsx)(`input`,{id:`login-password`,className:`login-input login-input-secret`,type:`password`,value:o,onChange:e=>s(e.target.value),onBlur:()=>void E(),autoComplete:`current-password`,required:!0}),f&&(0,A.jsx)(`p`,{className:`login-forgot`,children:`Ask an admin of your workspace: from Team they hand you a one-use link where you choose a new password.`}),g!==null&&g.length>0?(0,A.jsxs)(A.Fragment,{children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-org`,children:`Workspace`}),(0,A.jsxs)(`div`,{className:`login-workspace`,children:[(0,A.jsx)(`span`,{className:`login-workspace-tile`,children:(n[0]??`·`).toUpperCase()}),(0,A.jsx)(`select`,{id:`login-org`,className:`login-workspace-input`,value:n,onChange:e=>r(e.target.value),disabled:g.length===1,children:g.map(e=>(0,A.jsx)(`option`,{value:e.slug??e.org,children:e.name??e.slug??e.org},e.org))})]})]}):!v&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`div`,{className:`login-label-row`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-org`,children:`Workspace`}),(0,A.jsx)(`span`,{className:`login-hint`,children:`only if you belong to several`})]}),(0,A.jsxs)(`div`,{className:`login-workspace`,children:[(0,A.jsx)(`span`,{className:`login-workspace-tile`,children:(n.trim()[0]??`·`).toUpperCase()}),(0,A.jsx)(`input`,{id:`login-org`,className:`login-workspace-input`,value:n,onChange:e=>r(e.target.value),autoComplete:`organization`,placeholder:`the oldest of yours`})]})]}),(0,A.jsx)(`button`,{className:`login-go`,type:`submit`,disabled:c,children:c?`Signing in…`:`Sign in`}),u!==null&&(0,A.jsx)(`p`,{className:`login-refused`,children:u}),(x||m)&&(0,A.jsxs)(`div`,{className:`login-or`,children:[(0,A.jsx)(`span`,{className:`login-or-line`}),(0,A.jsx)(`span`,{className:`login-or-word`,children:`or`}),(0,A.jsx)(`span`,{className:`login-or-line`})]}),m&&(0,A.jsxs)(`button`,{type:`button`,className:`login-sso login-google`,onClick:()=>window.location.assign(ym(e)),children:[(0,A.jsx)(TX,{}),`Continue with Google`]}),x&&(0,A.jsxs)(A.Fragment,{children:[(0,A.jsxs)(`button`,{type:`button`,className:`login-sso`,disabled:te,onClick:()=>void re(),children:[(0,A.jsx)(`span`,{className:`login-sso-glyph`}),te?`Looking for your workspace…`:`Continue with SSO`]}),C!==null&&(0,A.jsxs)(`div`,{className:`login-sso-pick`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`login-sso-org`,children:`Which workspace`}),(0,A.jsxs)(`div`,{className:`login-workspace`,children:[(0,A.jsx)(`span`,{className:`login-workspace-tile`,children:`·`}),(0,A.jsxs)(`select`,{id:`login-sso-org`,className:`login-workspace-input`,defaultValue:``,onChange:t=>t.target.value!==``&&window.location.assign(vm(e,t.target.value)),children:[(0,A.jsx)(`option`,{value:``,disabled:!0,children:`Choose one…`}),C.map(e=>(0,A.jsx)(`option`,{value:e.slug??e.org,children:e.name??e.slug??e.org},e.org))]})]})]}),T!==null&&(0,A.jsx)(`p`,{className:`login-sso-note`,children:T})]}),(0,A.jsx)(`p`,{className:`login-note`,children:`Invited and no password yet? Open the link in your invitation — that is where you choose one.`})]})})}function TX(){return(0,A.jsxs)(`svg`,{width:`16`,height:`16`,viewBox:`0 0 48 48`,"aria-hidden":!0,children:[(0,A.jsx)(`path`,{fill:`#EA4335`,d:`M24 9.5c3.54 0 6.71 1.22 9.21 3.6l6.85-6.85C35.9 2.38 30.47 0 24 0 14.62 0 6.51 5.38 2.56 13.22l7.98 6.19C12.43 13.72 17.74 9.5 24 9.5z`}),(0,A.jsx)(`path`,{fill:`#4285F4`,d:`M46.98 24.55c0-1.57-.15-3.09-.38-4.55H24v9.02h12.94c-.58 2.96-2.26 5.48-4.78 7.18l7.73 6c4.51-4.18 7.09-10.36 7.09-17.65z`}),(0,A.jsx)(`path`,{fill:`#FBBC05`,d:`M10.53 28.59c-.48-1.45-.76-2.99-.76-4.59s.27-3.14.76-4.59l-7.98-6.19C.92 16.46 0 20.12 0 24c0 3.88.92 7.54 2.56 10.78l7.97-6.19z`}),(0,A.jsx)(`path`,{fill:`#34A853`,d:`M24 48c6.48 0 11.93-2.13 15.89-5.81l-7.73-6c-2.15 1.45-4.92 2.3-8.16 2.3-6.26 0-11.57-4.22-13.47-9.91l-7.98 6.19C6.51 42.62 14.62 48 24 48z`})]})}function EX({base:e,token:t,onSigned:n}){let[r,i]=(0,D.useState)(``),[a,o]=(0,D.useState)(``),[s,c]=(0,D.useState)(null),[l,u]=(0,D.useState)(!1),[d,f]=(0,D.useState)(null);(0,D.useEffect)(()=>{let t=!1;return CX(e).then(e=>{t||c(e.min_password)}),()=>{t=!0}},[e]);let p=async i=>{if(i.preventDefault(),r!==a){f(`The two passwords differ.`);return}u(!0),f(null);try{n(await dm(e,t,r))}catch(e){f(e instanceof ta?e.message:String(e))}finally{u(!1)}};return(0,A.jsx)(Cm,{children:(0,A.jsxs)(`form`,{onSubmit:e=>void p(e),children:[(0,A.jsx)(`h1`,{className:`login-title`,children:`Choose your password`}),(0,A.jsx)(`p`,{className:`login-lede`,children:`This link came from an invitation, or from an admin resetting your password. It opens once; the password you pick here is the one you sign in with from now on.`}),(0,A.jsxs)(`div`,{className:`login-label-row`,children:[(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`accept-password`,children:`Password`}),s!==null&&s>0&&(0,A.jsxs)(`span`,{className:`login-hint`,children:[s,` characters at least`]})]}),(0,A.jsx)(`input`,{id:`accept-password`,className:`login-input login-input-secret`,type:`password`,value:r,minLength:s??void 0,onChange:e=>i(e.target.value),autoComplete:`new-password`,autoFocus:!0,required:!0}),(0,A.jsx)(`label`,{className:`login-label`,htmlFor:`accept-again`,children:`Again`}),(0,A.jsx)(`input`,{id:`accept-again`,className:`login-input login-input-secret`,type:`password`,value:a,onChange:e=>o(e.target.value),autoComplete:`new-password`,required:!0}),(0,A.jsx)(`button`,{className:`login-go`,type:`submit`,disabled:l,style:{marginTop:8},children:l?`Joining…`:`Join`}),d!==null&&(0,A.jsx)(`p`,{className:`login-refused`,children:d})]})})}var DX=document.getElementById(`root`);if(DX===null)throw Error(`index.html has no #root for the console to mount in`);wa();var OX=`login`,kX=/^\/invitations\/([^/]+)\/?$/;function AX(){let e=kX.exec(window.location.pathname);return e===null?null:decodeURIComponent(e[1]??``)}var jX=Mm[Am],MX=``;async function NX(){if(Am===`local`)return MX;let e=new URL(window.location.href),t=e.searchParams.get(OX);if(t!==null){e.searchParams.delete(OX),window.history.replaceState(null,``,e.toString());try{let e=await om(`/`,t);return Gm(e.key),e.key}catch{}}return Wm()}function PX({startingWith:e}){let[t,n]=(0,D.useState)(e),[r,i]=(0,D.useState)(()=>jX===`sandbox`?Jm():null),a=(0,D.useCallback)(e=>{Ym(e),i(e)},[]);aa(()=>{Km(),n(null)});let o=(0,D.useCallback)(async e=>{if(t===null)return;let n=await um({base:`/`,key:t},e);Ym(null),Gm(n.key),window.location.assign(`/`)},[t]),s=(0,D.useMemo)(()=>({world:jX,moveTo:o,corner:r,lookInto:a}),[o,r,a]),c=(0,D.useMemo)(()=>({base:`/`,key:t??``,corner:r,...Am===`hosted`?{world:jX}:{}}),[t,r]),l=(0,D.useCallback)(()=>{Km(),Ym(null),i(null),n(null)},[]),u=e=>{Gm(e.key),n(e.key)};if(t===null){if(Am===`local`)return(0,A.jsx)(Em,{});let e=AX();return e===null?(0,A.jsx)(wX,{base:`/`,onSigned:u}):(0,A.jsx)(EX,{base:`/`,token:e,onSigned:e=>{window.history.replaceState(null,``,`/`),u(e)}})}return(0,A.jsx)(Aa,{value:c,children:(0,A.jsx)(Uh,{children:(0,A.jsx)(Jh,{value:s,children:(0,A.jsx)(Om,{value:l,children:(0,A.jsx)(Kr,{router:xX})})})})})}NX().then(e=>{(0,hi.createRoot)(DX).render((0,A.jsx)(D.StrictMode,{children:(0,A.jsx)(PX,{startingWith:e})}))});