@mcpjam/inspector 1.5.13 → 1.5.14
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/client/assets/code-block-OCS4YCEC-D6XFrMiK.js +3 -0
- package/dist/client/assets/{code-block-OCS4YCEC-C2ZGbWWM.js.map → code-block-OCS4YCEC-D6XFrMiK.js.map} +1 -1
- package/dist/client/assets/{index-D8kYCuS4.js → index-BUVtQr4n.js} +6 -6
- package/dist/client/assets/{index-D8kYCuS4.js.map → index-BUVtQr4n.js.map} +1 -1
- package/dist/client/index.html +1 -1
- package/package.json +1 -1
- package/dist/client/assets/code-block-OCS4YCEC-C2ZGbWWM.js +0 -3
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};e.SENTRY_RELEASE={id:"ffa2f33358651519c6cb6e9899235e50a24a568b"};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="918b52a3-96f2-4c9e-8353-4254ab313d90",e._sentryDebugIdIdentifier="sentry-dbid-918b52a3-96f2-4c9e-8353-4254ab313d90")}catch{}})();function KUe(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in e)){const a=Object.getOwnPropertyDescriptor(r,i);a&&Object.defineProperty(e,i,a.get?a:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const s of a.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(i){if(i.ep)return;i.ep=!0;const a=n(i);fetch(i.href,a)}})();var FE=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var oM={exports:{}},Jb={};var nee;function ZUe(){if(nee)return Jb;nee=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,a){var s=null;if(a!==void 0&&(s=""+a),i.key!==void 0&&(s=""+i.key),"key"in i){a={};for(var o in i)o!=="key"&&(a[o]=i[o])}else a=i;return i=a.ref,{$$typeof:e,type:r,key:s,ref:i!==void 0?i:null,props:a}}return Jb.Fragment=t,Jb.jsx=n,Jb.jsxs=n,Jb}var ree;function YUe(){return ree||(ree=1,oM.exports=ZUe()),oM.exports}var l=YUe(),lM={exports:{}},kn={};var iee;function XUe(){if(iee)return kn;iee=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),s=Symbol.for("react.context"),o=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),c=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),f=Symbol.iterator;function p(L){return L===null||typeof L!="object"?null:(L=f&&L[f]||L["@@iterator"],typeof L=="function"?L:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,v={};function x(L,Y,G){this.props=L,this.context=Y,this.refs=v,this.updater=G||m}x.prototype.isReactComponent={},x.prototype.setState=function(L,Y){if(typeof L!="object"&&typeof L!="function"&&L!=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,L,Y,"setState")},x.prototype.forceUpdate=function(L){this.updater.enqueueForceUpdate(this,L,"forceUpdate")};function _(){}_.prototype=x.prototype;function S(L,Y,G){this.props=L,this.context=Y,this.refs=v,this.updater=G||m}var w=S.prototype=new _;w.constructor=S,y(w,x.prototype),w.isPureReactComponent=!0;var T=Array.isArray,N={H:null,A:null,T:null,S:null,V:null},E=Object.prototype.hasOwnProperty;function A(L,Y,G,P,V,K){return G=K.ref,{$$typeof:e,type:L,key:Y,ref:G!==void 0?G:null,props:K}}function I(L,Y){return A(L.type,Y,void 0,void 0,void 0,L.props)}function M(L){return typeof L=="object"&&L!==null&&L.$$typeof===e}function $(L){var Y={"=":"=0",":":"=2"};return"$"+L.replace(/[=:]/g,function(G){return Y[G]})}var O=/\/+/g;function R(L,Y){return typeof L=="object"&&L!==null&&L.key!=null?$(""+L.key):Y.toString(36)}function U(){}function z(L){switch(L.status){case"fulfilled":return L.value;case"rejected":throw L.reason;default:switch(typeof L.status=="string"?L.then(U,U):(L.status="pending",L.then(function(Y){L.status==="pending"&&(L.status="fulfilled",L.value=Y)},function(Y){L.status==="pending"&&(L.status="rejected",L.reason=Y)})),L.status){case"fulfilled":return L.value;case"rejected":throw L.reason}}throw L}function F(L,Y,G,P,V){var K=typeof L;(K==="undefined"||K==="boolean")&&(L=null);var Q=!1;if(L===null)Q=!0;else switch(K){case"bigint":case"string":case"number":Q=!0;break;case"object":switch(L.$$typeof){case e:case t:Q=!0;break;case d:return Q=L._init,F(Q(L._payload),Y,G,P,V)}}if(Q)return V=V(L),Q=P===""?"."+R(L,0):P,T(V)?(G="",Q!=null&&(G=Q.replace(O,"$&/")+"/"),F(V,Y,G,"",function(ee){return ee})):V!=null&&(M(V)&&(V=I(V,G+(V.key==null||L&&L.key===V.key?"":(""+V.key).replace(O,"$&/")+"/")+Q)),Y.push(V)),1;Q=0;var oe=P===""?".":P+":";if(T(L))for(var re=0;re<L.length;re++)P=L[re],K=oe+R(P,re),Q+=F(P,Y,G,K,V);else if(re=p(L),typeof re=="function")for(L=re.call(L),re=0;!(P=L.next()).done;)P=P.value,K=oe+R(P,re++),Q+=F(P,Y,G,K,V);else if(K==="object"){if(typeof L.then=="function")return F(z(L),Y,G,P,V);throw Y=String(L),Error("Objects are not valid as a React child (found: "+(Y==="[object Object]"?"object with keys {"+Object.keys(L).join(", ")+"}":Y)+"). If you meant to render a collection of children, use an array instead.")}return Q}function D(L,Y,G){if(L==null)return L;var P=[],V=0;return F(L,P,"","",function(K){return Y.call(G,K,V++)}),P}function W(L){if(L._status===-1){var Y=L._result;Y=Y(),Y.then(function(G){(L._status===0||L._status===-1)&&(L._status=1,L._result=G)},function(G){(L._status===0||L._status===-1)&&(L._status=2,L._result=G)}),L._status===-1&&(L._status=0,L._result=Y)}if(L._status===1)return L._result.default;throw L._result}var q=typeof reportError=="function"?reportError:function(L){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var Y=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof L=="object"&&L!==null&&typeof L.message=="string"?String(L.message):String(L),error:L});if(!window.dispatchEvent(Y))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",L);return}console.error(L)};function X(){}return kn.Children={map:D,forEach:function(L,Y,G){D(L,function(){Y.apply(this,arguments)},G)},count:function(L){var Y=0;return D(L,function(){Y++}),Y},toArray:function(L){return D(L,function(Y){return Y})||[]},only:function(L){if(!M(L))throw Error("React.Children.only expected to receive a single React element child.");return L}},kn.Component=x,kn.Fragment=n,kn.Profiler=i,kn.PureComponent=S,kn.StrictMode=r,kn.Suspense=u,kn.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=N,kn.__COMPILER_RUNTIME={__proto__:null,c:function(L){return N.H.useMemoCache(L)}},kn.cache=function(L){return function(){return L.apply(null,arguments)}},kn.cloneElement=function(L,Y,G){if(L==null)throw Error("The argument must be a React element, but you passed "+L+".");var P=y({},L.props),V=L.key,K=void 0;if(Y!=null)for(Q in Y.ref!==void 0&&(K=void 0),Y.key!==void 0&&(V=""+Y.key),Y)!E.call(Y,Q)||Q==="key"||Q==="__self"||Q==="__source"||Q==="ref"&&Y.ref===void 0||(P[Q]=Y[Q]);var Q=arguments.length-2;if(Q===1)P.children=G;else if(1<Q){for(var oe=Array(Q),re=0;re<Q;re++)oe[re]=arguments[re+2];P.children=oe}return A(L.type,V,void 0,void 0,K,P)},kn.createContext=function(L){return L={$$typeof:s,_currentValue:L,_currentValue2:L,_threadCount:0,Provider:null,Consumer:null},L.Provider=L,L.Consumer={$$typeof:a,_context:L},L},kn.createElement=function(L,Y,G){var P,V={},K=null;if(Y!=null)for(P in Y.key!==void 0&&(K=""+Y.key),Y)E.call(Y,P)&&P!=="key"&&P!=="__self"&&P!=="__source"&&(V[P]=Y[P]);var Q=arguments.length-2;if(Q===1)V.children=G;else if(1<Q){for(var oe=Array(Q),re=0;re<Q;re++)oe[re]=arguments[re+2];V.children=oe}if(L&&L.defaultProps)for(P in Q=L.defaultProps,Q)V[P]===void 0&&(V[P]=Q[P]);return A(L,K,void 0,void 0,null,V)},kn.createRef=function(){return{current:null}},kn.forwardRef=function(L){return{$$typeof:o,render:L}},kn.isValidElement=M,kn.lazy=function(L){return{$$typeof:d,_payload:{_status:-1,_result:L},_init:W}},kn.memo=function(L,Y){return{$$typeof:c,type:L,compare:Y===void 0?null:Y}},kn.startTransition=function(L){var Y=N.T,G={};N.T=G;try{var P=L(),V=N.S;V!==null&&V(G,P),typeof P=="object"&&P!==null&&typeof P.then=="function"&&P.then(X,q)}catch(K){q(K)}finally{N.T=Y}},kn.unstable_useCacheRefresh=function(){return N.H.useCacheRefresh()},kn.use=function(L){return N.H.use(L)},kn.useActionState=function(L,Y,G){return N.H.useActionState(L,Y,G)},kn.useCallback=function(L,Y){return N.H.useCallback(L,Y)},kn.useContext=function(L){return N.H.useContext(L)},kn.useDebugValue=function(){},kn.useDeferredValue=function(L,Y){return N.H.useDeferredValue(L,Y)},kn.useEffect=function(L,Y,G){var P=N.H;if(typeof G=="function")throw Error("useEffect CRUD overload is not enabled in this build of React.");return P.useEffect(L,Y)},kn.useId=function(){return N.H.useId()},kn.useImperativeHandle=function(L,Y,G){return N.H.useImperativeHandle(L,Y,G)},kn.useInsertionEffect=function(L,Y){return N.H.useInsertionEffect(L,Y)},kn.useLayoutEffect=function(L,Y){return N.H.useLayoutEffect(L,Y)},kn.useMemo=function(L,Y){return N.H.useMemo(L,Y)},kn.useOptimistic=function(L,Y){return N.H.useOptimistic(L,Y)},kn.useReducer=function(L,Y,G){return N.H.useReducer(L,Y,G)},kn.useRef=function(L){return N.H.useRef(L)},kn.useState=function(L){return N.H.useState(L)},kn.useSyncExternalStore=function(L,Y,G){return N.H.useSyncExternalStore(L,Y,G)},kn.useTransition=function(){return N.H.useTransition()},kn.version="19.1.0",kn}var aee;function X2(){return aee||(aee=1,lM.exports=XUe()),lM.exports}var b=X2();const de=Jn(b),dO=KUe({__proto__:null,default:de},[b]);var uM={exports:{}},Qb={},cM={exports:{}},dM={};var see;function JUe(){return see||(see=1,(function(e){function t(D,W){var q=D.length;D.push(W);e:for(;0<q;){var X=q-1>>>1,L=D[X];if(0<i(L,W))D[X]=W,D[q]=L,q=X;else break e}}function n(D){return D.length===0?null:D[0]}function r(D){if(D.length===0)return null;var W=D[0],q=D.pop();if(q!==W){D[0]=q;e:for(var X=0,L=D.length,Y=L>>>1;X<Y;){var G=2*(X+1)-1,P=D[G],V=G+1,K=D[V];if(0>i(P,q))V<L&&0>i(K,P)?(D[X]=K,D[V]=q,X=V):(D[X]=P,D[G]=q,X=G);else if(V<L&&0>i(K,q))D[X]=K,D[V]=q,X=V;else break e}}return W}function i(D,W){var q=D.sortIndex-W.sortIndex;return q!==0?q:D.id-W.id}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 s=Date,o=s.now();e.unstable_now=function(){return s.now()-o}}var u=[],c=[],d=1,f=null,p=3,m=!1,y=!1,v=!1,x=!1,_=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;function T(D){for(var W=n(c);W!==null;){if(W.callback===null)r(c);else if(W.startTime<=D)r(c),W.sortIndex=W.expirationTime,t(u,W);else break;W=n(c)}}function N(D){if(v=!1,T(D),!y)if(n(u)!==null)y=!0,E||(E=!0,R());else{var W=n(c);W!==null&&F(N,W.startTime-D)}}var E=!1,A=-1,I=5,M=-1;function $(){return x?!0:!(e.unstable_now()-M<I)}function O(){if(x=!1,E){var D=e.unstable_now();M=D;var W=!0;try{e:{y=!1,v&&(v=!1,S(A),A=-1),m=!0;var q=p;try{t:{for(T(D),f=n(u);f!==null&&!(f.expirationTime>D&&$());){var X=f.callback;if(typeof X=="function"){f.callback=null,p=f.priorityLevel;var L=X(f.expirationTime<=D);if(D=e.unstable_now(),typeof L=="function"){f.callback=L,T(D),W=!0;break t}f===n(u)&&r(u),T(D)}else r(u);f=n(u)}if(f!==null)W=!0;else{var Y=n(c);Y!==null&&F(N,Y.startTime-D),W=!1}}break e}finally{f=null,p=q,m=!1}W=void 0}}finally{W?R():E=!1}}}var R;if(typeof w=="function")R=function(){w(O)};else if(typeof MessageChannel<"u"){var U=new MessageChannel,z=U.port2;U.port1.onmessage=O,R=function(){z.postMessage(null)}}else R=function(){_(O,0)};function F(D,W){A=_(function(){D(e.unstable_now())},W)}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(D){D.callback=null},e.unstable_forceFrameRate=function(D){0>D||125<D?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):I=0<D?Math.floor(1e3/D):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(D){switch(p){case 1:case 2:case 3:var W=3;break;default:W=p}var q=p;p=W;try{return D()}finally{p=q}},e.unstable_requestPaint=function(){x=!0},e.unstable_runWithPriority=function(D,W){switch(D){case 1:case 2:case 3:case 4:case 5:break;default:D=3}var q=p;p=D;try{return W()}finally{p=q}},e.unstable_scheduleCallback=function(D,W,q){var X=e.unstable_now();switch(typeof q=="object"&&q!==null?(q=q.delay,q=typeof q=="number"&&0<q?X+q:X):q=X,D){case 1:var L=-1;break;case 2:L=250;break;case 5:L=1073741823;break;case 4:L=1e4;break;default:L=5e3}return L=q+L,D={id:d++,callback:W,priorityLevel:D,startTime:q,expirationTime:L,sortIndex:-1},q>X?(D.sortIndex=q,t(c,D),n(u)===null&&D===n(c)&&(v?(S(A),A=-1):v=!0,F(N,q-X))):(D.sortIndex=L,t(u,D),y||m||(y=!0,E||(E=!0,R()))),D},e.unstable_shouldYield=$,e.unstable_wrapCallback=function(D){var W=p;return function(){var q=p;p=W;try{return D.apply(this,arguments)}finally{p=q}}}})(dM)),dM}var oee;function QUe(){return oee||(oee=1,cM.exports=JUe()),cM.exports}var fM={exports:{}},vs={};var lee;function e7e(){if(lee)return vs;lee=1;var e=X2();function t(u){var c="https://react.dev/errors/"+u;if(1<arguments.length){c+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)c+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+u+"; visit "+c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},i=Symbol.for("react.portal");function a(u,c,d){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:f==null?null:""+f,children:u,containerInfo:c,implementation:d}}var s=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function o(u,c){if(u==="font")return"";if(typeof c=="string")return c==="use-credentials"?c:""}return vs.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,vs.createPortal=function(u,c){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!c||c.nodeType!==1&&c.nodeType!==9&&c.nodeType!==11)throw Error(t(299));return a(u,c,null,d)},vs.flushSync=function(u){var c=s.T,d=r.p;try{if(s.T=null,r.p=2,u)return u()}finally{s.T=c,r.p=d,r.d.f()}},vs.preconnect=function(u,c){typeof u=="string"&&(c?(c=c.crossOrigin,c=typeof c=="string"?c==="use-credentials"?c:"":void 0):c=null,r.d.C(u,c))},vs.prefetchDNS=function(u){typeof u=="string"&&r.d.D(u)},vs.preinit=function(u,c){if(typeof u=="string"&&c&&typeof c.as=="string"){var d=c.as,f=o(d,c.crossOrigin),p=typeof c.integrity=="string"?c.integrity:void 0,m=typeof c.fetchPriority=="string"?c.fetchPriority:void 0;d==="style"?r.d.S(u,typeof c.precedence=="string"?c.precedence:void 0,{crossOrigin:f,integrity:p,fetchPriority:m}):d==="script"&&r.d.X(u,{crossOrigin:f,integrity:p,fetchPriority:m,nonce:typeof c.nonce=="string"?c.nonce:void 0})}},vs.preinitModule=function(u,c){if(typeof u=="string")if(typeof c=="object"&&c!==null){if(c.as==null||c.as==="script"){var d=o(c.as,c.crossOrigin);r.d.M(u,{crossOrigin:d,integrity:typeof c.integrity=="string"?c.integrity:void 0,nonce:typeof c.nonce=="string"?c.nonce:void 0})}}else c==null&&r.d.M(u)},vs.preload=function(u,c){if(typeof u=="string"&&typeof c=="object"&&c!==null&&typeof c.as=="string"){var d=c.as,f=o(d,c.crossOrigin);r.d.L(u,d,{crossOrigin:f,integrity:typeof c.integrity=="string"?c.integrity:void 0,nonce:typeof c.nonce=="string"?c.nonce:void 0,type:typeof c.type=="string"?c.type:void 0,fetchPriority:typeof c.fetchPriority=="string"?c.fetchPriority:void 0,referrerPolicy:typeof c.referrerPolicy=="string"?c.referrerPolicy:void 0,imageSrcSet:typeof c.imageSrcSet=="string"?c.imageSrcSet:void 0,imageSizes:typeof c.imageSizes=="string"?c.imageSizes:void 0,media:typeof c.media=="string"?c.media:void 0})}},vs.preloadModule=function(u,c){if(typeof u=="string")if(c){var d=o(c.as,c.crossOrigin);r.d.m(u,{as:typeof c.as=="string"&&c.as!=="script"?c.as:void 0,crossOrigin:d,integrity:typeof c.integrity=="string"?c.integrity:void 0})}else r.d.m(u)},vs.requestFormReset=function(u){r.d.r(u)},vs.unstable_batchedUpdates=function(u,c){return u(c)},vs.useFormState=function(u,c,d){return s.H.useFormState(u,c,d)},vs.useFormStatus=function(){return s.H.useHostTransitionStatus()},vs.version="19.1.0",vs}var uee;function nve(){if(uee)return fM.exports;uee=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),fM.exports=e7e(),fM.exports}var cee;function t7e(){if(cee)return Qb;cee=1;var e=QUe(),t=X2(),n=nve();function r(h){var g="https://react.dev/errors/"+h;if(1<arguments.length){g+="?args[]="+encodeURIComponent(arguments[1]);for(var k=2;k<arguments.length;k++)g+="&args[]="+encodeURIComponent(arguments[k])}return"Minified React error #"+h+"; visit "+g+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function i(h){return!(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11)}function a(h){var g=h,k=h;if(h.alternate)for(;g.return;)g=g.return;else{h=g;do g=h,(g.flags&4098)!==0&&(k=g.return),h=g.return;while(h)}return g.tag===3?k:null}function s(h){if(h.tag===13){var g=h.memoizedState;if(g===null&&(h=h.alternate,h!==null&&(g=h.memoizedState)),g!==null)return g.dehydrated}return null}function o(h){if(a(h)!==h)throw Error(r(188))}function u(h){var g=h.alternate;if(!g){if(g=a(h),g===null)throw Error(r(188));return g!==h?null:h}for(var k=h,C=g;;){var j=k.return;if(j===null)break;var B=j.alternate;if(B===null){if(C=j.return,C!==null){k=C;continue}break}if(j.child===B.child){for(B=j.child;B;){if(B===k)return o(j),h;if(B===C)return o(j),g;B=B.sibling}throw Error(r(188))}if(k.return!==C.return)k=j,C=B;else{for(var ae=!1,pe=j.child;pe;){if(pe===k){ae=!0,k=j,C=B;break}if(pe===C){ae=!0,C=j,k=B;break}pe=pe.sibling}if(!ae){for(pe=B.child;pe;){if(pe===k){ae=!0,k=B,C=j;break}if(pe===C){ae=!0,C=B,k=j;break}pe=pe.sibling}if(!ae)throw Error(r(189))}}if(k.alternate!==C)throw Error(r(190))}if(k.tag!==3)throw Error(r(188));return k.stateNode.current===k?h:g}function c(h){var g=h.tag;if(g===5||g===26||g===27||g===6)return h;for(h=h.child;h!==null;){if(g=c(h),g!==null)return g;h=h.sibling}return null}var d=Object.assign,f=Symbol.for("react.element"),p=Symbol.for("react.transitional.element"),m=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),v=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),_=Symbol.for("react.provider"),S=Symbol.for("react.consumer"),w=Symbol.for("react.context"),T=Symbol.for("react.forward_ref"),N=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),A=Symbol.for("react.memo"),I=Symbol.for("react.lazy"),M=Symbol.for("react.activity"),$=Symbol.for("react.memo_cache_sentinel"),O=Symbol.iterator;function R(h){return h===null||typeof h!="object"?null:(h=O&&h[O]||h["@@iterator"],typeof h=="function"?h:null)}var U=Symbol.for("react.client.reference");function z(h){if(h==null)return null;if(typeof h=="function")return h.$$typeof===U?null:h.displayName||h.name||null;if(typeof h=="string")return h;switch(h){case y:return"Fragment";case x:return"Profiler";case v:return"StrictMode";case N:return"Suspense";case E:return"SuspenseList";case M:return"Activity"}if(typeof h=="object")switch(h.$$typeof){case m:return"Portal";case w:return(h.displayName||"Context")+".Provider";case S:return(h._context.displayName||"Context")+".Consumer";case T:var g=h.render;return h=h.displayName,h||(h=g.displayName||g.name||"",h=h!==""?"ForwardRef("+h+")":"ForwardRef"),h;case A:return g=h.displayName||null,g!==null?g:z(h.type)||"Memo";case I:g=h._payload,h=h._init;try{return z(h(g))}catch{}}return null}var F=Array.isArray,D=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,W=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,q={pending:!1,data:null,method:null,action:null},X=[],L=-1;function Y(h){return{current:h}}function G(h){0>L||(h.current=X[L],X[L]=null,L--)}function P(h,g){L++,X[L]=h.current,h.current=g}var V=Y(null),K=Y(null),Q=Y(null),oe=Y(null);function re(h,g){switch(P(Q,g),P(K,h),P(V,null),g.nodeType){case 9:case 11:h=(h=g.documentElement)&&(h=h.namespaceURI)?IQ(h):0;break;default:if(h=g.tagName,g=g.namespaceURI)g=IQ(g),h=jQ(g,h);else switch(h){case"svg":h=1;break;case"math":h=2;break;default:h=0}}G(V),P(V,h)}function ee(){G(V),G(K),G(Q)}function le(h){h.memoizedState!==null&&P(oe,h);var g=V.current,k=jQ(g,h.type);g!==k&&(P(K,h),P(V,k))}function te(h){K.current===h&&(G(V),G(K)),oe.current===h&&(G(oe),Wb._currentValue=q)}var Z=Object.prototype.hasOwnProperty,ne=e.unstable_scheduleCallback,J=e.unstable_cancelCallback,se=e.unstable_shouldYield,ie=e.unstable_requestPaint,he=e.unstable_now,ye=e.unstable_getCurrentPriorityLevel,Ne=e.unstable_ImmediatePriority,ce=e.unstable_UserBlockingPriority,Te=e.unstable_NormalPriority,we=e.unstable_LowPriority,Oe=e.unstable_IdlePriority,Ue=e.log,Me=e.unstable_setDisableYieldValue,be=null,je=null;function Xe(h){if(typeof Ue=="function"&&Me(h),je&&typeof je.setStrictMode=="function")try{je.setStrictMode(be,h)}catch{}}var ue=Math.clz32?Math.clz32:Ce,fe=Math.log,xe=Math.LN2;function Ce(h){return h>>>=0,h===0?32:31-(fe(h)/xe|0)|0}var He=256,Ze=4194304;function st(h){var g=h&42;if(g!==0)return g;switch(h&-h){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:case 262144:case 524288:case 1048576:case 2097152:return h&4194048;case 4194304:case 8388608:case 16777216:case 33554432:return h&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return h}}function ot(h,g,k){var C=h.pendingLanes;if(C===0)return 0;var j=0,B=h.suspendedLanes,ae=h.pingedLanes;h=h.warmLanes;var pe=C&134217727;return pe!==0?(C=pe&~B,C!==0?j=st(C):(ae&=pe,ae!==0?j=st(ae):k||(k=pe&~h,k!==0&&(j=st(k))))):(pe=C&~B,pe!==0?j=st(pe):ae!==0?j=st(ae):k||(k=C&~h,k!==0&&(j=st(k)))),j===0?0:g!==0&&g!==j&&(g&B)===0&&(B=j&-j,k=g&-g,B>=k||B===32&&(k&4194048)!==0)?g:j}function mt(h,g){return(h.pendingLanes&~(h.suspendedLanes&~h.pingedLanes)&g)===0}function Bt(h,g){switch(h){case 1:case 2:case 4:case 8:case 64:return g+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 g+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 Mt(){var h=He;return He<<=1,(He&4194048)===0&&(He=256),h}function It(){var h=Ze;return Ze<<=1,(Ze&62914560)===0&&(Ze=4194304),h}function gn(h){for(var g=[],k=0;31>k;k++)g.push(h);return g}function nt(h,g){h.pendingLanes|=g,g!==268435456&&(h.suspendedLanes=0,h.pingedLanes=0,h.warmLanes=0)}function yt(h,g,k,C,j,B){var ae=h.pendingLanes;h.pendingLanes=k,h.suspendedLanes=0,h.pingedLanes=0,h.warmLanes=0,h.expiredLanes&=k,h.entangledLanes&=k,h.errorRecoveryDisabledLanes&=k,h.shellSuspendCounter=0;var pe=h.entanglements,ke=h.expirationTimes,ze=h.hiddenUpdates;for(k=ae&~k;0<k;){var Ye=31-ue(k),et=1<<Ye;pe[Ye]=0,ke[Ye]=-1;var Fe=ze[Ye];if(Fe!==null)for(ze[Ye]=null,Ye=0;Ye<Fe.length;Ye++){var Be=Fe[Ye];Be!==null&&(Be.lane&=-536870913)}k&=~et}C!==0&&ut(h,C,0),B!==0&&j===0&&h.tag!==0&&(h.suspendedLanes|=B&~(ae&~g))}function ut(h,g,k){h.pendingLanes|=g,h.suspendedLanes&=~g;var C=31-ue(g);h.entangledLanes|=g,h.entanglements[C]=h.entanglements[C]|1073741824|k&4194090}function vt(h,g){var k=h.entangledLanes|=g;for(h=h.entanglements;k;){var C=31-ue(k),j=1<<C;j&g|h[C]&g&&(h[C]|=g),k&=~j}}function Wt(h){switch(h){case 2:h=1;break;case 8:h=4;break;case 32:h=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:h=128;break;case 268435456:h=134217728;break;default:h=0}return h}function Qn(h){return h&=-h,2<h?8<h?(h&134217727)!==0?32:268435456:8:2}function Gi(){var h=W.p;return h!==0?h:(h=window.event,h===void 0?32:YQ(h.type))}function Pt(h,g){var k=W.p;try{return W.p=h,g()}finally{W.p=k}}var sn=Math.random().toString(36).slice(2),Mn="__reactFiber$"+sn,ln="__reactProps$"+sn,ir="__reactContainer$"+sn,Ga="__reactEvents$"+sn,ja="__reactListeners$"+sn,Zc="__reactHandles$"+sn,qu="__reactResources$"+sn,Is="__reactMarker$"+sn;function Hu(h){delete h[Mn],delete h[ln],delete h[Ga],delete h[ja],delete h[Zc]}function Ao(h){var g=h[Mn];if(g)return g;for(var k=h.parentNode;k;){if(g=k[ir]||k[Mn]){if(k=g.alternate,g.child!==null||k!==null&&k.child!==null)for(h=$Q(h);h!==null;){if(k=h[Mn])return k;h=$Q(h)}return g}h=k,k=h.parentNode}return null}function Ai(h){if(h=h[Mn]||h[ir]){var g=h.tag;if(g===5||g===6||g===13||g===26||g===27||g===3)return h}return null}function Wa(h){var g=h.tag;if(g===5||g===26||g===27||g===6)return h.stateNode;throw Error(r(33))}function hs(h){var g=h[qu];return g||(g=h[qu]={hoistableStyles:new Map,hoistableScripts:new Map}),g}function vr(h){h[Is]=!0}var Yc=new Set,Xl={};function ht(h,g){Nt(h,g),Nt(h+"Capture",g)}function Nt(h,g){for(Xl[h]=g,h=0;h<g.length;h++)Yc.add(g[h])}var Tt=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]*$"),Cr={},vn={};function yr(h){return Z.call(vn,h)?!0:Z.call(Cr,h)?!1:Tt.test(h)?vn[h]=!0:(Cr[h]=!0,!1)}function Ka(h,g,k){if(yr(g))if(k===null)h.removeAttribute(g);else{switch(typeof k){case"undefined":case"function":case"symbol":h.removeAttribute(g);return;case"boolean":var C=g.toLowerCase().slice(0,5);if(C!=="data-"&&C!=="aria-"){h.removeAttribute(g);return}}h.setAttribute(g,""+k)}}function ms(h,g,k){if(k===null)h.removeAttribute(g);else{switch(typeof k){case"undefined":case"function":case"symbol":case"boolean":h.removeAttribute(g);return}h.setAttribute(g,""+k)}}function js(h,g,k,C){if(C===null)h.removeAttribute(k);else{switch(typeof C){case"undefined":case"function":case"symbol":case"boolean":h.removeAttribute(k);return}h.setAttributeNS(g,k,""+C)}}var Xc,ol;function Ve(h){if(Xc===void 0)try{throw Error()}catch(k){var g=k.stack.trim().match(/\n( *(at )?)/);Xc=g&&g[1]||"",ol=-1<k.stack.indexOf(`
|
|
1
|
+
(function(){try{var e=typeof window<"u"?window:typeof global<"u"?global:typeof globalThis<"u"?globalThis:typeof self<"u"?self:{};e.SENTRY_RELEASE={id:"da17445e9faac92325bad8ba3320aeba4239a305"};var t=new e.Error().stack;t&&(e._sentryDebugIds=e._sentryDebugIds||{},e._sentryDebugIds[t]="9d8d56a7-6f74-481b-bfc3-f62b709bfb7f",e._sentryDebugIdIdentifier="sentry-dbid-9d8d56a7-6f74-481b-bfc3-f62b709bfb7f")}catch{}})();function KUe(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const i in r)if(i!=="default"&&!(i in e)){const a=Object.getOwnPropertyDescriptor(r,i);a&&Object.defineProperty(e,i,a.get?a:{enumerable:!0,get:()=>r[i]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}(function(){const t=document.createElement("link").relList;if(t&&t.supports&&t.supports("modulepreload"))return;for(const i of document.querySelectorAll('link[rel="modulepreload"]'))r(i);new MutationObserver(i=>{for(const a of i)if(a.type==="childList")for(const s of a.addedNodes)s.tagName==="LINK"&&s.rel==="modulepreload"&&r(s)}).observe(document,{childList:!0,subtree:!0});function n(i){const a={};return i.integrity&&(a.integrity=i.integrity),i.referrerPolicy&&(a.referrerPolicy=i.referrerPolicy),i.crossOrigin==="use-credentials"?a.credentials="include":i.crossOrigin==="anonymous"?a.credentials="omit":a.credentials="same-origin",a}function r(i){if(i.ep)return;i.ep=!0;const a=n(i);fetch(i.href,a)}})();var FE=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Jn(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var oM={exports:{}},Jb={};var nee;function ZUe(){if(nee)return Jb;nee=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,i,a){var s=null;if(a!==void 0&&(s=""+a),i.key!==void 0&&(s=""+i.key),"key"in i){a={};for(var o in i)o!=="key"&&(a[o]=i[o])}else a=i;return i=a.ref,{$$typeof:e,type:r,key:s,ref:i!==void 0?i:null,props:a}}return Jb.Fragment=t,Jb.jsx=n,Jb.jsxs=n,Jb}var ree;function YUe(){return ree||(ree=1,oM.exports=ZUe()),oM.exports}var l=YUe(),lM={exports:{}},kn={};var iee;function XUe(){if(iee)return kn;iee=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.consumer"),s=Symbol.for("react.context"),o=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),c=Symbol.for("react.memo"),d=Symbol.for("react.lazy"),f=Symbol.iterator;function p(L){return L===null||typeof L!="object"?null:(L=f&&L[f]||L["@@iterator"],typeof L=="function"?L:null)}var m={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,v={};function x(L,Y,G){this.props=L,this.context=Y,this.refs=v,this.updater=G||m}x.prototype.isReactComponent={},x.prototype.setState=function(L,Y){if(typeof L!="object"&&typeof L!="function"&&L!=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,L,Y,"setState")},x.prototype.forceUpdate=function(L){this.updater.enqueueForceUpdate(this,L,"forceUpdate")};function _(){}_.prototype=x.prototype;function S(L,Y,G){this.props=L,this.context=Y,this.refs=v,this.updater=G||m}var w=S.prototype=new _;w.constructor=S,y(w,x.prototype),w.isPureReactComponent=!0;var T=Array.isArray,N={H:null,A:null,T:null,S:null,V:null},E=Object.prototype.hasOwnProperty;function A(L,Y,G,P,V,K){return G=K.ref,{$$typeof:e,type:L,key:Y,ref:G!==void 0?G:null,props:K}}function I(L,Y){return A(L.type,Y,void 0,void 0,void 0,L.props)}function M(L){return typeof L=="object"&&L!==null&&L.$$typeof===e}function $(L){var Y={"=":"=0",":":"=2"};return"$"+L.replace(/[=:]/g,function(G){return Y[G]})}var O=/\/+/g;function R(L,Y){return typeof L=="object"&&L!==null&&L.key!=null?$(""+L.key):Y.toString(36)}function U(){}function z(L){switch(L.status){case"fulfilled":return L.value;case"rejected":throw L.reason;default:switch(typeof L.status=="string"?L.then(U,U):(L.status="pending",L.then(function(Y){L.status==="pending"&&(L.status="fulfilled",L.value=Y)},function(Y){L.status==="pending"&&(L.status="rejected",L.reason=Y)})),L.status){case"fulfilled":return L.value;case"rejected":throw L.reason}}throw L}function F(L,Y,G,P,V){var K=typeof L;(K==="undefined"||K==="boolean")&&(L=null);var Q=!1;if(L===null)Q=!0;else switch(K){case"bigint":case"string":case"number":Q=!0;break;case"object":switch(L.$$typeof){case e:case t:Q=!0;break;case d:return Q=L._init,F(Q(L._payload),Y,G,P,V)}}if(Q)return V=V(L),Q=P===""?"."+R(L,0):P,T(V)?(G="",Q!=null&&(G=Q.replace(O,"$&/")+"/"),F(V,Y,G,"",function(ee){return ee})):V!=null&&(M(V)&&(V=I(V,G+(V.key==null||L&&L.key===V.key?"":(""+V.key).replace(O,"$&/")+"/")+Q)),Y.push(V)),1;Q=0;var oe=P===""?".":P+":";if(T(L))for(var re=0;re<L.length;re++)P=L[re],K=oe+R(P,re),Q+=F(P,Y,G,K,V);else if(re=p(L),typeof re=="function")for(L=re.call(L),re=0;!(P=L.next()).done;)P=P.value,K=oe+R(P,re++),Q+=F(P,Y,G,K,V);else if(K==="object"){if(typeof L.then=="function")return F(z(L),Y,G,P,V);throw Y=String(L),Error("Objects are not valid as a React child (found: "+(Y==="[object Object]"?"object with keys {"+Object.keys(L).join(", ")+"}":Y)+"). If you meant to render a collection of children, use an array instead.")}return Q}function D(L,Y,G){if(L==null)return L;var P=[],V=0;return F(L,P,"","",function(K){return Y.call(G,K,V++)}),P}function W(L){if(L._status===-1){var Y=L._result;Y=Y(),Y.then(function(G){(L._status===0||L._status===-1)&&(L._status=1,L._result=G)},function(G){(L._status===0||L._status===-1)&&(L._status=2,L._result=G)}),L._status===-1&&(L._status=0,L._result=Y)}if(L._status===1)return L._result.default;throw L._result}var q=typeof reportError=="function"?reportError:function(L){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var Y=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof L=="object"&&L!==null&&typeof L.message=="string"?String(L.message):String(L),error:L});if(!window.dispatchEvent(Y))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",L);return}console.error(L)};function X(){}return kn.Children={map:D,forEach:function(L,Y,G){D(L,function(){Y.apply(this,arguments)},G)},count:function(L){var Y=0;return D(L,function(){Y++}),Y},toArray:function(L){return D(L,function(Y){return Y})||[]},only:function(L){if(!M(L))throw Error("React.Children.only expected to receive a single React element child.");return L}},kn.Component=x,kn.Fragment=n,kn.Profiler=i,kn.PureComponent=S,kn.StrictMode=r,kn.Suspense=u,kn.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=N,kn.__COMPILER_RUNTIME={__proto__:null,c:function(L){return N.H.useMemoCache(L)}},kn.cache=function(L){return function(){return L.apply(null,arguments)}},kn.cloneElement=function(L,Y,G){if(L==null)throw Error("The argument must be a React element, but you passed "+L+".");var P=y({},L.props),V=L.key,K=void 0;if(Y!=null)for(Q in Y.ref!==void 0&&(K=void 0),Y.key!==void 0&&(V=""+Y.key),Y)!E.call(Y,Q)||Q==="key"||Q==="__self"||Q==="__source"||Q==="ref"&&Y.ref===void 0||(P[Q]=Y[Q]);var Q=arguments.length-2;if(Q===1)P.children=G;else if(1<Q){for(var oe=Array(Q),re=0;re<Q;re++)oe[re]=arguments[re+2];P.children=oe}return A(L.type,V,void 0,void 0,K,P)},kn.createContext=function(L){return L={$$typeof:s,_currentValue:L,_currentValue2:L,_threadCount:0,Provider:null,Consumer:null},L.Provider=L,L.Consumer={$$typeof:a,_context:L},L},kn.createElement=function(L,Y,G){var P,V={},K=null;if(Y!=null)for(P in Y.key!==void 0&&(K=""+Y.key),Y)E.call(Y,P)&&P!=="key"&&P!=="__self"&&P!=="__source"&&(V[P]=Y[P]);var Q=arguments.length-2;if(Q===1)V.children=G;else if(1<Q){for(var oe=Array(Q),re=0;re<Q;re++)oe[re]=arguments[re+2];V.children=oe}if(L&&L.defaultProps)for(P in Q=L.defaultProps,Q)V[P]===void 0&&(V[P]=Q[P]);return A(L,K,void 0,void 0,null,V)},kn.createRef=function(){return{current:null}},kn.forwardRef=function(L){return{$$typeof:o,render:L}},kn.isValidElement=M,kn.lazy=function(L){return{$$typeof:d,_payload:{_status:-1,_result:L},_init:W}},kn.memo=function(L,Y){return{$$typeof:c,type:L,compare:Y===void 0?null:Y}},kn.startTransition=function(L){var Y=N.T,G={};N.T=G;try{var P=L(),V=N.S;V!==null&&V(G,P),typeof P=="object"&&P!==null&&typeof P.then=="function"&&P.then(X,q)}catch(K){q(K)}finally{N.T=Y}},kn.unstable_useCacheRefresh=function(){return N.H.useCacheRefresh()},kn.use=function(L){return N.H.use(L)},kn.useActionState=function(L,Y,G){return N.H.useActionState(L,Y,G)},kn.useCallback=function(L,Y){return N.H.useCallback(L,Y)},kn.useContext=function(L){return N.H.useContext(L)},kn.useDebugValue=function(){},kn.useDeferredValue=function(L,Y){return N.H.useDeferredValue(L,Y)},kn.useEffect=function(L,Y,G){var P=N.H;if(typeof G=="function")throw Error("useEffect CRUD overload is not enabled in this build of React.");return P.useEffect(L,Y)},kn.useId=function(){return N.H.useId()},kn.useImperativeHandle=function(L,Y,G){return N.H.useImperativeHandle(L,Y,G)},kn.useInsertionEffect=function(L,Y){return N.H.useInsertionEffect(L,Y)},kn.useLayoutEffect=function(L,Y){return N.H.useLayoutEffect(L,Y)},kn.useMemo=function(L,Y){return N.H.useMemo(L,Y)},kn.useOptimistic=function(L,Y){return N.H.useOptimistic(L,Y)},kn.useReducer=function(L,Y,G){return N.H.useReducer(L,Y,G)},kn.useRef=function(L){return N.H.useRef(L)},kn.useState=function(L){return N.H.useState(L)},kn.useSyncExternalStore=function(L,Y,G){return N.H.useSyncExternalStore(L,Y,G)},kn.useTransition=function(){return N.H.useTransition()},kn.version="19.1.0",kn}var aee;function X2(){return aee||(aee=1,lM.exports=XUe()),lM.exports}var b=X2();const de=Jn(b),dO=KUe({__proto__:null,default:de},[b]);var uM={exports:{}},Qb={},cM={exports:{}},dM={};var see;function JUe(){return see||(see=1,(function(e){function t(D,W){var q=D.length;D.push(W);e:for(;0<q;){var X=q-1>>>1,L=D[X];if(0<i(L,W))D[X]=W,D[q]=L,q=X;else break e}}function n(D){return D.length===0?null:D[0]}function r(D){if(D.length===0)return null;var W=D[0],q=D.pop();if(q!==W){D[0]=q;e:for(var X=0,L=D.length,Y=L>>>1;X<Y;){var G=2*(X+1)-1,P=D[G],V=G+1,K=D[V];if(0>i(P,q))V<L&&0>i(K,P)?(D[X]=K,D[V]=q,X=V):(D[X]=P,D[G]=q,X=G);else if(V<L&&0>i(K,q))D[X]=K,D[V]=q,X=V;else break e}}return W}function i(D,W){var q=D.sortIndex-W.sortIndex;return q!==0?q:D.id-W.id}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 s=Date,o=s.now();e.unstable_now=function(){return s.now()-o}}var u=[],c=[],d=1,f=null,p=3,m=!1,y=!1,v=!1,x=!1,_=typeof setTimeout=="function"?setTimeout:null,S=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;function T(D){for(var W=n(c);W!==null;){if(W.callback===null)r(c);else if(W.startTime<=D)r(c),W.sortIndex=W.expirationTime,t(u,W);else break;W=n(c)}}function N(D){if(v=!1,T(D),!y)if(n(u)!==null)y=!0,E||(E=!0,R());else{var W=n(c);W!==null&&F(N,W.startTime-D)}}var E=!1,A=-1,I=5,M=-1;function $(){return x?!0:!(e.unstable_now()-M<I)}function O(){if(x=!1,E){var D=e.unstable_now();M=D;var W=!0;try{e:{y=!1,v&&(v=!1,S(A),A=-1),m=!0;var q=p;try{t:{for(T(D),f=n(u);f!==null&&!(f.expirationTime>D&&$());){var X=f.callback;if(typeof X=="function"){f.callback=null,p=f.priorityLevel;var L=X(f.expirationTime<=D);if(D=e.unstable_now(),typeof L=="function"){f.callback=L,T(D),W=!0;break t}f===n(u)&&r(u),T(D)}else r(u);f=n(u)}if(f!==null)W=!0;else{var Y=n(c);Y!==null&&F(N,Y.startTime-D),W=!1}}break e}finally{f=null,p=q,m=!1}W=void 0}}finally{W?R():E=!1}}}var R;if(typeof w=="function")R=function(){w(O)};else if(typeof MessageChannel<"u"){var U=new MessageChannel,z=U.port2;U.port1.onmessage=O,R=function(){z.postMessage(null)}}else R=function(){_(O,0)};function F(D,W){A=_(function(){D(e.unstable_now())},W)}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(D){D.callback=null},e.unstable_forceFrameRate=function(D){0>D||125<D?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):I=0<D?Math.floor(1e3/D):5},e.unstable_getCurrentPriorityLevel=function(){return p},e.unstable_next=function(D){switch(p){case 1:case 2:case 3:var W=3;break;default:W=p}var q=p;p=W;try{return D()}finally{p=q}},e.unstable_requestPaint=function(){x=!0},e.unstable_runWithPriority=function(D,W){switch(D){case 1:case 2:case 3:case 4:case 5:break;default:D=3}var q=p;p=D;try{return W()}finally{p=q}},e.unstable_scheduleCallback=function(D,W,q){var X=e.unstable_now();switch(typeof q=="object"&&q!==null?(q=q.delay,q=typeof q=="number"&&0<q?X+q:X):q=X,D){case 1:var L=-1;break;case 2:L=250;break;case 5:L=1073741823;break;case 4:L=1e4;break;default:L=5e3}return L=q+L,D={id:d++,callback:W,priorityLevel:D,startTime:q,expirationTime:L,sortIndex:-1},q>X?(D.sortIndex=q,t(c,D),n(u)===null&&D===n(c)&&(v?(S(A),A=-1):v=!0,F(N,q-X))):(D.sortIndex=L,t(u,D),y||m||(y=!0,E||(E=!0,R()))),D},e.unstable_shouldYield=$,e.unstable_wrapCallback=function(D){var W=p;return function(){var q=p;p=W;try{return D.apply(this,arguments)}finally{p=q}}}})(dM)),dM}var oee;function QUe(){return oee||(oee=1,cM.exports=JUe()),cM.exports}var fM={exports:{}},vs={};var lee;function e7e(){if(lee)return vs;lee=1;var e=X2();function t(u){var c="https://react.dev/errors/"+u;if(1<arguments.length){c+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)c+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+u+"; visit "+c+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function n(){}var r={d:{f:n,r:function(){throw Error(t(522))},D:n,C:n,L:n,m:n,X:n,S:n,M:n},p:0,findDOMNode:null},i=Symbol.for("react.portal");function a(u,c,d){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:i,key:f==null?null:""+f,children:u,containerInfo:c,implementation:d}}var s=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function o(u,c){if(u==="font")return"";if(typeof c=="string")return c==="use-credentials"?c:""}return vs.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,vs.createPortal=function(u,c){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!c||c.nodeType!==1&&c.nodeType!==9&&c.nodeType!==11)throw Error(t(299));return a(u,c,null,d)},vs.flushSync=function(u){var c=s.T,d=r.p;try{if(s.T=null,r.p=2,u)return u()}finally{s.T=c,r.p=d,r.d.f()}},vs.preconnect=function(u,c){typeof u=="string"&&(c?(c=c.crossOrigin,c=typeof c=="string"?c==="use-credentials"?c:"":void 0):c=null,r.d.C(u,c))},vs.prefetchDNS=function(u){typeof u=="string"&&r.d.D(u)},vs.preinit=function(u,c){if(typeof u=="string"&&c&&typeof c.as=="string"){var d=c.as,f=o(d,c.crossOrigin),p=typeof c.integrity=="string"?c.integrity:void 0,m=typeof c.fetchPriority=="string"?c.fetchPriority:void 0;d==="style"?r.d.S(u,typeof c.precedence=="string"?c.precedence:void 0,{crossOrigin:f,integrity:p,fetchPriority:m}):d==="script"&&r.d.X(u,{crossOrigin:f,integrity:p,fetchPriority:m,nonce:typeof c.nonce=="string"?c.nonce:void 0})}},vs.preinitModule=function(u,c){if(typeof u=="string")if(typeof c=="object"&&c!==null){if(c.as==null||c.as==="script"){var d=o(c.as,c.crossOrigin);r.d.M(u,{crossOrigin:d,integrity:typeof c.integrity=="string"?c.integrity:void 0,nonce:typeof c.nonce=="string"?c.nonce:void 0})}}else c==null&&r.d.M(u)},vs.preload=function(u,c){if(typeof u=="string"&&typeof c=="object"&&c!==null&&typeof c.as=="string"){var d=c.as,f=o(d,c.crossOrigin);r.d.L(u,d,{crossOrigin:f,integrity:typeof c.integrity=="string"?c.integrity:void 0,nonce:typeof c.nonce=="string"?c.nonce:void 0,type:typeof c.type=="string"?c.type:void 0,fetchPriority:typeof c.fetchPriority=="string"?c.fetchPriority:void 0,referrerPolicy:typeof c.referrerPolicy=="string"?c.referrerPolicy:void 0,imageSrcSet:typeof c.imageSrcSet=="string"?c.imageSrcSet:void 0,imageSizes:typeof c.imageSizes=="string"?c.imageSizes:void 0,media:typeof c.media=="string"?c.media:void 0})}},vs.preloadModule=function(u,c){if(typeof u=="string")if(c){var d=o(c.as,c.crossOrigin);r.d.m(u,{as:typeof c.as=="string"&&c.as!=="script"?c.as:void 0,crossOrigin:d,integrity:typeof c.integrity=="string"?c.integrity:void 0})}else r.d.m(u)},vs.requestFormReset=function(u){r.d.r(u)},vs.unstable_batchedUpdates=function(u,c){return u(c)},vs.useFormState=function(u,c,d){return s.H.useFormState(u,c,d)},vs.useFormStatus=function(){return s.H.useHostTransitionStatus()},vs.version="19.1.0",vs}var uee;function nve(){if(uee)return fM.exports;uee=1;function e(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(e)}catch(t){console.error(t)}}return e(),fM.exports=e7e(),fM.exports}var cee;function t7e(){if(cee)return Qb;cee=1;var e=QUe(),t=X2(),n=nve();function r(h){var g="https://react.dev/errors/"+h;if(1<arguments.length){g+="?args[]="+encodeURIComponent(arguments[1]);for(var k=2;k<arguments.length;k++)g+="&args[]="+encodeURIComponent(arguments[k])}return"Minified React error #"+h+"; visit "+g+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function i(h){return!(!h||h.nodeType!==1&&h.nodeType!==9&&h.nodeType!==11)}function a(h){var g=h,k=h;if(h.alternate)for(;g.return;)g=g.return;else{h=g;do g=h,(g.flags&4098)!==0&&(k=g.return),h=g.return;while(h)}return g.tag===3?k:null}function s(h){if(h.tag===13){var g=h.memoizedState;if(g===null&&(h=h.alternate,h!==null&&(g=h.memoizedState)),g!==null)return g.dehydrated}return null}function o(h){if(a(h)!==h)throw Error(r(188))}function u(h){var g=h.alternate;if(!g){if(g=a(h),g===null)throw Error(r(188));return g!==h?null:h}for(var k=h,C=g;;){var j=k.return;if(j===null)break;var B=j.alternate;if(B===null){if(C=j.return,C!==null){k=C;continue}break}if(j.child===B.child){for(B=j.child;B;){if(B===k)return o(j),h;if(B===C)return o(j),g;B=B.sibling}throw Error(r(188))}if(k.return!==C.return)k=j,C=B;else{for(var ae=!1,pe=j.child;pe;){if(pe===k){ae=!0,k=j,C=B;break}if(pe===C){ae=!0,C=j,k=B;break}pe=pe.sibling}if(!ae){for(pe=B.child;pe;){if(pe===k){ae=!0,k=B,C=j;break}if(pe===C){ae=!0,C=B,k=j;break}pe=pe.sibling}if(!ae)throw Error(r(189))}}if(k.alternate!==C)throw Error(r(190))}if(k.tag!==3)throw Error(r(188));return k.stateNode.current===k?h:g}function c(h){var g=h.tag;if(g===5||g===26||g===27||g===6)return h;for(h=h.child;h!==null;){if(g=c(h),g!==null)return g;h=h.sibling}return null}var d=Object.assign,f=Symbol.for("react.element"),p=Symbol.for("react.transitional.element"),m=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),v=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),_=Symbol.for("react.provider"),S=Symbol.for("react.consumer"),w=Symbol.for("react.context"),T=Symbol.for("react.forward_ref"),N=Symbol.for("react.suspense"),E=Symbol.for("react.suspense_list"),A=Symbol.for("react.memo"),I=Symbol.for("react.lazy"),M=Symbol.for("react.activity"),$=Symbol.for("react.memo_cache_sentinel"),O=Symbol.iterator;function R(h){return h===null||typeof h!="object"?null:(h=O&&h[O]||h["@@iterator"],typeof h=="function"?h:null)}var U=Symbol.for("react.client.reference");function z(h){if(h==null)return null;if(typeof h=="function")return h.$$typeof===U?null:h.displayName||h.name||null;if(typeof h=="string")return h;switch(h){case y:return"Fragment";case x:return"Profiler";case v:return"StrictMode";case N:return"Suspense";case E:return"SuspenseList";case M:return"Activity"}if(typeof h=="object")switch(h.$$typeof){case m:return"Portal";case w:return(h.displayName||"Context")+".Provider";case S:return(h._context.displayName||"Context")+".Consumer";case T:var g=h.render;return h=h.displayName,h||(h=g.displayName||g.name||"",h=h!==""?"ForwardRef("+h+")":"ForwardRef"),h;case A:return g=h.displayName||null,g!==null?g:z(h.type)||"Memo";case I:g=h._payload,h=h._init;try{return z(h(g))}catch{}}return null}var F=Array.isArray,D=t.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,W=n.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,q={pending:!1,data:null,method:null,action:null},X=[],L=-1;function Y(h){return{current:h}}function G(h){0>L||(h.current=X[L],X[L]=null,L--)}function P(h,g){L++,X[L]=h.current,h.current=g}var V=Y(null),K=Y(null),Q=Y(null),oe=Y(null);function re(h,g){switch(P(Q,g),P(K,h),P(V,null),g.nodeType){case 9:case 11:h=(h=g.documentElement)&&(h=h.namespaceURI)?IQ(h):0;break;default:if(h=g.tagName,g=g.namespaceURI)g=IQ(g),h=jQ(g,h);else switch(h){case"svg":h=1;break;case"math":h=2;break;default:h=0}}G(V),P(V,h)}function ee(){G(V),G(K),G(Q)}function le(h){h.memoizedState!==null&&P(oe,h);var g=V.current,k=jQ(g,h.type);g!==k&&(P(K,h),P(V,k))}function te(h){K.current===h&&(G(V),G(K)),oe.current===h&&(G(oe),Wb._currentValue=q)}var Z=Object.prototype.hasOwnProperty,ne=e.unstable_scheduleCallback,J=e.unstable_cancelCallback,se=e.unstable_shouldYield,ie=e.unstable_requestPaint,he=e.unstable_now,ye=e.unstable_getCurrentPriorityLevel,Ne=e.unstable_ImmediatePriority,ce=e.unstable_UserBlockingPriority,Te=e.unstable_NormalPriority,we=e.unstable_LowPriority,Oe=e.unstable_IdlePriority,Ue=e.log,Me=e.unstable_setDisableYieldValue,be=null,je=null;function Xe(h){if(typeof Ue=="function"&&Me(h),je&&typeof je.setStrictMode=="function")try{je.setStrictMode(be,h)}catch{}}var ue=Math.clz32?Math.clz32:Ce,fe=Math.log,xe=Math.LN2;function Ce(h){return h>>>=0,h===0?32:31-(fe(h)/xe|0)|0}var He=256,Ze=4194304;function st(h){var g=h&42;if(g!==0)return g;switch(h&-h){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:case 262144:case 524288:case 1048576:case 2097152:return h&4194048;case 4194304:case 8388608:case 16777216:case 33554432:return h&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return h}}function ot(h,g,k){var C=h.pendingLanes;if(C===0)return 0;var j=0,B=h.suspendedLanes,ae=h.pingedLanes;h=h.warmLanes;var pe=C&134217727;return pe!==0?(C=pe&~B,C!==0?j=st(C):(ae&=pe,ae!==0?j=st(ae):k||(k=pe&~h,k!==0&&(j=st(k))))):(pe=C&~B,pe!==0?j=st(pe):ae!==0?j=st(ae):k||(k=C&~h,k!==0&&(j=st(k)))),j===0?0:g!==0&&g!==j&&(g&B)===0&&(B=j&-j,k=g&-g,B>=k||B===32&&(k&4194048)!==0)?g:j}function mt(h,g){return(h.pendingLanes&~(h.suspendedLanes&~h.pingedLanes)&g)===0}function Bt(h,g){switch(h){case 1:case 2:case 4:case 8:case 64:return g+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 g+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 Mt(){var h=He;return He<<=1,(He&4194048)===0&&(He=256),h}function It(){var h=Ze;return Ze<<=1,(Ze&62914560)===0&&(Ze=4194304),h}function gn(h){for(var g=[],k=0;31>k;k++)g.push(h);return g}function nt(h,g){h.pendingLanes|=g,g!==268435456&&(h.suspendedLanes=0,h.pingedLanes=0,h.warmLanes=0)}function yt(h,g,k,C,j,B){var ae=h.pendingLanes;h.pendingLanes=k,h.suspendedLanes=0,h.pingedLanes=0,h.warmLanes=0,h.expiredLanes&=k,h.entangledLanes&=k,h.errorRecoveryDisabledLanes&=k,h.shellSuspendCounter=0;var pe=h.entanglements,ke=h.expirationTimes,ze=h.hiddenUpdates;for(k=ae&~k;0<k;){var Ye=31-ue(k),et=1<<Ye;pe[Ye]=0,ke[Ye]=-1;var Fe=ze[Ye];if(Fe!==null)for(ze[Ye]=null,Ye=0;Ye<Fe.length;Ye++){var Be=Fe[Ye];Be!==null&&(Be.lane&=-536870913)}k&=~et}C!==0&&ut(h,C,0),B!==0&&j===0&&h.tag!==0&&(h.suspendedLanes|=B&~(ae&~g))}function ut(h,g,k){h.pendingLanes|=g,h.suspendedLanes&=~g;var C=31-ue(g);h.entangledLanes|=g,h.entanglements[C]=h.entanglements[C]|1073741824|k&4194090}function vt(h,g){var k=h.entangledLanes|=g;for(h=h.entanglements;k;){var C=31-ue(k),j=1<<C;j&g|h[C]&g&&(h[C]|=g),k&=~j}}function Wt(h){switch(h){case 2:h=1;break;case 8:h=4;break;case 32:h=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:h=128;break;case 268435456:h=134217728;break;default:h=0}return h}function Qn(h){return h&=-h,2<h?8<h?(h&134217727)!==0?32:268435456:8:2}function Gi(){var h=W.p;return h!==0?h:(h=window.event,h===void 0?32:YQ(h.type))}function Pt(h,g){var k=W.p;try{return W.p=h,g()}finally{W.p=k}}var sn=Math.random().toString(36).slice(2),Mn="__reactFiber$"+sn,ln="__reactProps$"+sn,ir="__reactContainer$"+sn,Ga="__reactEvents$"+sn,ja="__reactListeners$"+sn,Zc="__reactHandles$"+sn,qu="__reactResources$"+sn,Is="__reactMarker$"+sn;function Hu(h){delete h[Mn],delete h[ln],delete h[Ga],delete h[ja],delete h[Zc]}function Ao(h){var g=h[Mn];if(g)return g;for(var k=h.parentNode;k;){if(g=k[ir]||k[Mn]){if(k=g.alternate,g.child!==null||k!==null&&k.child!==null)for(h=$Q(h);h!==null;){if(k=h[Mn])return k;h=$Q(h)}return g}h=k,k=h.parentNode}return null}function Ai(h){if(h=h[Mn]||h[ir]){var g=h.tag;if(g===5||g===6||g===13||g===26||g===27||g===3)return h}return null}function Wa(h){var g=h.tag;if(g===5||g===26||g===27||g===6)return h.stateNode;throw Error(r(33))}function hs(h){var g=h[qu];return g||(g=h[qu]={hoistableStyles:new Map,hoistableScripts:new Map}),g}function vr(h){h[Is]=!0}var Yc=new Set,Xl={};function ht(h,g){Nt(h,g),Nt(h+"Capture",g)}function Nt(h,g){for(Xl[h]=g,h=0;h<g.length;h++)Yc.add(g[h])}var Tt=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]*$"),Cr={},vn={};function yr(h){return Z.call(vn,h)?!0:Z.call(Cr,h)?!1:Tt.test(h)?vn[h]=!0:(Cr[h]=!0,!1)}function Ka(h,g,k){if(yr(g))if(k===null)h.removeAttribute(g);else{switch(typeof k){case"undefined":case"function":case"symbol":h.removeAttribute(g);return;case"boolean":var C=g.toLowerCase().slice(0,5);if(C!=="data-"&&C!=="aria-"){h.removeAttribute(g);return}}h.setAttribute(g,""+k)}}function ms(h,g,k){if(k===null)h.removeAttribute(g);else{switch(typeof k){case"undefined":case"function":case"symbol":case"boolean":h.removeAttribute(g);return}h.setAttribute(g,""+k)}}function js(h,g,k,C){if(C===null)h.removeAttribute(k);else{switch(typeof C){case"undefined":case"function":case"symbol":case"boolean":h.removeAttribute(k);return}h.setAttributeNS(g,k,""+C)}}var Xc,ol;function Ve(h){if(Xc===void 0)try{throw Error()}catch(k){var g=k.stack.trim().match(/\n( *(at )?)/);Xc=g&&g[1]||"",ol=-1<k.stack.indexOf(`
|
|
2
2
|
at`)?" (<anonymous>)":-1<k.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
3
3
|
`+Xc+h+ol}var Br=!1;function Un(h,g){if(!h||Br)return"";Br=!0;var k=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var C={DetermineComponentFrameRoot:function(){try{if(g){var et=function(){throw Error()};if(Object.defineProperty(et.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(et,[])}catch(Be){var Fe=Be}Reflect.construct(h,[],et)}else{try{et.call()}catch(Be){Fe=Be}h.call(et.prototype)}}else{try{throw Error()}catch(Be){Fe=Be}(et=h())&&typeof et.catch=="function"&&et.catch(function(){})}}catch(Be){if(Be&&Fe&&typeof Be.stack=="string")return[Be.stack,Fe.stack]}return[null,null]}};C.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var j=Object.getOwnPropertyDescriptor(C.DetermineComponentFrameRoot,"name");j&&j.configurable&&Object.defineProperty(C.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var B=C.DetermineComponentFrameRoot(),ae=B[0],pe=B[1];if(ae&&pe){var ke=ae.split(`
|
|
4
4
|
`),ze=pe.split(`
|
|
@@ -1696,7 +1696,7 @@ Please report this to https://github.com/markedjs/marked.`,t){let i="<p>An error
|
|
|
1696
1696
|
`||d==="\r"){u=!0;break}if(!u)return o;let c=[];for(let d of o)d===" "?c.push("\\t"):d===`
|
|
1697
1697
|
`?c.push("\\n"):d==="\r"?c.push("\\r"):c.push(d);return c.join("")},i=t.length>0?n.length+1:n.length,a=new Array(i),s=0;t.length>0&&(a[s]=t.map(r).join(" "),s+=1);for(let o of n)a[s]=o.map(r).join(" "),s+=1;return a.join(`
|
|
1698
1698
|
`)},tD=e=>{let t=!1;for(let r of e)if(r==="\\"||r==="|"){t=!0;break}if(!t)return e;let n=[];for(let r of e)r==="\\"?n.push("\\\\"):r==="|"?n.push("\\|"):n.push(r);return n.join("")},TAt=e=>{let{headers:t,rows:n}=e;if(t.length===0)return"";let r=new Array(n.length+2),i=0,a=t.map(o=>tD(o));r[i]=`| ${a.join(" | ")} |`,i+=1;let s=new Array(t.length);for(let o=0;o<t.length;o+=1)s[o]="---";r[i]=`| ${s.join(" | ")} |`,i+=1;for(let o of n)if(o.length<t.length){let u=new Array(t.length);for(let c=0;c<t.length;c+=1)u[c]=c<o.length?tD(o[c]):"";r[i]=`| ${u.join(" | ")} |`,i+=1}else{let u=o.map(c=>tD(c));r[i]=`| ${u.join(" | ")} |`,i+=1}return r.join(`
|
|
1699
|
-
`)},NAt=({children:e,className:t,onCopy:n,onError:r,timeout:i=2e3})=>{let[a,s]=b.useState(!1),[o,u]=b.useState(!1),c=b.useRef(null),d=b.useRef(0),{isAnimating:f}=b.useContext(Ul),p=async y=>{var v,x;if(typeof window>"u"||!((v=navigator?.clipboard)!=null&&v.write)){r?.(new Error("Clipboard API not available"));return}try{let _=(x=c.current)==null?void 0:x.closest('[data-streamdown="table-wrapper"]'),S=_?.querySelector("table");if(!S){r?.(new Error("Table not found"));return}let w=J3e(S),T=y==="csv"?Q3e(w):EAt(w),N=new ClipboardItem({"text/plain":new Blob([T],{type:"text/plain"}),"text/html":new Blob([S.outerHTML],{type:"text/html"})});await navigator.clipboard.write([N]),u(!0),s(!1),n?.(y),d.current=window.setTimeout(()=>u(!1),i)}catch(_){r?.(_)}};b.useEffect(()=>{let y=v=>{let x=v.composedPath();c.current&&!x.includes(c.current)&&s(!1)};return document.addEventListener("mousedown",y),()=>{document.removeEventListener("mousedown",y),window.clearTimeout(d.current)}},[]);let m=o?aK:sK;return l.jsxs("div",{className:"relative",ref:c,children:[l.jsx("button",{className:cn("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",t),disabled:f,onClick:()=>s(!a),title:"Copy table",type:"button",children:e??l.jsx(m,{size:14})}),a?l.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[l.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>p("csv"),title:"Copy table as CSV",type:"button",children:"CSV"}),l.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>p("tsv"),title:"Copy table as TSV",type:"button",children:"TSV"})]}):null]})},CAt=({children:e,className:t,onDownload:n,onError:r})=>{let[i,a]=b.useState(!1),s=b.useRef(null),{isAnimating:o}=b.useContext(Ul),u=c=>{var d;try{let f=(d=s.current)==null?void 0:d.closest('[data-streamdown="table-wrapper"]'),p=f?.querySelector("table");if(!p){r?.(new Error("Table not found"));return}let m=J3e(p),y=c==="csv"?Q3e(m):TAt(m);Vv(`table.${c==="csv"?"csv":"md"}`,y,c==="csv"?"text/csv":"text/markdown"),a(!1),n?.(c)}catch(f){r?.(f)}};return b.useEffect(()=>{let c=d=>{let f=d.composedPath();s.current&&!f.includes(s.current)&&a(!1)};return document.addEventListener("mousedown",c),()=>{document.removeEventListener("mousedown",c)}},[]),l.jsxs("div",{className:"relative",ref:s,children:[l.jsx("button",{className:cn("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",t),disabled:o,onClick:()=>a(!i),title:"Download table",type:"button",children:e??l.jsx(zR,{size:14})}),i?l.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[l.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>u("csv"),title:"Download table as CSV",type:"button",children:"CSV"}),l.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>u("markdown"),title:"Download table as Markdown",type:"button",children:"Markdown"})]}):null]})},AAt=({children:e,className:t,showControls:n,...r})=>l.jsxs("div",{className:"my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",children:[n?l.jsxs("div",{className:"flex items-center justify-end gap-1",children:[l.jsx(NAt,{}),l.jsx(CAt,{})]}):null,l.jsx("div",{className:"overflow-x-auto overscroll-y-auto",children:l.jsx("table",{className:cn("w-full border-collapse border border-border",t),"data-streamdown":"table",...r,children:e})})]}),IAt=b.lazy(()=>TW(()=>import("./code-block-OCS4YCEC-C2ZGbWWM.js"),[]).then(e=>({default:e.CodeBlock}))),jAt=b.lazy(()=>TW(()=>Promise.resolve().then(()=>Ofn),void 0).then(e=>({default:e.Mermaid}))),OAt=/language-([^\s]+)/;function UR(e,t){if(!(e!=null&&e.position||t!=null&&t.position))return!0;if(!(e!=null&&e.position&&t!=null&&t.position))return!1;let n=e.position.start,r=t.position.start,i=e.position.end,a=t.position.end;return n?.line===r?.line&&n?.column===r?.column&&i?.line===a?.line&&i?.column===a?.column}function Vi(e,t){return e.className===t.className&&UR(e.node,t.node)}var oF=(e,t)=>typeof e=="boolean"?e:e[t]!==!1,fN=(e,t)=>{if(typeof e=="boolean")return e;let n=e.mermaid;return n===!1?!1:n===!0||n===void 0?!0:n[t]!==!1},lK=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("ol",{className:cn("list-inside list-decimal whitespace-normal [li_&]:pl-6",t),"data-streamdown":"ordered-list",...r,children:e}),(e,t)=>Vi(e,t));lK.displayName="MarkdownOl";var eRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("li",{className:cn("py-1 [&>p]:inline",t),"data-streamdown":"list-item",...r,children:e}),(e,t)=>e.className===t.className&&UR(e.node,t.node));eRe.displayName="MarkdownLi";var tRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("ul",{className:cn("list-inside list-disc whitespace-normal [li_&]:pl-6",t),"data-streamdown":"unordered-list",...r,children:e}),(e,t)=>Vi(e,t));tRe.displayName="MarkdownUl";var nRe=b.memo(({className:e,node:t,...n})=>l.jsx("hr",{className:cn("my-6 border-border",e),"data-streamdown":"horizontal-rule",...n}),(e,t)=>Vi(e,t));nRe.displayName="MarkdownHr";var rRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("span",{className:cn("font-semibold",t),"data-streamdown":"strong",...r,children:e}),(e,t)=>Vi(e,t));rRe.displayName="MarkdownStrong";var RAt=({children:e,className:t,href:n,node:r,...i})=>{let{linkSafety:a}=b.useContext(Ul),[s,o]=b.useState(!1),u=n==="streamdown:incomplete-link",c=b.useCallback(async m=>{if(!(!(a!=null&&a.enabled&&n)||u)){if(m.preventDefault(),a.onLinkCheck&&await a.onLinkCheck(n)){window.open(n,"_blank","noreferrer");return}o(!0)}},[a,n,u]),d=b.useCallback(()=>{n&&window.open(n,"_blank","noreferrer")},[n]),f=b.useCallback(()=>{o(!1)},[]),p={url:n??"",isOpen:s,onClose:f,onConfirm:d};return a!=null&&a.enabled&&n?l.jsxs(l.Fragment,{children:[l.jsx("button",{className:cn("wrap-anywhere appearance-none text-left font-medium text-primary underline",t),"data-incomplete":u,"data-streamdown":"link",onClick:c,type:"button",children:e}),a.renderModal?a.renderModal(p):l.jsx(xAt,{...p})]}):l.jsx("a",{className:cn("wrap-anywhere font-medium text-primary underline",t),"data-incomplete":u,"data-streamdown":"link",href:n,rel:"noreferrer",target:"_blank",...i,children:e})},iRe=b.memo(RAt,(e,t)=>Vi(e,t)&&e.href===t.href);iRe.displayName="MarkdownA";var aRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h1",{className:cn("mt-6 mb-2 font-semibold text-3xl",t),"data-streamdown":"heading-1",...r,children:e}),(e,t)=>Vi(e,t));aRe.displayName="MarkdownH1";var sRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h2",{className:cn("mt-6 mb-2 font-semibold text-2xl",t),"data-streamdown":"heading-2",...r,children:e}),(e,t)=>Vi(e,t));sRe.displayName="MarkdownH2";var oRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h3",{className:cn("mt-6 mb-2 font-semibold text-xl",t),"data-streamdown":"heading-3",...r,children:e}),(e,t)=>Vi(e,t));oRe.displayName="MarkdownH3";var lRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h4",{className:cn("mt-6 mb-2 font-semibold text-lg",t),"data-streamdown":"heading-4",...r,children:e}),(e,t)=>Vi(e,t));lRe.displayName="MarkdownH4";var uRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h5",{className:cn("mt-6 mb-2 font-semibold text-base",t),"data-streamdown":"heading-5",...r,children:e}),(e,t)=>Vi(e,t));uRe.displayName="MarkdownH5";var cRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h6",{className:cn("mt-6 mb-2 font-semibold text-sm",t),"data-streamdown":"heading-6",...r,children:e}),(e,t)=>Vi(e,t));cRe.displayName="MarkdownH6";var dRe=b.memo(({children:e,className:t,node:n,...r})=>{let{controls:i}=b.useContext(Ul),a=oF(i,"table");return l.jsx(AAt,{className:t,showControls:a,...r,children:e})},(e,t)=>Vi(e,t));dRe.displayName="MarkdownTable";var fRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("thead",{className:cn("bg-muted/80",t),"data-streamdown":"table-header",...r,children:e}),(e,t)=>Vi(e,t));fRe.displayName="MarkdownThead";var pRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("tbody",{className:cn("divide-y divide-border bg-muted/40",t),"data-streamdown":"table-body",...r,children:e}),(e,t)=>Vi(e,t));pRe.displayName="MarkdownTbody";var hRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("tr",{className:cn("border-border border-b",t),"data-streamdown":"table-row",...r,children:e}),(e,t)=>Vi(e,t));hRe.displayName="MarkdownTr";var mRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("th",{className:cn("whitespace-nowrap px-4 py-2 text-left font-semibold text-sm",t),"data-streamdown":"table-header-cell",...r,children:e}),(e,t)=>Vi(e,t));mRe.displayName="MarkdownTh";var gRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("td",{className:cn("px-4 py-2 text-sm",t),"data-streamdown":"table-cell",...r,children:e}),(e,t)=>Vi(e,t));gRe.displayName="MarkdownTd";var vRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("blockquote",{className:cn("my-4 border-muted-foreground/30 border-l-4 pl-4 text-muted-foreground italic",t),"data-streamdown":"blockquote",...r,children:e}),(e,t)=>Vi(e,t));vRe.displayName="MarkdownBlockquote";var yRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("sup",{className:cn("text-sm",t),"data-streamdown":"superscript",...r,children:e}),(e,t)=>Vi(e,t));yRe.displayName="MarkdownSup";var xRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("sub",{className:cn("text-sm",t),"data-streamdown":"subscript",...r,children:e}),(e,t)=>Vi(e,t));xRe.displayName="MarkdownSub";var bRe=b.memo(({children:e,className:t,node:n,...r})=>{if("data-footnotes"in r){let i=s=>{var o,u;if(!b.isValidElement(s))return!1;let c=Array.isArray(s.props.children)?s.props.children:[s.props.children],d=!1,f=!1;for(let p of c)if(p){if(typeof p=="string")p.trim()!==""&&(d=!0);else if(b.isValidElement(p))if(((o=p.props)==null?void 0:o["data-footnote-backref"])!==void 0)f=!0;else{let m=Array.isArray(p.props.children)?p.props.children:[p.props.children];for(let y of m){if(typeof y=="string"&&y.trim()!==""){d=!0;break}if(b.isValidElement(y)&&((u=y.props)==null?void 0:u["data-footnote-backref"])===void 0){d=!0;break}}}}return f&&!d},a=Array.isArray(e)?e.map(s=>{if(!b.isValidElement(s))return s;if(s.type===lK){let o=(Array.isArray(s.props.children)?s.props.children:[s.props.children]).filter(u=>!i(u));return o.length===0?null:{...s,props:{...s.props,children:o}}}return s}):e;return(Array.isArray(a)?a.some(s=>s!==null):a!==null)?l.jsx("section",{className:t,...r,children:a}):null}return l.jsx("section",{className:t,...r,children:e})},(e,t)=>Vi(e,t));bRe.displayName="MarkdownSection";var PAt=({node:e,className:t,children:n,...r})=>{var i;let a=!("data-block"in r),{mermaid:s,controls:o}=b.useContext(Ul),u=oK();if(a)return l.jsx("code",{className:cn("rounded bg-muted px-1.5 py-0.5 font-mono text-sm",t),"data-streamdown":"inline-code",...r,children:n});let c=t?.match(OAt),d=(i=c?.at(1))!=null?i:"",f="";if(b.isValidElement(n)&&n.props&&typeof n.props=="object"&&"children"in n.props&&typeof n.props.children=="string"?f=n.props.children:typeof n=="string"&&(f=n),d==="mermaid"&&u){let m=oF(o,"mermaid"),y=fN(o,"download"),v=fN(o,"copy"),x=fN(o,"fullscreen"),_=fN(o,"panZoom"),S=m&&(y||v||x);return l.jsx(b.Suspense,{fallback:l.jsx(ooe,{}),children:l.jsxs("div",{className:cn("group relative my-4 h-auto rounded-xl border p-4",t),"data-streamdown":"mermaid-block",children:[S?l.jsxs("div",{className:"flex items-center justify-end gap-2",children:[y?l.jsx(_At,{chart:f,config:s?.config}):null,v?l.jsx(aoe,{code:f}):null,x?l.jsx(kAt,{chart:f,config:s?.config}):null]}):null,l.jsx(jAt,{chart:f,config:s?.config,showControls:_})]})})}let p=oF(o,"code");return l.jsx(b.Suspense,{fallback:l.jsx(ooe,{}),children:l.jsx(IAt,{className:cn("overflow-x-auto border-border border-t",t),code:f,language:d,children:p?l.jsxs(l.Fragment,{children:[l.jsx(hAt,{code:f,language:d}),l.jsx(aoe,{})]}):null})})},_Re=b.memo(PAt,(e,t)=>e.className===t.className&&UR(e.node,t.node));_Re.displayName="MarkdownCode";var wRe=b.memo(gAt,(e,t)=>e.className===t.className&&UR(e.node,t.node));wRe.displayName="MarkdownImg";var SRe=b.memo(({children:e,className:t,node:n,...r})=>{let i=(Array.isArray(e)?e:[e]).filter(a=>a!=null&&a!=="");if(i.length===1&&b.isValidElement(i[0])){let a=i[0].props.node,s=a?.tagName;if(s==="img")return l.jsx(l.Fragment,{children:e});if(s==="code"&&"data-block"in i[0].props)return l.jsx(l.Fragment,{children:e})}return l.jsx("p",{className:t,...r,children:e})},(e,t)=>Vi(e,t));SRe.displayName="MarkdownParagraph";var $At={ol:lK,li:eRe,ul:tRe,hr:nRe,strong:rRe,a:iRe,h1:aRe,h2:sRe,h3:oRe,h4:lRe,h5:uRe,h6:cRe,table:dRe,thead:fRe,tbody:pRe,tr:hRe,th:mRe,td:gRe,blockquote:vRe,code:_Re,img:wRe,pre:({children:e})=>b.isValidElement(e)?b.cloneElement(e,{"data-block":"true"}):e,sup:yRe,sub:xRe,p:SRe,section:bRe},MAt=()=>e=>{Gp(e,"html",(t,n,r)=>{!r||typeof n!="number"||(r.children[n]={type:"text",value:t.value})})},loe=[],uoe={allowDangerousHtml:!0},pN=new WeakMap,DAt=class{constructor(){this.cache=new Map,this.keyCache=new WeakMap,this.maxSize=100}generateCacheKey(e){let t=this.keyCache.get(e);if(t)return t;let n=e.rehypePlugins,r=e.remarkPlugins,i=e.remarkRehypeOptions;if(!(n||r||i)){let d="default";return this.keyCache.set(e,d),d}let a=d=>{if(!d||d.length===0)return"";let f="";for(let p=0;p<d.length;p+=1){let m=d[p];if(p>0&&(f+=","),Array.isArray(m)){let[y,v]=m;if(typeof y=="function"){let x=pN.get(y);x||(x=y.name,pN.set(y,x)),f+=x}else f+=String(y);f+=":",f+=JSON.stringify(v)}else if(typeof m=="function"){let y=pN.get(m);y||(y=m.name,pN.set(m,y)),f+=y}else f+=String(m)}return f},s=a(n),o=a(r),u=i?JSON.stringify(i):"",c=`${o}::${s}::${u}`;return this.keyCache.set(e,c),c}get(e){let t=this.generateCacheKey(e),n=this.cache.get(t);return n&&(this.cache.delete(t),this.cache.set(t,n)),n}set(e,t){let n=this.generateCacheKey(e);if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(n,t)}clear(){this.cache.clear()}},coe=new DAt,kRe=e=>{let t=LAt(e),n=e.children||"";return VAt(t.runSync(t.parse(n),n),e)},LAt=e=>{let t=coe.get(e);if(t)return t;let n=UAt(e);return coe.set(e,n),n},zAt=e=>e.some(t=>Array.isArray(t)?t[0]===K7:t===K7),UAt=e=>{let t=e.rehypePlugins||loe,n=e.remarkPlugins||loe,r=zAt(t)?n:[...n,MAt],i=e.remarkRehypeOptions?{...uoe,...e.remarkRehypeOptions}:uoe;return uCt().use(lNt).use(r).use(HNt,i).use(t)},FAt=e=>e,BAt=(e,t,n,r)=>{n?e.children.splice(t,1):e.children[t]={type:"text",value:r}},qAt=(e,t)=>{var n;for(let r in G5)if(Object.hasOwn(G5,r)&&Object.hasOwn(e.properties,r)){let i=e.properties[r],a=G5[r];(a===null||a.includes(e.tagName))&&(e.properties[r]=(n=t(String(i||""),r,e))!=null?n:void 0)}},HAt=(e,t,n,r,i,a)=>{let s=!1;return r?s=!r.includes(e.tagName):i&&(s=i.includes(e.tagName)),!s&&a&&typeof t=="number"&&(s=!a(e,t,n)),s},VAt=(e,t)=>{let{allowElement:n,allowedElements:r,disallowedElements:i,skipHtml:a,unwrapDisallowed:s,urlTransform:o}=t;if(n||r||i||a||o){let u=o||FAt;Gp(e,(c,d,f)=>{if(c.type==="raw"&&f&&typeof d=="number")return BAt(f,d,a,c.value),d;if(c.type==="element"&&(qAt(c,u),HAt(c,d,f,r,i,n)&&f&&typeof d=="number"))return s&&c.children?f.children.splice(d,1,...c.children):f.children.splice(d,1),d})}return gTt(e,{Fragment:l.Fragment,components:t.components,ignoreInvalidStyle:!0,jsx:l.jsx,jsxs:l.jsxs,passKeys:!0,passNode:!0})},GAt=/\[\^[\w-]{1,200}\](?!:)/,WAt=/\[\^[\w-]{1,200}\]:/,KAt=/<\/(\w+)>/,ZAt=/<(\w+)[\s>]/,YAt=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),XAt=e=>{let t=0;for(let n=0;n<e.length-1;n+=1)e[n]==="$"&&e[n+1]==="$"&&(t+=1,n+=1);return t},JAt=e=>{let t=GAt.test(e),n=WAt.test(e);if(t||n)return[e];let r=Tl.lex(e,{gfm:!0}),i=[],a=[],s=!1;for(let o of r){let u=o.raw,c=i.length;if(a.length>0){if(i[c-1]+=u,o.type==="html"){let d=u.match(KAt);if(d){let f=d[1];a.at(-1)===f&&a.pop()}}continue}if(o.type==="html"&&o.block){let d=u.match(ZAt);if(d){let f=d[1];u.includes(`</${f}>`)||YAt.has(f.toLowerCase())||a.push(f)}}if(c>0&&!s){let d=i[c-1];if(XAt(d)%2===1){i[c-1]=d+u;continue}}i.push(u),o.type!=="space"&&(s=o.type==="code")}return i},doe,foe,SC={...G1,protocols:{...G1.protocols,href:[...(foe=(doe=G1.protocols)==null?void 0:doe.href)!=null?foe:[],"tel"]}},lF={raw:K7,sanitize:[zOe,SC],harden:[Ixt,{allowedImagePrefixes:["*"],allowedLinkPrefixes:["*"],allowedProtocols:["*"],defaultOrigin:void 0,allowDataImages:!0}]},QAt={gfm:[Gkt,{}]},poe=Object.values(lF),eIt=Object.values(QAt),tIt={block:" ▋",circle:" ●"},nIt={shikiTheme:["github-light","github-dark"],controls:!0,isAnimating:!1,mode:"streaming",mermaid:void 0,linkSafety:{enabled:!0}},Ul=b.createContext(nIt),ERe=b.memo(({content:e,shouldParseIncompleteMarkdown:t,index:n,...r})=>l.jsx(kRe,{...r,children:e}),(e,t)=>{if(e.content!==t.content||e.index!==t.index)return!1;if(e.components!==t.components){let n=Object.keys(e.components||{}),r=Object.keys(t.components||{});if(n.length!==r.length||n.some(i=>{var a,s;return((a=e.components)==null?void 0:a[i])!==((s=t.components)==null?void 0:s[i])}))return!1}return!(e.rehypePlugins!==t.rehypePlugins||e.remarkPlugins!==t.remarkPlugins)});ERe.displayName="Block";var rIt=["github-light","github-dark"],TRe=b.memo(({children:e,mode:t="streaming",parseIncompleteMarkdown:n=!0,components:r,rehypePlugins:i=poe,remarkPlugins:a=eIt,className:s,shikiTheme:o=rIt,mermaid:u,controls:c=!0,isAnimating:d=!1,animated:f,BlockComponent:p=ERe,parseMarkdownIntoBlocksFn:m=JAt,caret:y,plugins:v,remend:x,linkSafety:_={enabled:!0},allowedTags:S,...w})=>{let T=b.useId(),[N,E]=b.useTransition(),A=b.useMemo(()=>typeof e!="string"?"":t==="streaming"&&n?eTt(e,x):e,[e,t,n,x]),I=b.useMemo(()=>m(A),[A,m]),[M,$]=b.useState(I);b.useEffect(()=>{t==="streaming"?E(()=>{$(I)}):$(I)},[I,t]);let O=t==="streaming"?M:I,R=b.useMemo(()=>O.map((X,L)=>`${T}-${L}`),[O.length,T]),U=b.useMemo(()=>f?f===!0?aF():aF(f):null,[f]),z=b.useMemo(()=>{var X,L;return{shikiTheme:(L=(X=v?.code)==null?void 0:X.getThemes())!=null?L:o,controls:c,isAnimating:d,mode:t,mermaid:u,linkSafety:_}},[o,c,d,t,u,_,v?.code]),F=b.useMemo(()=>({...$At,...r}),[r]),D=b.useMemo(()=>{let X=[];return v!=null&&v.cjk&&(X=[...X,...v.cjk.remarkPluginsBefore]),X=[...X,...a],v!=null&&v.cjk&&(X=[...X,...v.cjk.remarkPluginsAfter]),v!=null&&v.math&&(X=[...X,v.math.remarkPlugin]),X},[a,v?.math,v?.cjk]),W=b.useMemo(()=>{var X;let L=i;if(S&&Object.keys(S).length>0&&i===poe){let Y={...SC,tagNames:[...(X=SC.tagNames)!=null?X:[],...Object.keys(S)],attributes:{...SC.attributes,...S}};L=[lF.raw,[zOe,Y],lF.harden]}return v!=null&&v.math&&(L=[...L,v.math.rehypePlugin]),U&&d&&(L=[...L,U.rehypePlugin]),L},[i,v?.math,U,d,S]),q=b.useMemo(()=>y&&d?{"--streamdown-caret":`"${tIt[y]}"`}:void 0,[y,d]);return t==="static"?l.jsx(sF.Provider,{value:v??null,children:l.jsx(Ul.Provider,{value:z,children:l.jsx("div",{className:cn("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",s),children:l.jsx(kRe,{components:F,rehypePlugins:W,remarkPlugins:D,...w,children:e})})})}):l.jsx(sF.Provider,{value:v??null,children:l.jsx(Ul.Provider,{value:z,children:l.jsxs("div",{className:cn("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",y?"*:last:after:inline *:last:after:align-baseline *:last:after:content-[var(--streamdown-caret)]":null,s),style:q,children:[O.length===0&&y&&d&&l.jsx("span",{}),O.map((X,L)=>l.jsx(p,{components:F,content:X,index:L,rehypePlugins:W,remarkPlugins:D,shouldParseIncompleteMarkdown:n,...w},R[L]))]})})})},(e,t)=>e.children===t.children&&e.shikiTheme===t.shikiTheme&&e.isAnimating===t.isAnimating&&e.animated===t.animated&&e.mode===t.mode&&e.plugins===t.plugins&&e.className===t.className&&e.linkSafety===t.linkSafety);TRe.displayName="Streamdown";var iIt=({children:e,className:t,minZoom:n=.5,maxZoom:r=3,zoomStep:i=.1,showControls:a=!0,initialZoom:s=1,fullscreen:o=!1})=>{let u=b.useRef(null),c=b.useRef(null),[d,f]=b.useState(s),[p,m]=b.useState({x:0,y:0}),[y,v]=b.useState(!1),[x,_]=b.useState({x:0,y:0}),[S,w]=b.useState({x:0,y:0}),T=b.useCallback(R=>{f(U=>Math.max(n,Math.min(r,U+R)))},[n,r]),N=b.useCallback(()=>{T(i)},[T,i]),E=b.useCallback(()=>{T(-i)},[T,i]),A=b.useCallback(()=>{f(s),m({x:0,y:0})},[s]),I=b.useCallback(R=>{R.preventDefault();let U=R.deltaY>0?-i:i;T(U)},[T,i]),M=b.useCallback(R=>{if(R.button!==0||R.isPrimary===!1)return;v(!0),_({x:R.clientX,y:R.clientY}),w(p);let U=R.currentTarget;U instanceof HTMLElement&&U.setPointerCapture(R.pointerId)},[p]),$=b.useCallback(R=>{if(!y)return;R.preventDefault();let U=R.clientX-x.x,z=R.clientY-x.y;m({x:S.x+U,y:S.y+z})},[y,x,S]),O=b.useCallback(R=>{v(!1);let U=R.currentTarget;U instanceof HTMLElement&&U.releasePointerCapture(R.pointerId)},[]);return b.useEffect(()=>{let R=u.current;if(R)return R.addEventListener("wheel",I,{passive:!1}),()=>{R.removeEventListener("wheel",I)}},[I]),b.useEffect(()=>{let R=c.current;if(R&&y)return document.body.style.userSelect="none",R.addEventListener("pointermove",$,{passive:!1}),R.addEventListener("pointerup",O),R.addEventListener("pointercancel",O),()=>{document.body.style.userSelect="",R.removeEventListener("pointermove",$),R.removeEventListener("pointerup",O),R.removeEventListener("pointercancel",O)}},[y,$,O]),l.jsxs("div",{className:cn("relative flex flex-col",o?"h-full w-full":"min-h-28 w-full",t),ref:u,style:{cursor:y?"grabbing":"grab"},children:[a?l.jsxs("div",{className:cn("absolute z-10 flex flex-col gap-1 rounded-md border border-border bg-background/90 p-1 shadow-sm backdrop-blur-sm",o?"bottom-4 left-4":"bottom-2 left-2"),children:[l.jsx("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:d>=r,onClick:N,title:"Zoom in",type:"button",children:l.jsx(dAt,{size:16})}),l.jsx("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:d<=n,onClick:E,title:"Zoom out",type:"button",children:l.jsx(fAt,{size:16})}),l.jsx("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:A,title:"Reset zoom and pan",type:"button",children:l.jsx(cAt,{size:16})})]}):null,l.jsx("div",{className:cn("flex-1 origin-center transition-transform duration-150 ease-out",o?"flex h-full w-full items-center justify-center":"flex w-full items-center justify-center"),onPointerDown:M,ref:c,role:"application",style:{transform:`translate(${p.x}px, ${p.y}px) scale(${d})`,transformOrigin:"center center",touchAction:"none",willChange:"transform"},children:e})]})},NRe=({chart:e,className:t,config:n,fullscreen:r=!1,showControls:i=!0})=>{let[a,s]=b.useState(null),[o,u]=b.useState(!1),[c,d]=b.useState(""),[f,p]=b.useState(""),[m,y]=b.useState(0),{mermaid:v}=b.useContext(Ul),x=oK(),_=v?.errorComponent,{shouldRender:S,containerRef:w}=QCt({immediate:r});if(b.useEffect(()=>{if(S){if(!x){s("Mermaid plugin not available. Please add the mermaid plugin to enable diagram rendering.");return}(async()=>{try{s(null),u(!0);let N=x.getMermaid(n),E=e.split("").reduce((M,$)=>(M<<5)-M+$.charCodeAt(0)|0,0),A=`mermaid-${Math.abs(E)}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,{svg:I}=await N.render(A,e);d(I),p(I)}catch(N){if(!(f||c)){let E=N instanceof Error?N.message:"Failed to render Mermaid chart";s(E)}}finally{u(!1)}})()}},[e,n,m,S,x]),!(S||c||f))return l.jsx("div",{className:cn("my-4 min-h-[200px]",t),ref:w});if(o&&!c&&!f)return l.jsx("div",{className:cn("my-4 flex justify-center p-4",t),ref:w,children:l.jsxs("div",{className:"flex items-center space-x-2 text-muted-foreground",children:[l.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-current border-b-2"}),l.jsx("span",{className:"text-sm",children:"Loading diagram..."})]})});if(a&&!c&&!f){let N=()=>y(E=>E+1);return _?l.jsx("div",{ref:w,children:l.jsx(_,{chart:e,error:a,retry:N})}):l.jsxs("div",{className:cn("rounded-lg border border-red-200 bg-red-50 p-4",t),ref:w,children:[l.jsxs("p",{className:"font-mono text-red-700 text-sm",children:["Mermaid Error: ",a]}),l.jsxs("details",{className:"mt-2",children:[l.jsx("summary",{className:"cursor-pointer text-red-600 text-xs",children:"Show Code"}),l.jsx("pre",{className:"mt-2 overflow-x-auto rounded bg-red-100 p-2 text-red-800 text-xs",children:e})]})]})}let T=c||f;return l.jsx("div",{className:cn("size-full",t),"data-streamdown":"mermaid",ref:w,children:l.jsx(iIt,{className:cn(r?"size-full overflow-hidden":"my-4 overflow-hidden",t),fullscreen:r,maxZoom:3,minZoom:.5,showControls:i,zoomStep:.1,children:l.jsx("div",{"aria-label":"Mermaid chart",className:cn("flex justify-center",r?"size-full items-center":null),dangerouslySetInnerHTML:{__html:T},role:"img"})})})};function aIt(e){const t=Rr.lexer(e);return t.length===0?[e]:t.map(n=>n.raw)}const CRe=b.memo(({content:e})=>l.jsx(TRe,{children:e}),(e,t)=>e.content===t.content);CRe.displayName="MemoizedMarkdownBlock";const NI=b.memo(({content:e,className:t})=>b.useMemo(()=>aIt(e),[e]).map((r,i)=>l.jsx("div",{className:t,children:l.jsx(CRe,{content:r})},`markdown-block_${i}`)),(e,t)=>!(e.content!==t.content||e.className!==t.className));NI.displayName="MemoizedMarkdown";function sIt(e,t){const n=t.split(".").pop()?.toLowerCase()||"";return{js:"javascript",mjs:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",php:"php",swift:"swift",kt:"kotlin",scala:"scala",lua:"lua",r:"r",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",htm:"html",css:"css",toml:"toml",ini:"ini"}[n]||"text"}function hoe(e,t){return"```"+t+`
|
|
1699
|
+
`)},NAt=({children:e,className:t,onCopy:n,onError:r,timeout:i=2e3})=>{let[a,s]=b.useState(!1),[o,u]=b.useState(!1),c=b.useRef(null),d=b.useRef(0),{isAnimating:f}=b.useContext(Ul),p=async y=>{var v,x;if(typeof window>"u"||!((v=navigator?.clipboard)!=null&&v.write)){r?.(new Error("Clipboard API not available"));return}try{let _=(x=c.current)==null?void 0:x.closest('[data-streamdown="table-wrapper"]'),S=_?.querySelector("table");if(!S){r?.(new Error("Table not found"));return}let w=J3e(S),T=y==="csv"?Q3e(w):EAt(w),N=new ClipboardItem({"text/plain":new Blob([T],{type:"text/plain"}),"text/html":new Blob([S.outerHTML],{type:"text/html"})});await navigator.clipboard.write([N]),u(!0),s(!1),n?.(y),d.current=window.setTimeout(()=>u(!1),i)}catch(_){r?.(_)}};b.useEffect(()=>{let y=v=>{let x=v.composedPath();c.current&&!x.includes(c.current)&&s(!1)};return document.addEventListener("mousedown",y),()=>{document.removeEventListener("mousedown",y),window.clearTimeout(d.current)}},[]);let m=o?aK:sK;return l.jsxs("div",{className:"relative",ref:c,children:[l.jsx("button",{className:cn("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",t),disabled:f,onClick:()=>s(!a),title:"Copy table",type:"button",children:e??l.jsx(m,{size:14})}),a?l.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[l.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>p("csv"),title:"Copy table as CSV",type:"button",children:"CSV"}),l.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>p("tsv"),title:"Copy table as TSV",type:"button",children:"TSV"})]}):null]})},CAt=({children:e,className:t,onDownload:n,onError:r})=>{let[i,a]=b.useState(!1),s=b.useRef(null),{isAnimating:o}=b.useContext(Ul),u=c=>{var d;try{let f=(d=s.current)==null?void 0:d.closest('[data-streamdown="table-wrapper"]'),p=f?.querySelector("table");if(!p){r?.(new Error("Table not found"));return}let m=J3e(p),y=c==="csv"?Q3e(m):TAt(m);Vv(`table.${c==="csv"?"csv":"md"}`,y,c==="csv"?"text/csv":"text/markdown"),a(!1),n?.(c)}catch(f){r?.(f)}};return b.useEffect(()=>{let c=d=>{let f=d.composedPath();s.current&&!f.includes(s.current)&&a(!1)};return document.addEventListener("mousedown",c),()=>{document.removeEventListener("mousedown",c)}},[]),l.jsxs("div",{className:"relative",ref:s,children:[l.jsx("button",{className:cn("cursor-pointer p-1 text-muted-foreground transition-all hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",t),disabled:o,onClick:()=>a(!i),title:"Download table",type:"button",children:e??l.jsx(zR,{size:14})}),i?l.jsxs("div",{className:"absolute top-full right-0 z-10 mt-1 min-w-[120px] overflow-hidden rounded-md border border-border bg-background shadow-lg",children:[l.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>u("csv"),title:"Download table as CSV",type:"button",children:"CSV"}),l.jsx("button",{className:"w-full px-3 py-2 text-left text-sm transition-colors hover:bg-muted/40",onClick:()=>u("markdown"),title:"Download table as Markdown",type:"button",children:"Markdown"})]}):null]})},AAt=({children:e,className:t,showControls:n,...r})=>l.jsxs("div",{className:"my-4 flex flex-col space-y-2","data-streamdown":"table-wrapper",children:[n?l.jsxs("div",{className:"flex items-center justify-end gap-1",children:[l.jsx(NAt,{}),l.jsx(CAt,{})]}):null,l.jsx("div",{className:"overflow-x-auto overscroll-y-auto",children:l.jsx("table",{className:cn("w-full border-collapse border border-border",t),"data-streamdown":"table",...r,children:e})})]}),IAt=b.lazy(()=>TW(()=>import("./code-block-OCS4YCEC-D6XFrMiK.js"),[]).then(e=>({default:e.CodeBlock}))),jAt=b.lazy(()=>TW(()=>Promise.resolve().then(()=>Ofn),void 0).then(e=>({default:e.Mermaid}))),OAt=/language-([^\s]+)/;function UR(e,t){if(!(e!=null&&e.position||t!=null&&t.position))return!0;if(!(e!=null&&e.position&&t!=null&&t.position))return!1;let n=e.position.start,r=t.position.start,i=e.position.end,a=t.position.end;return n?.line===r?.line&&n?.column===r?.column&&i?.line===a?.line&&i?.column===a?.column}function Vi(e,t){return e.className===t.className&&UR(e.node,t.node)}var oF=(e,t)=>typeof e=="boolean"?e:e[t]!==!1,fN=(e,t)=>{if(typeof e=="boolean")return e;let n=e.mermaid;return n===!1?!1:n===!0||n===void 0?!0:n[t]!==!1},lK=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("ol",{className:cn("list-inside list-decimal whitespace-normal [li_&]:pl-6",t),"data-streamdown":"ordered-list",...r,children:e}),(e,t)=>Vi(e,t));lK.displayName="MarkdownOl";var eRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("li",{className:cn("py-1 [&>p]:inline",t),"data-streamdown":"list-item",...r,children:e}),(e,t)=>e.className===t.className&&UR(e.node,t.node));eRe.displayName="MarkdownLi";var tRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("ul",{className:cn("list-inside list-disc whitespace-normal [li_&]:pl-6",t),"data-streamdown":"unordered-list",...r,children:e}),(e,t)=>Vi(e,t));tRe.displayName="MarkdownUl";var nRe=b.memo(({className:e,node:t,...n})=>l.jsx("hr",{className:cn("my-6 border-border",e),"data-streamdown":"horizontal-rule",...n}),(e,t)=>Vi(e,t));nRe.displayName="MarkdownHr";var rRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("span",{className:cn("font-semibold",t),"data-streamdown":"strong",...r,children:e}),(e,t)=>Vi(e,t));rRe.displayName="MarkdownStrong";var RAt=({children:e,className:t,href:n,node:r,...i})=>{let{linkSafety:a}=b.useContext(Ul),[s,o]=b.useState(!1),u=n==="streamdown:incomplete-link",c=b.useCallback(async m=>{if(!(!(a!=null&&a.enabled&&n)||u)){if(m.preventDefault(),a.onLinkCheck&&await a.onLinkCheck(n)){window.open(n,"_blank","noreferrer");return}o(!0)}},[a,n,u]),d=b.useCallback(()=>{n&&window.open(n,"_blank","noreferrer")},[n]),f=b.useCallback(()=>{o(!1)},[]),p={url:n??"",isOpen:s,onClose:f,onConfirm:d};return a!=null&&a.enabled&&n?l.jsxs(l.Fragment,{children:[l.jsx("button",{className:cn("wrap-anywhere appearance-none text-left font-medium text-primary underline",t),"data-incomplete":u,"data-streamdown":"link",onClick:c,type:"button",children:e}),a.renderModal?a.renderModal(p):l.jsx(xAt,{...p})]}):l.jsx("a",{className:cn("wrap-anywhere font-medium text-primary underline",t),"data-incomplete":u,"data-streamdown":"link",href:n,rel:"noreferrer",target:"_blank",...i,children:e})},iRe=b.memo(RAt,(e,t)=>Vi(e,t)&&e.href===t.href);iRe.displayName="MarkdownA";var aRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h1",{className:cn("mt-6 mb-2 font-semibold text-3xl",t),"data-streamdown":"heading-1",...r,children:e}),(e,t)=>Vi(e,t));aRe.displayName="MarkdownH1";var sRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h2",{className:cn("mt-6 mb-2 font-semibold text-2xl",t),"data-streamdown":"heading-2",...r,children:e}),(e,t)=>Vi(e,t));sRe.displayName="MarkdownH2";var oRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h3",{className:cn("mt-6 mb-2 font-semibold text-xl",t),"data-streamdown":"heading-3",...r,children:e}),(e,t)=>Vi(e,t));oRe.displayName="MarkdownH3";var lRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h4",{className:cn("mt-6 mb-2 font-semibold text-lg",t),"data-streamdown":"heading-4",...r,children:e}),(e,t)=>Vi(e,t));lRe.displayName="MarkdownH4";var uRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h5",{className:cn("mt-6 mb-2 font-semibold text-base",t),"data-streamdown":"heading-5",...r,children:e}),(e,t)=>Vi(e,t));uRe.displayName="MarkdownH5";var cRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("h6",{className:cn("mt-6 mb-2 font-semibold text-sm",t),"data-streamdown":"heading-6",...r,children:e}),(e,t)=>Vi(e,t));cRe.displayName="MarkdownH6";var dRe=b.memo(({children:e,className:t,node:n,...r})=>{let{controls:i}=b.useContext(Ul),a=oF(i,"table");return l.jsx(AAt,{className:t,showControls:a,...r,children:e})},(e,t)=>Vi(e,t));dRe.displayName="MarkdownTable";var fRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("thead",{className:cn("bg-muted/80",t),"data-streamdown":"table-header",...r,children:e}),(e,t)=>Vi(e,t));fRe.displayName="MarkdownThead";var pRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("tbody",{className:cn("divide-y divide-border bg-muted/40",t),"data-streamdown":"table-body",...r,children:e}),(e,t)=>Vi(e,t));pRe.displayName="MarkdownTbody";var hRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("tr",{className:cn("border-border border-b",t),"data-streamdown":"table-row",...r,children:e}),(e,t)=>Vi(e,t));hRe.displayName="MarkdownTr";var mRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("th",{className:cn("whitespace-nowrap px-4 py-2 text-left font-semibold text-sm",t),"data-streamdown":"table-header-cell",...r,children:e}),(e,t)=>Vi(e,t));mRe.displayName="MarkdownTh";var gRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("td",{className:cn("px-4 py-2 text-sm",t),"data-streamdown":"table-cell",...r,children:e}),(e,t)=>Vi(e,t));gRe.displayName="MarkdownTd";var vRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("blockquote",{className:cn("my-4 border-muted-foreground/30 border-l-4 pl-4 text-muted-foreground italic",t),"data-streamdown":"blockquote",...r,children:e}),(e,t)=>Vi(e,t));vRe.displayName="MarkdownBlockquote";var yRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("sup",{className:cn("text-sm",t),"data-streamdown":"superscript",...r,children:e}),(e,t)=>Vi(e,t));yRe.displayName="MarkdownSup";var xRe=b.memo(({children:e,className:t,node:n,...r})=>l.jsx("sub",{className:cn("text-sm",t),"data-streamdown":"subscript",...r,children:e}),(e,t)=>Vi(e,t));xRe.displayName="MarkdownSub";var bRe=b.memo(({children:e,className:t,node:n,...r})=>{if("data-footnotes"in r){let i=s=>{var o,u;if(!b.isValidElement(s))return!1;let c=Array.isArray(s.props.children)?s.props.children:[s.props.children],d=!1,f=!1;for(let p of c)if(p){if(typeof p=="string")p.trim()!==""&&(d=!0);else if(b.isValidElement(p))if(((o=p.props)==null?void 0:o["data-footnote-backref"])!==void 0)f=!0;else{let m=Array.isArray(p.props.children)?p.props.children:[p.props.children];for(let y of m){if(typeof y=="string"&&y.trim()!==""){d=!0;break}if(b.isValidElement(y)&&((u=y.props)==null?void 0:u["data-footnote-backref"])===void 0){d=!0;break}}}}return f&&!d},a=Array.isArray(e)?e.map(s=>{if(!b.isValidElement(s))return s;if(s.type===lK){let o=(Array.isArray(s.props.children)?s.props.children:[s.props.children]).filter(u=>!i(u));return o.length===0?null:{...s,props:{...s.props,children:o}}}return s}):e;return(Array.isArray(a)?a.some(s=>s!==null):a!==null)?l.jsx("section",{className:t,...r,children:a}):null}return l.jsx("section",{className:t,...r,children:e})},(e,t)=>Vi(e,t));bRe.displayName="MarkdownSection";var PAt=({node:e,className:t,children:n,...r})=>{var i;let a=!("data-block"in r),{mermaid:s,controls:o}=b.useContext(Ul),u=oK();if(a)return l.jsx("code",{className:cn("rounded bg-muted px-1.5 py-0.5 font-mono text-sm",t),"data-streamdown":"inline-code",...r,children:n});let c=t?.match(OAt),d=(i=c?.at(1))!=null?i:"",f="";if(b.isValidElement(n)&&n.props&&typeof n.props=="object"&&"children"in n.props&&typeof n.props.children=="string"?f=n.props.children:typeof n=="string"&&(f=n),d==="mermaid"&&u){let m=oF(o,"mermaid"),y=fN(o,"download"),v=fN(o,"copy"),x=fN(o,"fullscreen"),_=fN(o,"panZoom"),S=m&&(y||v||x);return l.jsx(b.Suspense,{fallback:l.jsx(ooe,{}),children:l.jsxs("div",{className:cn("group relative my-4 h-auto rounded-xl border p-4",t),"data-streamdown":"mermaid-block",children:[S?l.jsxs("div",{className:"flex items-center justify-end gap-2",children:[y?l.jsx(_At,{chart:f,config:s?.config}):null,v?l.jsx(aoe,{code:f}):null,x?l.jsx(kAt,{chart:f,config:s?.config}):null]}):null,l.jsx(jAt,{chart:f,config:s?.config,showControls:_})]})})}let p=oF(o,"code");return l.jsx(b.Suspense,{fallback:l.jsx(ooe,{}),children:l.jsx(IAt,{className:cn("overflow-x-auto border-border border-t",t),code:f,language:d,children:p?l.jsxs(l.Fragment,{children:[l.jsx(hAt,{code:f,language:d}),l.jsx(aoe,{})]}):null})})},_Re=b.memo(PAt,(e,t)=>e.className===t.className&&UR(e.node,t.node));_Re.displayName="MarkdownCode";var wRe=b.memo(gAt,(e,t)=>e.className===t.className&&UR(e.node,t.node));wRe.displayName="MarkdownImg";var SRe=b.memo(({children:e,className:t,node:n,...r})=>{let i=(Array.isArray(e)?e:[e]).filter(a=>a!=null&&a!=="");if(i.length===1&&b.isValidElement(i[0])){let a=i[0].props.node,s=a?.tagName;if(s==="img")return l.jsx(l.Fragment,{children:e});if(s==="code"&&"data-block"in i[0].props)return l.jsx(l.Fragment,{children:e})}return l.jsx("p",{className:t,...r,children:e})},(e,t)=>Vi(e,t));SRe.displayName="MarkdownParagraph";var $At={ol:lK,li:eRe,ul:tRe,hr:nRe,strong:rRe,a:iRe,h1:aRe,h2:sRe,h3:oRe,h4:lRe,h5:uRe,h6:cRe,table:dRe,thead:fRe,tbody:pRe,tr:hRe,th:mRe,td:gRe,blockquote:vRe,code:_Re,img:wRe,pre:({children:e})=>b.isValidElement(e)?b.cloneElement(e,{"data-block":"true"}):e,sup:yRe,sub:xRe,p:SRe,section:bRe},MAt=()=>e=>{Gp(e,"html",(t,n,r)=>{!r||typeof n!="number"||(r.children[n]={type:"text",value:t.value})})},loe=[],uoe={allowDangerousHtml:!0},pN=new WeakMap,DAt=class{constructor(){this.cache=new Map,this.keyCache=new WeakMap,this.maxSize=100}generateCacheKey(e){let t=this.keyCache.get(e);if(t)return t;let n=e.rehypePlugins,r=e.remarkPlugins,i=e.remarkRehypeOptions;if(!(n||r||i)){let d="default";return this.keyCache.set(e,d),d}let a=d=>{if(!d||d.length===0)return"";let f="";for(let p=0;p<d.length;p+=1){let m=d[p];if(p>0&&(f+=","),Array.isArray(m)){let[y,v]=m;if(typeof y=="function"){let x=pN.get(y);x||(x=y.name,pN.set(y,x)),f+=x}else f+=String(y);f+=":",f+=JSON.stringify(v)}else if(typeof m=="function"){let y=pN.get(m);y||(y=m.name,pN.set(m,y)),f+=y}else f+=String(m)}return f},s=a(n),o=a(r),u=i?JSON.stringify(i):"",c=`${o}::${s}::${u}`;return this.keyCache.set(e,c),c}get(e){let t=this.generateCacheKey(e),n=this.cache.get(t);return n&&(this.cache.delete(t),this.cache.set(t,n)),n}set(e,t){let n=this.generateCacheKey(e);if(this.cache.size>=this.maxSize){let r=this.cache.keys().next().value;r&&this.cache.delete(r)}this.cache.set(n,t)}clear(){this.cache.clear()}},coe=new DAt,kRe=e=>{let t=LAt(e),n=e.children||"";return VAt(t.runSync(t.parse(n),n),e)},LAt=e=>{let t=coe.get(e);if(t)return t;let n=UAt(e);return coe.set(e,n),n},zAt=e=>e.some(t=>Array.isArray(t)?t[0]===K7:t===K7),UAt=e=>{let t=e.rehypePlugins||loe,n=e.remarkPlugins||loe,r=zAt(t)?n:[...n,MAt],i=e.remarkRehypeOptions?{...uoe,...e.remarkRehypeOptions}:uoe;return uCt().use(lNt).use(r).use(HNt,i).use(t)},FAt=e=>e,BAt=(e,t,n,r)=>{n?e.children.splice(t,1):e.children[t]={type:"text",value:r}},qAt=(e,t)=>{var n;for(let r in G5)if(Object.hasOwn(G5,r)&&Object.hasOwn(e.properties,r)){let i=e.properties[r],a=G5[r];(a===null||a.includes(e.tagName))&&(e.properties[r]=(n=t(String(i||""),r,e))!=null?n:void 0)}},HAt=(e,t,n,r,i,a)=>{let s=!1;return r?s=!r.includes(e.tagName):i&&(s=i.includes(e.tagName)),!s&&a&&typeof t=="number"&&(s=!a(e,t,n)),s},VAt=(e,t)=>{let{allowElement:n,allowedElements:r,disallowedElements:i,skipHtml:a,unwrapDisallowed:s,urlTransform:o}=t;if(n||r||i||a||o){let u=o||FAt;Gp(e,(c,d,f)=>{if(c.type==="raw"&&f&&typeof d=="number")return BAt(f,d,a,c.value),d;if(c.type==="element"&&(qAt(c,u),HAt(c,d,f,r,i,n)&&f&&typeof d=="number"))return s&&c.children?f.children.splice(d,1,...c.children):f.children.splice(d,1),d})}return gTt(e,{Fragment:l.Fragment,components:t.components,ignoreInvalidStyle:!0,jsx:l.jsx,jsxs:l.jsxs,passKeys:!0,passNode:!0})},GAt=/\[\^[\w-]{1,200}\](?!:)/,WAt=/\[\^[\w-]{1,200}\]:/,KAt=/<\/(\w+)>/,ZAt=/<(\w+)[\s>]/,YAt=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]),XAt=e=>{let t=0;for(let n=0;n<e.length-1;n+=1)e[n]==="$"&&e[n+1]==="$"&&(t+=1,n+=1);return t},JAt=e=>{let t=GAt.test(e),n=WAt.test(e);if(t||n)return[e];let r=Tl.lex(e,{gfm:!0}),i=[],a=[],s=!1;for(let o of r){let u=o.raw,c=i.length;if(a.length>0){if(i[c-1]+=u,o.type==="html"){let d=u.match(KAt);if(d){let f=d[1];a.at(-1)===f&&a.pop()}}continue}if(o.type==="html"&&o.block){let d=u.match(ZAt);if(d){let f=d[1];u.includes(`</${f}>`)||YAt.has(f.toLowerCase())||a.push(f)}}if(c>0&&!s){let d=i[c-1];if(XAt(d)%2===1){i[c-1]=d+u;continue}}i.push(u),o.type!=="space"&&(s=o.type==="code")}return i},doe,foe,SC={...G1,protocols:{...G1.protocols,href:[...(foe=(doe=G1.protocols)==null?void 0:doe.href)!=null?foe:[],"tel"]}},lF={raw:K7,sanitize:[zOe,SC],harden:[Ixt,{allowedImagePrefixes:["*"],allowedLinkPrefixes:["*"],allowedProtocols:["*"],defaultOrigin:void 0,allowDataImages:!0}]},QAt={gfm:[Gkt,{}]},poe=Object.values(lF),eIt=Object.values(QAt),tIt={block:" ▋",circle:" ●"},nIt={shikiTheme:["github-light","github-dark"],controls:!0,isAnimating:!1,mode:"streaming",mermaid:void 0,linkSafety:{enabled:!0}},Ul=b.createContext(nIt),ERe=b.memo(({content:e,shouldParseIncompleteMarkdown:t,index:n,...r})=>l.jsx(kRe,{...r,children:e}),(e,t)=>{if(e.content!==t.content||e.index!==t.index)return!1;if(e.components!==t.components){let n=Object.keys(e.components||{}),r=Object.keys(t.components||{});if(n.length!==r.length||n.some(i=>{var a,s;return((a=e.components)==null?void 0:a[i])!==((s=t.components)==null?void 0:s[i])}))return!1}return!(e.rehypePlugins!==t.rehypePlugins||e.remarkPlugins!==t.remarkPlugins)});ERe.displayName="Block";var rIt=["github-light","github-dark"],TRe=b.memo(({children:e,mode:t="streaming",parseIncompleteMarkdown:n=!0,components:r,rehypePlugins:i=poe,remarkPlugins:a=eIt,className:s,shikiTheme:o=rIt,mermaid:u,controls:c=!0,isAnimating:d=!1,animated:f,BlockComponent:p=ERe,parseMarkdownIntoBlocksFn:m=JAt,caret:y,plugins:v,remend:x,linkSafety:_={enabled:!0},allowedTags:S,...w})=>{let T=b.useId(),[N,E]=b.useTransition(),A=b.useMemo(()=>typeof e!="string"?"":t==="streaming"&&n?eTt(e,x):e,[e,t,n,x]),I=b.useMemo(()=>m(A),[A,m]),[M,$]=b.useState(I);b.useEffect(()=>{t==="streaming"?E(()=>{$(I)}):$(I)},[I,t]);let O=t==="streaming"?M:I,R=b.useMemo(()=>O.map((X,L)=>`${T}-${L}`),[O.length,T]),U=b.useMemo(()=>f?f===!0?aF():aF(f):null,[f]),z=b.useMemo(()=>{var X,L;return{shikiTheme:(L=(X=v?.code)==null?void 0:X.getThemes())!=null?L:o,controls:c,isAnimating:d,mode:t,mermaid:u,linkSafety:_}},[o,c,d,t,u,_,v?.code]),F=b.useMemo(()=>({...$At,...r}),[r]),D=b.useMemo(()=>{let X=[];return v!=null&&v.cjk&&(X=[...X,...v.cjk.remarkPluginsBefore]),X=[...X,...a],v!=null&&v.cjk&&(X=[...X,...v.cjk.remarkPluginsAfter]),v!=null&&v.math&&(X=[...X,v.math.remarkPlugin]),X},[a,v?.math,v?.cjk]),W=b.useMemo(()=>{var X;let L=i;if(S&&Object.keys(S).length>0&&i===poe){let Y={...SC,tagNames:[...(X=SC.tagNames)!=null?X:[],...Object.keys(S)],attributes:{...SC.attributes,...S}};L=[lF.raw,[zOe,Y],lF.harden]}return v!=null&&v.math&&(L=[...L,v.math.rehypePlugin]),U&&d&&(L=[...L,U.rehypePlugin]),L},[i,v?.math,U,d,S]),q=b.useMemo(()=>y&&d?{"--streamdown-caret":`"${tIt[y]}"`}:void 0,[y,d]);return t==="static"?l.jsx(sF.Provider,{value:v??null,children:l.jsx(Ul.Provider,{value:z,children:l.jsx("div",{className:cn("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",s),children:l.jsx(kRe,{components:F,rehypePlugins:W,remarkPlugins:D,...w,children:e})})})}):l.jsx(sF.Provider,{value:v??null,children:l.jsx(Ul.Provider,{value:z,children:l.jsxs("div",{className:cn("space-y-4 whitespace-normal *:first:mt-0 *:last:mb-0",y?"*:last:after:inline *:last:after:align-baseline *:last:after:content-[var(--streamdown-caret)]":null,s),style:q,children:[O.length===0&&y&&d&&l.jsx("span",{}),O.map((X,L)=>l.jsx(p,{components:F,content:X,index:L,rehypePlugins:W,remarkPlugins:D,shouldParseIncompleteMarkdown:n,...w},R[L]))]})})})},(e,t)=>e.children===t.children&&e.shikiTheme===t.shikiTheme&&e.isAnimating===t.isAnimating&&e.animated===t.animated&&e.mode===t.mode&&e.plugins===t.plugins&&e.className===t.className&&e.linkSafety===t.linkSafety);TRe.displayName="Streamdown";var iIt=({children:e,className:t,minZoom:n=.5,maxZoom:r=3,zoomStep:i=.1,showControls:a=!0,initialZoom:s=1,fullscreen:o=!1})=>{let u=b.useRef(null),c=b.useRef(null),[d,f]=b.useState(s),[p,m]=b.useState({x:0,y:0}),[y,v]=b.useState(!1),[x,_]=b.useState({x:0,y:0}),[S,w]=b.useState({x:0,y:0}),T=b.useCallback(R=>{f(U=>Math.max(n,Math.min(r,U+R)))},[n,r]),N=b.useCallback(()=>{T(i)},[T,i]),E=b.useCallback(()=>{T(-i)},[T,i]),A=b.useCallback(()=>{f(s),m({x:0,y:0})},[s]),I=b.useCallback(R=>{R.preventDefault();let U=R.deltaY>0?-i:i;T(U)},[T,i]),M=b.useCallback(R=>{if(R.button!==0||R.isPrimary===!1)return;v(!0),_({x:R.clientX,y:R.clientY}),w(p);let U=R.currentTarget;U instanceof HTMLElement&&U.setPointerCapture(R.pointerId)},[p]),$=b.useCallback(R=>{if(!y)return;R.preventDefault();let U=R.clientX-x.x,z=R.clientY-x.y;m({x:S.x+U,y:S.y+z})},[y,x,S]),O=b.useCallback(R=>{v(!1);let U=R.currentTarget;U instanceof HTMLElement&&U.releasePointerCapture(R.pointerId)},[]);return b.useEffect(()=>{let R=u.current;if(R)return R.addEventListener("wheel",I,{passive:!1}),()=>{R.removeEventListener("wheel",I)}},[I]),b.useEffect(()=>{let R=c.current;if(R&&y)return document.body.style.userSelect="none",R.addEventListener("pointermove",$,{passive:!1}),R.addEventListener("pointerup",O),R.addEventListener("pointercancel",O),()=>{document.body.style.userSelect="",R.removeEventListener("pointermove",$),R.removeEventListener("pointerup",O),R.removeEventListener("pointercancel",O)}},[y,$,O]),l.jsxs("div",{className:cn("relative flex flex-col",o?"h-full w-full":"min-h-28 w-full",t),ref:u,style:{cursor:y?"grabbing":"grab"},children:[a?l.jsxs("div",{className:cn("absolute z-10 flex flex-col gap-1 rounded-md border border-border bg-background/90 p-1 shadow-sm backdrop-blur-sm",o?"bottom-4 left-4":"bottom-2 left-2"),children:[l.jsx("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:d>=r,onClick:N,title:"Zoom in",type:"button",children:l.jsx(dAt,{size:16})}),l.jsx("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground disabled:cursor-not-allowed disabled:opacity-50",disabled:d<=n,onClick:E,title:"Zoom out",type:"button",children:l.jsx(fAt,{size:16})}),l.jsx("button",{className:"flex items-center justify-center rounded p-1.5 text-muted-foreground transition-colors hover:bg-muted hover:text-foreground",onClick:A,title:"Reset zoom and pan",type:"button",children:l.jsx(cAt,{size:16})})]}):null,l.jsx("div",{className:cn("flex-1 origin-center transition-transform duration-150 ease-out",o?"flex h-full w-full items-center justify-center":"flex w-full items-center justify-center"),onPointerDown:M,ref:c,role:"application",style:{transform:`translate(${p.x}px, ${p.y}px) scale(${d})`,transformOrigin:"center center",touchAction:"none",willChange:"transform"},children:e})]})},NRe=({chart:e,className:t,config:n,fullscreen:r=!1,showControls:i=!0})=>{let[a,s]=b.useState(null),[o,u]=b.useState(!1),[c,d]=b.useState(""),[f,p]=b.useState(""),[m,y]=b.useState(0),{mermaid:v}=b.useContext(Ul),x=oK(),_=v?.errorComponent,{shouldRender:S,containerRef:w}=QCt({immediate:r});if(b.useEffect(()=>{if(S){if(!x){s("Mermaid plugin not available. Please add the mermaid plugin to enable diagram rendering.");return}(async()=>{try{s(null),u(!0);let N=x.getMermaid(n),E=e.split("").reduce((M,$)=>(M<<5)-M+$.charCodeAt(0)|0,0),A=`mermaid-${Math.abs(E)}-${Date.now()}-${Math.random().toString(36).substring(2,9)}`,{svg:I}=await N.render(A,e);d(I),p(I)}catch(N){if(!(f||c)){let E=N instanceof Error?N.message:"Failed to render Mermaid chart";s(E)}}finally{u(!1)}})()}},[e,n,m,S,x]),!(S||c||f))return l.jsx("div",{className:cn("my-4 min-h-[200px]",t),ref:w});if(o&&!c&&!f)return l.jsx("div",{className:cn("my-4 flex justify-center p-4",t),ref:w,children:l.jsxs("div",{className:"flex items-center space-x-2 text-muted-foreground",children:[l.jsx("div",{className:"h-4 w-4 animate-spin rounded-full border-current border-b-2"}),l.jsx("span",{className:"text-sm",children:"Loading diagram..."})]})});if(a&&!c&&!f){let N=()=>y(E=>E+1);return _?l.jsx("div",{ref:w,children:l.jsx(_,{chart:e,error:a,retry:N})}):l.jsxs("div",{className:cn("rounded-lg border border-red-200 bg-red-50 p-4",t),ref:w,children:[l.jsxs("p",{className:"font-mono text-red-700 text-sm",children:["Mermaid Error: ",a]}),l.jsxs("details",{className:"mt-2",children:[l.jsx("summary",{className:"cursor-pointer text-red-600 text-xs",children:"Show Code"}),l.jsx("pre",{className:"mt-2 overflow-x-auto rounded bg-red-100 p-2 text-red-800 text-xs",children:e})]})]})}let T=c||f;return l.jsx("div",{className:cn("size-full",t),"data-streamdown":"mermaid",ref:w,children:l.jsx(iIt,{className:cn(r?"size-full overflow-hidden":"my-4 overflow-hidden",t),fullscreen:r,maxZoom:3,minZoom:.5,showControls:i,zoomStep:.1,children:l.jsx("div",{"aria-label":"Mermaid chart",className:cn("flex justify-center",r?"size-full items-center":null),dangerouslySetInnerHTML:{__html:T},role:"img"})})})};function aIt(e){const t=Rr.lexer(e);return t.length===0?[e]:t.map(n=>n.raw)}const CRe=b.memo(({content:e})=>l.jsx(TRe,{children:e}),(e,t)=>e.content===t.content);CRe.displayName="MemoizedMarkdownBlock";const NI=b.memo(({content:e,className:t})=>b.useMemo(()=>aIt(e),[e]).map((r,i)=>l.jsx("div",{className:t,children:l.jsx(CRe,{content:r})},`markdown-block_${i}`)),(e,t)=>!(e.content!==t.content||e.className!==t.className));NI.displayName="MemoizedMarkdown";function sIt(e,t){const n=t.split(".").pop()?.toLowerCase()||"";return{js:"javascript",mjs:"javascript",jsx:"jsx",ts:"typescript",tsx:"tsx",py:"python",rb:"ruby",go:"go",rs:"rust",java:"java",c:"c",cpp:"cpp",h:"c",hpp:"cpp",sh:"bash",bash:"bash",zsh:"bash",fish:"fish",ps1:"powershell",sql:"sql",php:"php",swift:"swift",kt:"kotlin",scala:"scala",lua:"lua",r:"r",json:"json",yaml:"yaml",yml:"yaml",xml:"xml",html:"html",htm:"html",css:"css",toml:"toml",ini:"ini"}[n]||"text"}function hoe(e,t){return"```"+t+`
|
|
1700
1700
|
`+e+"\n```"}function oIt({file:e,loading:t,error:n,onLinkClick:r,rawMode:i=!1}){const a=b.useCallback(u=>{if(!r)return;const d=u.target.closest("a");if(!d)return;const f=d.getAttribute("href");f&&(f.startsWith("http://")||f.startsWith("https://")||f.startsWith("//")||(u.preventDefault(),r(f)))},[r]),s=()=>{if(!e)return;const u=e.isText?e.content:e.base64;if(!u)return;const c=e.isText?new Blob([u],{type:e.mimeType}):new Blob([Uint8Array.from(atob(u),p=>p.charCodeAt(0))],{type:e.mimeType}),d=URL.createObjectURL(c),f=document.createElement("a");f.href=d,f.download=e.name,document.body.appendChild(f),f.click(),document.body.removeChild(f),URL.revokeObjectURL(d)},o=b.useMemo(()=>{if(!e?.content||!e.mimeType.includes("markdown"))return null;if(i)return hoe(e.content,"yaml");let u=e.content;if(u.startsWith("---")){const c=u.indexOf("---",3);c!==-1&&(u=u.slice(c+3).trim())}return u},[e,i]);if(t)return l.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-center",children:[l.jsx("div",{className:"w-10 h-10 bg-muted rounded-full flex items-center justify-center mb-3",children:l.jsx(wn,{className:"h-4 w-4 text-muted-foreground animate-spin"})}),l.jsx("p",{className:"text-xs text-muted-foreground font-semibold",children:"Loading file..."})]});if(n)return l.jsx("div",{className:"h-full flex flex-col items-center justify-center p-6",children:l.jsx("div",{className:"p-3 bg-destructive/10 border border-destructive/20 rounded text-destructive text-xs font-medium max-w-md text-center",children:n})});if(!e)return l.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-center",children:[l.jsx(Um,{className:"h-8 w-8 text-muted-foreground/30 mb-3"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Select a file to view its content"})]});if(e.mimeType.startsWith("image/")&&e.base64)return l.jsx(Es,{className:"h-full",children:l.jsx("div",{className:"p-6 flex items-center justify-center",children:l.jsx("img",{src:`data:${e.mimeType};base64,${e.base64}`,alt:e.name,className:"max-w-full max-h-[70vh] object-contain rounded-md border border-border"})})});if(e.mimeType.includes("markdown")&&e.content)return l.jsxs(Es,{className:"h-full",children:[l.jsx("div",{onClick:a,className:i?"p-4 min-w-max":"p-6 prose prose-sm dark:prose-invert max-w-none",children:l.jsx(NI,{content:o||e.content})}),l.jsx(P7,{orientation:"horizontal"})]});if(e.isText&&e.content){const u=sIt(e.mimeType,e.name),c=hoe(e.content,u);return l.jsxs(Es,{className:"h-full",children:[l.jsx("div",{onClick:a,className:"p-4 min-w-max",children:l.jsx(NI,{content:c})}),l.jsx(P7,{orientation:"horizontal"})]})}return l.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-center p-6",children:[l.jsx(Um,{className:"h-12 w-12 text-muted-foreground/30 mb-4"}),l.jsx("p",{className:"text-sm font-medium text-foreground mb-1",children:"Binary File"}),l.jsxs("p",{className:"text-xs text-muted-foreground mb-4",children:[e.mimeType," (",lIt(e.size),")"]}),l.jsxs(Ee,{variant:"outline",size:"sm",onClick:s,children:[l.jsx(C1e,{className:"h-3 w-3 mr-2"}),"Download File"]})]})}function lIt(e){return e<1024?`${e} bytes`:e<1024*1024?`${(e/1024).toFixed(1)} KB`:`${(e/1024/1024).toFixed(2)} MB`}function uIt(){const e=ci(),[t,n]=b.useState([]),[r,i]=b.useState(""),[a,s]=b.useState(null),[o,u]=b.useState(!1),[c,d]=b.useState(!1),[f,p]=b.useState(""),[m,y]=b.useState(!1),[v,x]=b.useState(null),[_,S]=b.useState(!1),[w,T]=b.useState({}),[N,E]=b.useState({}),[A,I]=b.useState("SKILL.md"),[M,$]=b.useState(null),[O,R]=b.useState(!1),[U,z]=b.useState(""),[F,D]=b.useState(!1),[W,q]=b.useState(!1),[X,L]=b.useState(!1),Y=async()=>{if(M?.content)try{await navigator.clipboard.writeText(M.content),D(!0),setTimeout(()=>D(!1),2e3)}catch(Z){console.error("Failed to copy:",Z)}};b.useEffect(()=>{G()},[]),b.useEffect(()=>{r?P(r):(s(null),I("SKILL.md"),$(null))},[r]),b.useEffect(()=>{r&&A&&K(r,A)},[r,A]);const G=async()=>{d(!0),p("");try{const Z=await aI();n(Z),Z.length===0?(i(""),s(null)):Z.some(ne=>ne.name===r)||i(Z[0].name)}catch(Z){const ne=Z instanceof Error?Z.message:`Could not fetch skills: ${Z}`;p(ne)}finally{d(!1)}},P=async Z=>{u(!0),p("");try{const ne=await Sje(Z);s(ne)}catch(ne){const J=ne instanceof Error?ne.message:`Error getting skill: ${ne}`;p(J)}finally{u(!1)}},V=b.useCallback(async Z=>{if(!(w[Z]&&w[Z].length>0)){E(ne=>({...ne,[Z]:!0}));try{const ne=await kje(Z);T(J=>({...J,[Z]:ne}))}catch(ne){console.error("Error fetching skill files:",ne),T(J=>({...J,[Z]:[]}))}finally{E(ne=>({...ne,[Z]:!1}))}}},[w]),K=async(Z,ne)=>{R(!0),z("");try{const J=await Eje(Z,ne);$(J)}catch(J){const se=J instanceof Error?J.message:`Error reading file: ${J}`;z(se),$(null)}finally{R(!1)}},Q=async()=>{if(v){S(!0);try{await Cyt(v),e.capture("skill_deleted",{skill_name:v}),await G(),r===v&&(i(""),s(null)),T(Z=>{const ne={...Z};return delete ne[v],ne})}catch(Z){const ne=Z instanceof Error?Z.message:`Error deleting skill: ${Z}`;p(ne)}finally{S(!1),x(null)}}},oe=()=>{G(),y(!1)},re=Z=>{i(Z),I("SKILL.md"),q(!1),L(!1),e.capture("skill_viewed",{skill_name:Z}),K(Z,"SKILL.md")},ee=(Z,ne)=>{Z!==r&&i(Z),I(ne),q(!1),K(Z,ne)},le=Z=>{V(Z)},te=Z=>{I(Z),q(!1)};return l.jsxs("div",{className:"h-full flex flex-col",children:[l.jsxs(Bc,{direction:"horizontal",className:"flex-1",children:[l.jsx(ta,{defaultSize:25,minSize:15,maxSize:40,children:l.jsxs("div",{className:"h-full flex flex-col border-r border-border bg-background",children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-4 border-b border-border bg-background",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(ly,{className:"h-3 w-3 text-muted-foreground"}),l.jsx("h2",{className:"text-xs font-semibold text-foreground",children:"Skills"}),l.jsx(Cn,{variant:"secondary",className:"text-xs font-mono",children:t.length})]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Ee,{onClick:()=>y(!0),variant:"ghost",size:"sm",title:"Upload skill",children:l.jsx(_o,{className:"h-3 w-3 cursor-pointer"})}),l.jsx(Ee,{onClick:G,variant:"ghost",size:"sm",disabled:c,children:l.jsx(wn,{className:`h-3 w-3 ${c?"animate-spin":""} cursor-pointer`})})]})]}),l.jsx("div",{className:"flex-1 overflow-hidden",children:l.jsx(Es,{className:"h-full",children:l.jsx("div",{className:"p-2",children:c?l.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[l.jsx("div",{className:"w-8 h-8 bg-muted rounded-full flex items-center justify-center mb-3",children:l.jsx(wn,{className:"h-4 w-4 text-muted-foreground animate-spin cursor-pointer"})}),l.jsx("p",{className:"text-xs text-muted-foreground font-semibold mb-1",children:"Loading skills..."})]}):t.length===0?l.jsxs("div",{className:"text-center py-8",children:[l.jsx("p",{className:"text-sm text-muted-foreground mb-4",children:"No skills available"}),l.jsxs(Ee,{variant:"outline",size:"sm",onClick:()=>y(!0),children:[l.jsx(_o,{className:"h-3 w-3 mr-2"}),"Upload your first skill"]})]}):l.jsx(Lyt,{skills:t,skillFiles:w,loadingSkills:c,loadingFiles:N,selectedSkillName:r,selectedFilePath:A,onSelectSkill:re,onSelectFile:ee,onExpandSkill:le})})})})]})}),l.jsx($u,{withHandle:!0}),l.jsx(ta,{defaultSize:75,minSize:50,children:l.jsx("div",{className:"h-full flex flex-col bg-background",children:r&&a?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border gap-4",children:[l.jsxs("div",{className:"flex flex-col gap-0.5 min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-2 min-w-0",children:[l.jsx("span",{className:"font-medium text-sm text-foreground truncate",children:a.name}),A==="SKILL.md"?l.jsx("span",{className:"text-xs text-muted-foreground/60 font-mono truncate",title:a.path,children:a.path}):l.jsxs(l.Fragment,{children:[l.jsx("span",{className:"text-muted-foreground",children:"/"}),l.jsx("span",{className:"text-sm text-muted-foreground truncate",children:A})]})]}),A==="SKILL.md"&&a.description&&l.jsx("p",{onClick:()=>L(!X),className:`text-xs text-muted-foreground cursor-pointer hover:text-muted-foreground/80 ${X?"":"line-clamp-1"}`,children:a.description})]}),l.jsxs("div",{className:"flex items-center gap-1 flex-shrink-0",children:[M?.isText&&M.mimeType.includes("markdown")&&l.jsx(Ee,{onClick:()=>q(!W),variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-foreground",title:W?"Show rendered":"Show raw",children:W?l.jsx(sA,{className:"h-4 w-4"}):l.jsx(XXe,{className:"h-4 w-4"})}),M?.isText&&l.jsx(Ee,{onClick:Y,variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-foreground",title:"Copy",children:F?l.jsx(xi,{className:"h-4 w-4"}):l.jsx(Ca,{className:"h-4 w-4"})}),l.jsx(Ee,{onClick:()=>x(a.name),variant:"ghost",size:"icon",className:"h-8 w-8 text-muted-foreground hover:text-destructive hover:bg-destructive/10",title:"Delete skill",children:l.jsx(Ll,{className:"h-4 w-4"})})]})]}),l.jsx("div",{className:"flex-1 overflow-hidden",children:l.jsx(oIt,{file:M,loading:O,error:U,onLinkClick:te,rawMode:W})})]}):l.jsx("div",{className:"h-full flex items-center justify-center",children:l.jsx(Rc,{icon:ly,title:"Select a Skill",description:"Choose a skill from the left to view its content, or create a new one."})})})})]}),l.jsx(Tje,{open:m,onOpenChange:y,onSkillCreated:oe}),l.jsx(sI,{open:!!v,onOpenChange:()=>x(null),children:l.jsxs(oI,{children:[l.jsxs(lI,{children:[l.jsx(cI,{children:"Delete Skill"}),l.jsxs(dI,{children:['Are you sure you want to delete the skill "',v,'"? This will remove the skill directory and its SKILL.md file. This action cannot be undone.']})]}),l.jsxs(uI,{children:[l.jsx(pI,{disabled:_,children:"Cancel"}),l.jsx(fI,{onClick:Q,disabled:_,className:"bg-destructive text-destructive-foreground hover:bg-destructive/90",children:_?"Deleting...":"Delete"})]})]})})]})}function uK({className:e,value:t,...n}){return l.jsx(FKe,{"data-slot":"progress",className:Ie("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",e),...n,children:l.jsx(BKe,{"data-slot":"progress-indicator",className:"bg-primary h-full w-full flex-1 transition-all",style:{transform:`translateX(-${100-(t||0)}%)`}})})}function cIt({className:e,...t}){return l.jsx("div",{"data-slot":"progress-indeterminate",className:Ie("bg-primary/20 relative h-2 w-full overflow-hidden rounded-full",e),...t,children:l.jsx("div",{"data-slot":"progress-indeterminate-indicator",className:"bg-primary h-full w-1/3 absolute rounded-full animate-[progress-indeterminate_1.5s_ease-in-out_infinite]"})})}const uF={working:{icon:Pn,color:"text-info",bgColor:"bg-info/10",animate:!0},input_required:{icon:Gs,color:"text-warning",bgColor:"bg-warning/10",animate:!1},completed:{icon:yU,color:"text-success",bgColor:"bg-success/10",animate:!1},failed:{icon:qd,color:"text-destructive",bgColor:"bg-destructive/10",animate:!1},cancelled:{icon:BQe,color:"text-muted-foreground",bgColor:"bg-muted",animate:!1}};function dIt(e){try{return p9e(new Date(e),{addSuffix:!0})}catch{return e}}function fIt(e){try{const t=Date.now()-new Date(e).getTime();if(t<1e3)return"<1s";if(t<6e4)return`${Math.floor(t/1e3)}s`;if(t<36e5){const i=Math.floor(t/6e4),a=Math.floor(t%6e4/1e3);return`${i}m ${a}s`}const n=Math.floor(t/36e5),r=Math.floor(t%36e5/6e4);return`${n}h ${r}m`}catch{return"—"}}function pIt(e){const[t,n]=b.useState(null);return b.useEffect(()=>{if(!e){n(null);return}let r=!0;const i=async()=>{try{const s=await fje(e);r&&n(s)}catch(s){console.debug("Failed to fetch progress:",s)}};i();const a=setInterval(i,500);return()=>{r=!1,clearInterval(a)}},[e]),{progress:t?.progress??0,total:t?.total,message:t?.message,progressToken:t?.progressToken,timestamp:t?.timestamp}}function hIt({serverId:e,showElapsedTime:t=!0,startedAt:n}){const{progress:r,total:i,message:a}=pIt(e);return l.jsxs("div",{className:"mt-2 space-y-1",children:[i?l.jsx(uK,{value:r/i*100,className:"h-1.5"}):l.jsx(cIt,{className:"h-1.5"}),l.jsxs("div",{className:"flex items-center justify-between text-[10px] text-muted-foreground",children:[l.jsx("span",{className:"truncate max-w-[150px]",children:a||(i?`${r}/${i}`:"Working...")}),t&&n&&l.jsx("span",{className:"font-mono",children:fIt(n)})]})]})}function mIt(e=!0){const[t,n]=b.useState(null),[r,i]=b.useState(!1),[a,s]=b.useState(null),o=b.useRef(null);b.useEffect(()=>{if(!e){o.current&&(o.current.close(),o.current=null);return}const d=new EventSource(qq("/api/mcp/elicitation/stream"));return o.current=d,d.onmessage=f=>{try{const p=JSON.parse(f.data);p?.type==="elicitation_request"&&p.relatedTaskId?n({requestId:p.requestId,message:p.message,schema:p.schema,timestamp:p.timestamp||new Date().toISOString(),relatedTaskId:p.relatedTaskId}):p?.type==="elicitation_complete"&&n(m=>m&&(!p.requestId||p.requestId===m.requestId)?null:m)}catch{}},d.onerror=()=>{},()=>{d.close(),o.current=null}},[e]);const u=b.useCallback(async(d,f)=>{if(t){i(!0),s(null);try{await J0t(t.requestId,d,f),n(null)}catch(p){const m=p instanceof Error?p.message:"Failed to respond";throw s(m),p}finally{i(!1)}}},[t]),c=b.useCallback(()=>{n(null),s(null)},[]);return{elicitation:t,isResponding:r,error:a,respond:u,clear:c}}const moe="mcp-inspector-tasks-poll-interval",gIt=3e3;function nD({status:e}){const t=uF[e],n=t.icon;return l.jsx(n,{className:`h-4 w-4 ${t.color} ${t.animate?"animate-spin":""}`})}function goe(e){try{return new Date(e).toLocaleString()}catch{return e}}function rD(e){return e==="completed"||e==="failed"||e==="cancelled"}function vIt({serverConfig:e,serverName:t,isActive:n=!0}){const[r,i]=b.useState([]),[a,s]=b.useState(""),[o,u]=b.useState(null),[c,d]=b.useState(null),[f,p]=b.useState(!1),[m,y]=b.useState(!1),[v,x]=b.useState(""),[_,S]=b.useState(!1),[w,T]=b.useState(!1),N=b.useRef(!1),[E,A]=b.useState(()=>{const J=localStorage.getItem(moe);if(J){const se=parseInt(J,10);if(!isNaN(se)&&se>0)return se}return gIt}),[I,M]=b.useState(null),[$,O]=b.useState(null),[R,U]=b.useState(void 0),z=b.useRef(null),[F,D]=b.useState(!0),W=b.useMemo(()=>r.find(J=>J.taskId===a)??null,[r,a]),q=b.useMemo(()=>r.some(J=>!rD(J.status)),[r]);b.useEffect(()=>{q&&!N.current?S(!0):q||(S(!1),N.current=!1)},[q]);const X=b.useMemo(()=>{const J=r.filter(se=>!rD(se.status)&&se.pollInterval).map(se=>se.pollInterval);return J.length===0?null:Math.min(...J)},[r]),{elicitation:L,isResponding:Y,respond:G}=mIt(n),P=L?{requestId:L.requestId,message:L.message,schema:L.schema,timestamp:L.timestamp}:null,V=I??X??E,K=X!==null&&I===null,Q=b.useCallback(J=>{const se=parseInt(J,10);!isNaN(se)&&se>=500&&(X!==null&&M(se),A(se),localStorage.setItem(moe,String(se)))},[X]);b.useEffect(()=>{X===null&&M(null)},[X]);const oe=b.useCallback(()=>{if(!t)return;const J=r.map(se=>se.taskId);ivt(t,J),svt(t),i([]),s(""),u(null),d(null)},[t,r]),re=b.useCallback(async()=>{if(t){y(!0),x("");try{const J=avt(t);let se={tasks:[]},ie=new Set;R?.supportsList&&(se=await Z0t(t),ie=new Set(se.tasks.map(ce=>ce.taskId)));const he=evt(t),Ne=[...(await Promise.all(he.filter(ce=>!ie.has(ce.taskId)).filter(ce=>!J.has(ce.taskId)).map(async ce=>{try{return await Y0t(t,ce.taskId)}catch{return rvt(ce.taskId),null}}))).filter(ce=>ce!==null),...se.tasks.filter(ce=>!J.has(ce.taskId))];Ne.sort((ce,Te)=>{const we=new Date(ce.createdAt).getTime();return new Date(Te.createdAt).getTime()-we}),i(Ne)}catch(J){x(J instanceof Error?J.message:"Failed to fetch tasks")}finally{y(!1)}}},[t,R]),ee=b.useCallback(async(J,se)=>{try{await G(J,se),await re()}catch(ie){x(ie instanceof Error?ie.message:"Failed to respond to elicitation")}},[G,re]),le=b.useCallback(async J=>{if(t){p(!0),x("");try{const se=await hie(t,J);u(se)}catch(se){x(se instanceof Error?se.message:"Failed to fetch task result")}finally{p(!1)}}},[t]),te=b.useCallback(async()=>{if(!(!t||!a)){T(!0),x("");try{await X0t(t,a),await re()}catch(J){x(J instanceof Error?J.message:"Failed to cancel task")}finally{T(!1)}}},[t,a,re]);if(b.useEffect(()=>{if(!e||!t){U(void 0);return}U(void 0),(async()=>{try{const se=await dje(t);U(se)}catch{U(null)}})()},[e,t]),b.useEffect(()=>{e&&t&&n&&R!==void 0&&(i([]),s(""),u(null),re())},[e,t,re,n,R]),b.useEffect(()=>{if(!_||!t||!n)return;const J=setInterval(()=>{re()},V);return()=>clearInterval(J)},[_,t,re,V,n]),b.useEffect(()=>{if(W?.status==="completed"||W?.status==="failed")d(null),z.current=null,le(a);else if(W?.status==="input_required"){u(null);const J=a;z.current=J,(async()=>{if(t){p(!0);try{const se=await hie(t,J);z.current===J&&d(se)}catch{}finally{z.current===J&&p(!1)}}})()}else u(null),d(null),z.current=null},[a,W?.status,le,t]),b.useEffect(()=>{if(!t||!n)return;if(!r.some(he=>he.status==="working")){O(null);return}const se=async()=>{try{const he=await fje(t);O(he)}catch(he){console.debug("Failed to fetch progress:",he)}};se();const ie=setInterval(se,500);return()=>clearInterval(ie)},[t,r,n]),!e||!t)return l.jsx(Rc,{icon:xU,title:"No Server Selected",description:"Connect to an MCP server to browse and manage its tasks."});const Z=l.jsxs("div",{className:"h-full flex flex-col border-r border-border bg-background",children:[l.jsx("div",{className:"border-b border-border flex-shrink-0",children:l.jsxs("div",{className:"px-2 py-1.5 flex items-center gap-2",children:[l.jsx("div",{className:"flex items-center gap-1.5",children:l.jsxs("button",{className:"px-3 py-1.5 rounded-md text-xs font-medium bg-primary/10 text-primary cursor-default",children:["Tasks",l.jsx("span",{className:"ml-1 text-[10px] font-mono opacity-70",children:r.length})]})}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Ct,{type:"number",min:500,step:500,defaultValue:V,onBlur:J=>Q(J.target.value),className:"h-6 w-14 text-[10px] px-1.5 text-center [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"},`poll-${V}`),l.jsx("span",{className:"text-[10px] text-muted-foreground",children:"ms"}),K&&l.jsx(Cn,{variant:"secondary",className:"text-[9px] px-1 py-0 h-4",children:"server"})]})}),l.jsx(zt,{side:"bottom",className:"max-w-xs",children:K?l.jsxs("span",{children:["Prefilled with server-suggested interval.",l.jsx("br",{}),"Edit to override."]}):l.jsx("span",{children:"Poll interval (min 500ms)"})})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(JO,{id:"auto-refresh",checked:_,onCheckedChange:J=>{S(J),J||(N.current=!0)},className:"scale-75"}),l.jsx("label",{htmlFor:"auto-refresh",className:"text-[10px] text-muted-foreground cursor-pointer",children:"Auto"})]})}),l.jsx(zt,{side:"bottom",children:"Automatically poll for task status updates"})]}),l.jsxs("div",{className:"flex items-center gap-0.5 text-muted-foreground/80",children:[l.jsx(Ee,{onClick:re,variant:"ghost",size:"sm",disabled:m,className:"h-7 w-7 p-0",title:"Refresh tasks",children:l.jsx(wn,{className:`h-3.5 w-3.5 ${m?"animate-spin":""}`})}),l.jsx(Ee,{onClick:oe,variant:"ghost",size:"sm",disabled:r.length===0,className:"h-7 w-7 p-0",title:"Clear all tasks",children:l.jsx(Ll,{className:"h-3.5 w-3.5"})}),l.jsx(Ee,{onClick:()=>D(!1),variant:"ghost",size:"sm",className:"h-7 w-7 p-0",title:"Hide sidebar",children:l.jsx(gS,{className:"h-3.5 w-3.5"})})]})]})}),l.jsx("div",{className:"flex-1 overflow-hidden",children:l.jsx(Es,{className:"h-full",children:l.jsx("div",{className:"p-2 pb-16",children:m&&r.length===0?l.jsxs("div",{className:"flex flex-col items-center justify-center py-16 text-center",children:[l.jsx("div",{className:"w-8 h-8 bg-muted rounded-full flex items-center justify-center mb-3",children:l.jsx(wn,{className:"h-4 w-4 text-muted-foreground animate-spin"})}),l.jsx("p",{className:"text-xs text-muted-foreground font-semibold mb-1",children:"Loading tasks..."}),l.jsx("p",{className:"text-xs text-muted-foreground/70",children:"Fetching active tasks from server"})]}):r.length===0?l.jsxs("div",{className:"text-center py-8",children:[l.jsx("p",{className:"text-sm text-muted-foreground",children:"No tasks available"}),l.jsx("p",{className:"text-xs text-muted-foreground/70 mt-1",children:"Tasks will appear here when created by tool calls"})]}):l.jsx("div",{className:"space-y-1",children:r.map(J=>{const se=tvt(J.taskId),ie=se?.primitiveName||se?.toolName||J.taskId.substring(0,12);return l.jsx("div",{className:`cursor-pointer transition-all duration-200 hover:bg-muted/30 dark:hover:bg-muted/50 p-3 rounded-md mx-2 ${a===J.taskId?"bg-muted/50 dark:bg-muted/50 shadow-sm border border-border ring-1 ring-ring/20":"hover:shadow-sm"}`,onClick:()=>s(J.taskId),children:l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsx("div",{className:"mt-0.5",children:l.jsx(nD,{status:J.status})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("span",{className:"font-medium text-xs text-foreground truncate block mb-1",children:ie}),l.jsx("span",{className:"text-[10px] text-muted-foreground",children:dIt(J.createdAt)}),J.status==="working"&&l.jsx(hIt,{serverId:t,startedAt:J.createdAt})]}),l.jsx(wr,{className:"h-3 w-3 text-muted-foreground flex-shrink-0 mt-1"})]})},J.taskId)})})})})})]}),ne=l.jsx("div",{className:"h-full flex flex-col bg-background",children:W?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"flex items-center justify-between px-6 py-4 border-b border-border bg-background",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(nD,{status:W.status}),l.jsx(Cn,{variant:"outline",className:`text-xs ${uF[W.status].bgColor} ${uF[W.status].color} border-0`,children:W.status})]}),l.jsx("code",{className:"font-mono font-semibold text-foreground bg-muted px-2 py-1 rounded-md border border-border text-xs",children:W.taskId}),W.ttl!==null&&l.jsxs(Cn,{variant:"outline",className:"text-xs",children:["TTL: ",W.ttl,"ms"]}),W.pollInterval&&l.jsxs(Cn,{variant:"outline",className:"text-xs",children:["Poll interval: ",W.pollInterval,"ms"]})]}),!rD(W.status)&&l.jsx(Ee,{onClick:te,disabled:w,variant:"destructive",size:"sm",children:w?l.jsxs(l.Fragment,{children:[l.jsx(wn,{className:"h-3 w-3 animate-spin"}),"Cancelling"]}):l.jsxs(l.Fragment,{children:[l.jsx(L1e,{className:"h-3 w-3"}),"Cancel Task"]})})]}),l.jsxs("div",{className:"px-6 py-4 bg-muted/50 border-b border-border space-y-3",children:[l.jsxs("div",{className:"grid grid-cols-2 gap-4 text-xs",children:[l.jsxs("div",{children:[l.jsx("span",{className:"text-muted-foreground",children:"Created:"}),l.jsx("span",{className:"ml-2 font-mono text-foreground",children:goe(W.createdAt)})]}),l.jsxs("div",{children:[l.jsx("span",{className:"text-muted-foreground",children:"Updated:"}),l.jsx("span",{className:"ml-2 font-mono text-foreground",children:goe(W.lastUpdatedAt)})]})]}),W.statusMessage&&l.jsx("p",{className:"text-xs text-muted-foreground leading-relaxed",children:W.statusMessage}),W.status==="working"&&$&&$.total&&l.jsxs("div",{className:"space-y-1.5 pt-2",children:[l.jsxs("div",{className:"flex items-center justify-between text-xs",children:[l.jsx("span",{className:"text-muted-foreground",children:"Progress"}),l.jsxs("span",{className:"font-mono text-foreground",children:[$.progress," / ",$.total,l.jsxs("span",{className:"ml-2 text-muted-foreground",children:["(",Math.round($.progress/$.total*100),"%)"]})]})]}),l.jsx(uK,{value:$.progress/$.total*100,className:"h-2"}),$.message&&l.jsx("p",{className:"text-xs text-muted-foreground/80 italic",children:$.message})]})]}),l.jsxs("div",{className:"flex-1 overflow-hidden flex flex-col",children:[l.jsx("div",{className:"px-6 py-3 border-b border-border bg-background",children:l.jsx("h3",{className:"text-xs font-semibold text-foreground",children:W.status==="input_required"?"Pending Request":"Task Result"})}),l.jsxs("div",{className:"flex-1 min-h-0 p-4 flex flex-col",children:[v&&l.jsx("div",{className:"mb-4 p-3 bg-destructive/10 border border-destructive/20 rounded text-destructive text-xs font-medium",children:v}),f?l.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-center",children:[l.jsx(wn,{className:"h-4 w-4 text-muted-foreground animate-spin mb-2"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Fetching result..."})]}):W.status==="input_required"?c?l.jsx("div",{className:"flex-1 min-h-0 border border-border rounded-md overflow-hidden",children:l.jsx(zn,{value:c,readOnly:!0,showToolbar:!1,collapsible:!0,defaultExpandDepth:2,collapseStringsAfterLength:100,height:"100%"})}):l.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-center",children:[l.jsx(Gs,{className:"h-4 w-4 text-warning mb-2"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Waiting for input from client"})]}):W.status==="completed"||W.status==="failed"?o!==null?l.jsx("div",{className:"flex-1 min-h-0 border border-border rounded-md overflow-hidden",children:l.jsx(zn,{value:o,readOnly:!0,showToolbar:!1,collapsible:!0,defaultExpandDepth:2,collapseStringsAfterLength:100,height:"100%"})}):l.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-center",children:[l.jsx(wn,{className:"h-4 w-4 text-muted-foreground animate-spin mb-2"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading result..."})]}):l.jsxs("div",{className:"h-full flex flex-col items-center justify-center text-center",children:[l.jsx(nD,{status:W.status}),l.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:W.status==="working"?"Result available when task completes":"No result available"})]})]})]})]}):l.jsx("div",{className:"h-full flex items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"w-12 h-12 bg-muted rounded-full flex items-center justify-center mx-auto mb-3",children:l.jsx(xU,{className:"h-5 w-5 text-muted-foreground"})}),l.jsx("p",{className:"text-xs font-semibold text-foreground mb-1",children:"No selection"}),l.jsx("p",{className:"text-xs text-muted-foreground font-medium",children:"Choose a task from the left to view its details"})]})})});return l.jsxs(l.Fragment,{children:[l.jsx(mR,{id:"tasks",sidebar:Z,content:ne,sidebarVisible:F,onSidebarVisibilityChange:D,sidebarTooltip:"Show tasks sidebar",serverName:t}),l.jsx(uW,{elicitationRequest:P,onResponse:ee,loading:Y})]})}function hu(...e){return D9(dn(e))}function yIt(){return Math.random().toString(36).substr(2,9)}function voe(e,t,n){return{id:yIt(),role:e,content:t,timestamp:new Date,attachments:n,metadata:{createdAt:new Date().toISOString()}}}function xIt(e){return["text/plain","application/pdf","image/jpeg","image/jpg","image/png","image/gif","image/webp","application/json","text/csv","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"].includes(e.type)}function ARe(e){return e.type.startsWith("image/")}function cF(e){if(e===0)return"0 B";const t=1024,n=["B","KB","MB","GB"],r=Math.floor(Math.log(e)/Math.log(t));return parseFloat((e/Math.pow(t,r)).toFixed(2))+" "+n[r]}function dF(){return dF=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)({}).hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},dF.apply(null,arguments)}function bIt(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}var _It=b.useLayoutEffect,wIt=function(t){var n=de.useRef(t);return _It(function(){n.current=t}),n},yoe=function(t,n){if(typeof t=="function"){t(n);return}t.current=n},SIt=function(t,n){var r=de.useRef();return de.useCallback(function(i){t.current=i,r.current&&yoe(r.current,null),r.current=n,n&&yoe(n,i)},[n])},xoe={"min-height":"0","max-height":"none",height:"0",visibility:"hidden",overflow:"hidden",position:"absolute","z-index":"-1000",top:"0",right:"0",display:"block"},kIt=function(t){Object.keys(xoe).forEach(function(n){t.style.setProperty(n,xoe[n],"important")})},boe=kIt,Ps=null,_oe=function(t,n){var r=t.scrollHeight;return n.sizingStyle.boxSizing==="border-box"?r+n.borderSize:r-n.paddingSize};function EIt(e,t,n,r){n===void 0&&(n=1),r===void 0&&(r=1/0),Ps||(Ps=document.createElement("textarea"),Ps.setAttribute("tabindex","-1"),Ps.setAttribute("aria-hidden","true"),boe(Ps)),Ps.parentNode===null&&document.body.appendChild(Ps);var i=e.paddingSize,a=e.borderSize,s=e.sizingStyle,o=s.boxSizing;Object.keys(s).forEach(function(p){var m=p;Ps.style[m]=s[m]}),boe(Ps),Ps.value=t;var u=_oe(Ps,e);Ps.value=t,u=_oe(Ps,e),Ps.value="x";var c=Ps.scrollHeight-i,d=c*n;o==="border-box"&&(d=d+i+a),u=Math.max(d,u);var f=c*r;return o==="border-box"&&(f=f+i+a),u=Math.min(f,u),[u,c]}var woe=function(){},TIt=function(t,n){return t.reduce(function(r,i){return r[i]=n[i],r},{})},NIt=["borderBottomWidth","borderLeftWidth","borderRightWidth","borderTopWidth","boxSizing","fontFamily","fontSize","fontStyle","fontWeight","letterSpacing","lineHeight","paddingBottom","paddingLeft","paddingRight","paddingTop","tabSize","textIndent","textRendering","textTransform","width","wordBreak","wordSpacing","scrollbarGutter"],CIt=!!document.documentElement.currentStyle,AIt=function(t){var n=window.getComputedStyle(t);if(n===null)return null;var r=TIt(NIt,n),i=r.boxSizing;if(i==="")return null;CIt&&i==="border-box"&&(r.width=parseFloat(r.width)+parseFloat(r.borderRightWidth)+parseFloat(r.borderLeftWidth)+parseFloat(r.paddingRight)+parseFloat(r.paddingLeft)+"px");var a=parseFloat(r.paddingBottom)+parseFloat(r.paddingTop),s=parseFloat(r.borderBottomWidth)+parseFloat(r.borderTopWidth);return{sizingStyle:r,paddingSize:a,borderSize:s}},IIt=AIt;function cK(e,t,n){var r=wIt(n);b.useLayoutEffect(function(){var i=function(s){return r.current(s)};if(e)return e.addEventListener(t,i),function(){return e.removeEventListener(t,i)}},[])}var jIt=function(t,n){cK(document.body,"reset",function(r){t.current.form===r.target&&n(r)})},OIt=function(t){cK(window,"resize",t)},RIt=function(t){cK(document.fonts,"loadingdone",t)},PIt=["cacheMeasurements","maxRows","minRows","onChange","onHeightChange"],$It=function(t,n){var r=t.cacheMeasurements,i=t.maxRows,a=t.minRows,s=t.onChange,o=s===void 0?woe:s,u=t.onHeightChange,c=u===void 0?woe:u,d=bIt(t,PIt),f=d.value!==void 0,p=b.useRef(null),m=SIt(p,n),y=b.useRef(0),v=b.useRef(),x=function(){var w=p.current,T=r&&v.current?v.current:IIt(w);if(T){v.current=T;var N=EIt(T,w.value||w.placeholder||"x",a,i),E=N[0],A=N[1];y.current!==E&&(y.current=E,w.style.setProperty("height",E+"px","important"),c(E,{rowHeight:A}))}},_=function(w){f||x(),o(w)};return b.useLayoutEffect(x),jIt(p,function(){if(!f){var S=p.current.value;requestAnimationFrame(function(){var w=p.current;w&&S!==w.value&&x()})}}),OIt(x),RIt(x),b.createElement("textarea",dF({},d,{onChange:_,ref:m}))},MIt=b.forwardRef($It);function IRe({className:e,...t}){return l.jsx(MIt,{"data-slot":"textarea",className:Ie("border-input placeholder:text-muted-foreground focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 flex field-sizing-content min-h-16 w-full rounded-md border bg-transparent px-3 py-2 text-base shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 md:text-sm",e),...t})}function DIt({onSkillSelected:e,highlightedIndex:t,setHighlightedIndex:n,startIndex:r,isHovering:i,actionTrigger:a,onOpenUploadDialog:s}){const o=ci(),[u,c]=b.useState([]),[d,f]=b.useState(null),[p,m]=b.useState(!0);b.useEffect(()=>{let v=!0;return(async()=>{try{m(!0);const x=await aI();if(!v)return;c(x)}catch(x){const _=x instanceof Error?x.message:String(x);console.error("[SkillsPopoverSection] Failed to fetch skills",_)}finally{v&&m(!1)}})(),()=>{v=!1}},[]);const y=b.useCallback(async v=>{try{f(v.name);const x=await Sje(v.name);o.capture("skill_injected",{skill_name:v.name}),e(x)}catch(x){const _=x instanceof Error?x.message:String(x);console.error("[SkillsPopoverSection] Failed to get skill",_)}finally{f(null)}},[e]);return b.useEffect(()=>{if(a==="Enter"){const v=t-r;v>=0&&v<u.length&&y(u[v])}},[a,t,r,u,y]),p?l.jsx("div",{className:"px-2 py-2",children:l.jsxs("div",{className:"flex items-center gap-2 text-xs text-muted-foreground",children:[l.jsx(Pn,{size:12,className:"animate-spin"}),"Loading skills..."]})}):u.length===0&&!s?null:l.jsxs("div",{children:[l.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground border-t border-border mt-1 pt-2",children:l.jsx("span",{children:"SKILLS"})}),l.jsxs("div",{className:"flex flex-col",children:[u.map((v,x)=>{const _=r+x,S=t===_,w=d===v.name;return l.jsxs(Dt,{delayDuration:1e3,children:[l.jsx(Lt,{asChild:!0,children:l.jsxs("button",{type:"button",className:hu("flex items-center gap-2 rounded-sm px-2 max-w-[300px] py-1.5 text-xs select-none hover:bg-accent hover:text-accent-foreground",S?"bg-accent text-accent-foreground":""),onClick:()=>y(v),onMouseEnter:()=>{i&&n(_)},children:[l.jsx(ly,{size:16,className:"shrink-0 text-primary"}),l.jsx("span",{className:"flex-1 text-left truncate",children:v.name}),w&&l.jsx(Pn,{size:14,className:"text-muted-foreground shrink-0 ml-2 animate-spin","aria-label":"Loading"})]})}),l.jsx(zt,{children:v.description})]},v.name)}),u.length===0&&s&&l.jsx("div",{className:"px-2 py-2 text-xs text-muted-foreground",children:"No skills found. Create your first skill!"})]})]})}const jRe=(e,t)=>{const n=e.slice(0,t);return/(?:^\/$|\s+\/$)/.test(n)};function LIt({anchor:e,selectedServers:t,onPromptSelected:n,onSkillSelected:r,actionTrigger:i,setActionTrigger:a,value:s,caretIndex:o}){const[u,c]=b.useState(!1),[d,f]=b.useState([]),[p,m]=b.useState(null),[y,v]=b.useState(!1),[x,_]=b.useState(0),[S,w]=b.useState(!1),[T,N]=b.useState(0),[E,A]=b.useState(!1),I=!!r;b.useEffect(()=>{let z=!0;return(async()=>{try{if(!t||t.length===0)return;const{prompts:F}=await Eyt(t),D=[];for(const W of Object.keys(F))F[W].forEach(X=>{const L=`${W}/${X.name}`;D.push({...X,namespacedName:L,serverId:W})});if(!z)return;f(D)}catch(F){const D=F instanceof Error?F.message:String(F);console.error("[PromptsPopover] Failed to fetch prompts",D)}})(),()=>{z=!1}},[t]),b.useEffect(()=>{if(!I){N(0);return}let z=!0;return(async()=>{try{const F=await aI();if(!z)return;N(F.length)}catch{}})(),()=>{z=!1}},[I]);const M=d.length+T,$=b.useCallback(async(z,F)=>{try{const{serverId:D,name:W}=z,q=await wje(D,W,F),X={...z,result:q};n(X)}catch(D){const W=D instanceof Error?D.message:String(D);console.error("[PromptsPopover] Failed to get prompt result",W)}finally{m(null)}},[n]);b.useEffect(()=>{(async()=>{if(!p)return;if(p.arguments&&p.arguments.length>0){v(!0);return}await $(p,{})})()},[p,$]),b.useEffect(()=>{try{if(i===null||M===0)return;if(i==="ArrowDown")_(z=>(z+1)%M);else if(i==="ArrowUp")_(z=>(z-1+M)%M);else if(i==="Enter"){if(x===-1)return;w(!1),x<d.length&&m(d[x])}else i==="Escape"&&c(!1)}finally{a(null)}},[i,M,d.length]),b.useEffect(()=>{c(jRe(s,o)&&M>0)},[s,o,M]);const O=()=>{v(!1),m(null)},R=b.useCallback(z=>{r?.(z),c(!1)},[r]),U=b.useCallback(()=>{c(!1),A(!0)},[]);return l.jsxs("div",{className:"relative",children:[l.jsxs(qo,{open:u,onOpenChange:c,children:[l.jsx(A0t,{asChild:!0,children:l.jsx("span",{style:{position:"absolute",left:e.x,top:e.y,width:0,height:0,zIndex:1,pointerEvents:"none"}})}),l.jsxs(Ho,{side:"top",align:"start",sideOffset:8,collisionPadding:16,onMouseEnter:()=>w(!0),onMouseLeave:()=>w(!1),onOpenAutoFocus:z=>z.preventDefault(),className:"w-auto min-w-[200px] p-1 max-h-[400px] overflow-y-auto",children:[d.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"PROMPTS"}),l.jsx("div",{className:"flex flex-col",children:d.map((z,F)=>l.jsxs(Dt,{delayDuration:1e3,children:[l.jsx(Lt,{asChild:!0,children:l.jsxs("button",{type:"button",className:hu("flex items-center gap-2 rounded-sm px-2 max-w-[300px] py-1.5 text-xs select-none hover:bg-accent hover:text-accent-foreground",x===F?"bg-accent text-accent-foreground":""),onClick:()=>m(z),onMouseEnter:()=>{S&&_(F)},children:[l.jsx(P1e,{size:16,className:"shrink-0"}),l.jsx("span",{className:"flex-1 text-left truncate",children:z.namespacedName}),z.namespacedName===p?.namespacedName?l.jsx(Pn,{size:14,className:"text-muted-foreground shrink-0 ml-2 animate-spin","aria-label":"Loading"}):z.arguments&&z.arguments.length>0?l.jsx(UJe,{size:14,className:"text-muted-foreground shrink-0 ml-2","aria-label":"Requires inputs"}):null]})}),l.jsx(zt,{children:z.description})]},z.namespacedName))})]}),r&&l.jsx(DIt,{onSkillSelected:R,highlightedIndex:x,setHighlightedIndex:_,startIndex:d.length,isHovering:S,actionTrigger:i,onOpenUploadDialog:U})]})]}),l.jsx(zIt,{open:y,onOpenChange:v,promptListItem:p,onSubmit:$,onCancel:O}),l.jsx(Tje,{open:E,onOpenChange:A,onSkillCreated:z=>{aI().then(F=>N(F.length)).catch(()=>{}),R(z)}})]})}function zIt({open:e,onOpenChange:t,promptListItem:n,onSubmit:r,onCancel:i}){const[a,s]=b.useState([]),[o,u]=b.useState(!1);b.useEffect(()=>{if(!e){u(!1);return}!n?.arguments||n.arguments.length===0||s(n.arguments.map(p=>({...p,value:""})))},[e,n?.arguments]);const c=(p,m)=>{s(y=>y.map(v=>v.name===p?{...v,value:m}:v))},d=async p=>{if(p.preventDefault(),p.stopPropagation(),!n)return;const m={};a.forEach(y=>{m[y.name]=y.value}),u(!0);try{await r(n,m)}finally{e&&(u(!1),t(!1))}},f=b.useMemo(()=>a.some(m=>m.required&&!m.value.trim())||o,[a,o]);return l.jsx(si,{open:e,onOpenChange:t,children:l.jsxs(oi,{className:"sm:max-w-md",children:[l.jsx(vi,{children:l.jsx(yi,{children:`Arguments for ${n?.namespacedName}`})}),l.jsxs("form",{onSubmit:d,className:"space-y-6",children:[a.map(p=>l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("label",{htmlFor:`prompt-arg-${p.name}`,className:"text-sm font-medium",children:p.name}),p.required&&l.jsx("span",{className:"text-[11px] uppercase tracking-wide text-primary",children:"Required"})]}),l.jsx(Ct,{id:`prompt-arg-${p.name}`,value:p.value,placeholder:p.description||"Enter a value",onChange:m=>c(p.name,m.target.value),className:"h-10"}),p.description&&l.jsx("p",{className:"text-xs text-muted-foreground",children:p.description})]},p.name)),l.jsxs("div",{className:"flex justify-end space-x-2 pt-4",children:[l.jsx(Ee,{type:"button",variant:"outline",className:"px-4",onClick:()=>i(),disabled:o,children:"Cancel"}),l.jsx(Ee,{type:"submit",disabled:f,className:"px-4",children:o?l.jsxs(l.Fragment,{children:[l.jsx(Pn,{className:"h-4 w-4 animate-spin"}),"Loading..."]}):"Done"})]})]})]})})}function UIt(e){const t=e.type;return t.startsWith("image/")?XO:t==="application/pdf"||t==="text/plain"?Um:t==="text/csv"||t==="application/vnd.ms-excel"||t.includes("spreadsheet")?I1e:Fm}function FIt(e,t=20){if(e.length<=t)return e;const n=e.lastIndexOf(".");if(n===-1)return e.slice(0,t-3)+"...";const r=e.slice(n),i=e.slice(0,n),a=t-r.length-3;return a<=0?"..."+r:i.slice(0,a)+"..."+r}function BIt({attachment:e,onRemove:t}){const{file:n,previewUrl:r}=e,i=UIt(n),a=ARe(n);return l.jsxs("div",{className:"inline-flex items-center gap-2 rounded-md border border-border bg-muted/50 px-2 py-1.5 text-xs hover:bg-muted/70 transition-colors",children:[a&&r?l.jsx("img",{src:r,alt:n.name,className:"h-6 w-6 rounded object-cover flex-shrink-0"}):l.jsx(i,{className:"h-4 w-4 text-muted-foreground flex-shrink-0"}),l.jsxs("div",{className:"flex flex-col min-w-0",children:[l.jsx("span",{className:"font-medium text-foreground truncate max-w-[140px]",title:n.name,children:FIt(n.name)}),l.jsx("span",{className:"text-[10px] text-muted-foreground",children:cF(n.size)})]}),l.jsx("button",{type:"button",onClick:s=>{s.stopPropagation(),t()},className:"flex-shrink-0 rounded-sm opacity-60 hover:opacity-100 transition-opacity hover:bg-accent p-0.5 cursor-pointer","aria-label":`Remove ${n.name}`,children:l.jsx(Yn,{size:12,className:"text-muted-foreground"})})]})}const Soe=10*1024*1024;function qIt(e){if(!xIt(e)){const t=["Images (JPEG, PNG, GIF, WebP)","Documents (PDF, TXT, JSON)","Spreadsheets (CSV, Excel)"].join(", ");return{valid:!1,error:`Unsupported file type: ${e.type||"unknown"}. Allowed: ${t}`}}return e.size>Soe?{valid:!1,error:`File too large: ${cF(e.size)}. Maximum size: ${cF(Soe)}`}:{valid:!0}}function HIt(){return`file-${Date.now()}-${Math.random().toString(36).substr(2,9)}`}function VIt(e){const t={id:HIt(),file:e};return ARe(e)&&(t.previewUrl=URL.createObjectURL(e)),t}function CI(e){for(const t of e)t.previewUrl&&URL.revokeObjectURL(t.previewUrl)}function GIt(e){return new Promise((t,n)=>{const r=new FileReader;r.onload=()=>{typeof r.result=="string"?t(r.result):n(new Error("Failed to read file as data URL"))},r.onerror=()=>n(r.error),r.readAsDataURL(e)})}async function ORe(e){const t=[];for(const n of e){const r=await GIt(n.file);t.push({type:"file",mediaType:n.file.type||"application/octet-stream",filename:n.file.name,url:r})}return t}function WIt(){return["image/jpeg","image/png","image/gif","image/webp","application/pdf","text/plain","application/json","text/csv","application/vnd.ms-excel","application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"].join(",")}const KIt=["meta-llama/llama-3.3-70b-instruct","openai/gpt-oss-120b","x-ai/grok-4-fast","openai/gpt-5-nano","anthropic/claude-sonnet-4.5","anthropic/claude-haiku-4.5","openai/gpt-5.1","openai/gpt-5.1-codex","openai/gpt-5.1-codex-mini","openai/gpt-5-codex","openai/gpt-5","openai/gpt-5-mini","google/gemini-2.5-flash-preview-09-2025","moonshotai/kimi-k2-thinking","moonshotai/kimi-k2-0905","google/gemini-2.5-flash","z-ai/glm-4.6","openai/gpt-5.2-chat","x-ai/grok-code-fast-1","deepseek/deepseek-v3.2"],_r=e=>KIt.includes(e),RRe=e=>{const t=String(e);return _r(t)?!1:t.includes("gpt-5")};var cc=(e=>(e.CLAUDE_OPUS_4_1="claude-opus-4-1",e.CLAUDE_OPUS_4_0="claude-opus-4-0",e.CLAUDE_SONNET_4_5="claude-sonnet-4-5",e.CLAUDE_SONNET_4_0="claude-sonnet-4-0",e.CLAUDE_3_7_SONNET_LATEST="claude-3-7-sonnet-latest",e.CLAUDE_HAIKU_4_5="claude-haiku-4-5",e.CLAUDE_3_5_HAIKU_LATEST="claude-3-5-haiku-latest",e.GPT_4_1="gpt-4.1",e.GPT_4_1_MINI="gpt-4.1-mini",e.GPT_4_1_NANO="gpt-4.1-nano",e.GPT_4O="gpt-4o",e.GPT_4O_MINI="gpt-4o-mini",e.GPT_4_TURBO="gpt-4-turbo",e.GPT_4="gpt-4",e.GPT_5="gpt-5",e.GPT_5_MINI="gpt-5-mini",e.GPT_5_NANO="gpt-5-nano",e.GPT_5_MAIN="openai/gpt-5",e.GPT_5_PRO="gpt-5-pro",e.GPT_5_CODEX="gpt-5-codex",e.GPT_5_1="gpt-5.1",e.GPT_5_1_CODEX="gpt-5.1-codex",e.GPT_5_1_CODEX_MINI="gpt-5.1-codex-mini",e.GPT_3_5_TURBO="gpt-3.5-turbo",e.DEEPSEEK_CHAT="deepseek-chat",e.DEEPSEEK_REASONER="deepseek-reasoner",e.GEMINI_3_PRO="gemini-3-pro-preview",e.GEMINI_2_5_PRO="gemini-2.5-pro",e.GEMINI_2_5_FLASH="gemini-2.5-flash",e.GEMINI_2_5_FLASH_LITE="gemini-2.5-flash-lite",e.GEMINI_2_0_FLASH_EXP="gemini-2.0-flash-exp",e.GEMMA_3_2B="gemma-3-2b",e.GEMMA_3_9B="gemma-3-9b",e.GEMMA_3_27B="gemma-3-27b",e.GEMMA_2_2B="gemma-2-2b",e.GEMMA_2_9B="gemma-2-9b",e.GEMMA_2_27B="gemma-2-27b",e.CODE_GEMMA_2B="codegemma-2b",e.CODE_GEMMA_7B="codegemma-7b",e.MISTRAL_LARGE_LATEST="mistral-large-latest",e.MISTRAL_SMALL_LATEST="mistral-small-latest",e.CODESTRAL_LATEST="codestral-latest",e.MINISTRAL_8B_LATEST="ministral-8b-latest",e.MINISTRAL_3B_LATEST="ministral-3b-latest",e.GROK_3="grok-3",e.GROK_3_MINI="grok-3-mini",e.GROK_CODE_FAST_1="grok-code-fast-1",e.GROK_4_FAST_NON_REASONING="grok-4-fast-non-reasoning",e.GROK_4_FAST_REASONING="grok-4-fast-reasoning",e))(cc||{});const dK=[{id:"claude-opus-4-1",name:"Claude Opus 4.1",provider:"anthropic",contextLength:2e5},{id:"claude-opus-4-0",name:"Claude Opus 4",provider:"anthropic",contextLength:2e5},{id:"claude-sonnet-4-5",name:"Claude Sonnet 4.5",provider:"anthropic",contextLength:2e5},{id:"claude-sonnet-4-0",name:"Claude Sonnet 4",provider:"anthropic",contextLength:2e5},{id:"claude-haiku-4-5",name:"Claude Haiku 4.5",provider:"anthropic",contextLength:2e5},{id:"claude-3-7-sonnet-latest",name:"Claude Sonnet 3.7",provider:"anthropic",contextLength:2e5},{id:"claude-3-5-haiku-latest",name:"Claude Haiku 3.5",provider:"anthropic",contextLength:2e5},{id:"gpt-5.1",name:"GPT-5.1",provider:"openai",contextLength:4e5},{id:"gpt-5.1-codex",name:"GPT-5.1 Codex",provider:"openai",contextLength:4e5},{id:"gpt-5.1-codex-mini",name:"GPT-5.1 Codex Mini",provider:"openai",contextLength:2e5},{id:"openai/gpt-5.1",name:"GPT-5.1 (Free)",provider:"openai",contextLength:4e5},{id:"openai/gpt-5.1-codex",name:"GPT-5.1 Codex (Free)",provider:"openai",contextLength:4e5},{id:"openai/gpt-5.1-codex-mini",name:"GPT-5.1 Codex Mini (Free)",provider:"openai",contextLength:2e5},{id:"gpt-5",name:"GPT-5",provider:"openai",contextLength:4e5},{id:"gpt-5-mini",name:"GPT-5 Mini",provider:"openai",contextLength:2e5},{id:"gpt-5-nano",name:"GPT-5 Nano",provider:"openai",contextLength:128e3},{id:"gpt-5-pro",name:"GPT-5 Pro",provider:"openai",contextLength:4e5},{id:"gpt-5-codex",name:"GPT-5 Codex",provider:"openai",contextLength:4e5},{id:"gpt-4.1",name:"GPT-4.1",provider:"openai",contextLength:1047576},{id:"gpt-4.1-mini",name:"GPT-4.1 Mini",provider:"openai",contextLength:1047576},{id:"gpt-4.1-nano",name:"GPT-4.1 Nano",provider:"openai",contextLength:1047576},{id:"gpt-4o",name:"GPT-4o",provider:"openai",contextLength:128e3},{id:"gpt-4o-mini",name:"GPT-4o Mini",provider:"openai",contextLength:128e3},{id:"deepseek-chat",name:"DeepSeek Chat",provider:"deepseek",contextLength:128e3},{id:"deepseek-reasoner",name:"DeepSeek Reasoner",provider:"deepseek",contextLength:128e3},{id:"gemini-3-pro-preview",name:"Gemini 3 Pro (Preview)",provider:"google",contextLength:1e6},{id:"gemini-2.5-pro",name:"Gemini 2.5 Pro",provider:"google",contextLength:2e6},{id:"gemini-2.5-flash",name:"Gemini 2.5 Flash",provider:"google",contextLength:1e6},{id:"gemini-2.0-flash-exp",name:"Gemini 2.0 Flash Experimental",provider:"google",contextLength:1048576},{id:"meta-llama/llama-3.3-70b-instruct",name:"Llama 3.3 70B (Free)",provider:"meta",contextLength:128e3},{id:"openai/gpt-oss-120b",name:"GPT-OSS 120B (Free)",provider:"openai",contextLength:131072},{id:"x-ai/grok-4-fast",name:"Grok 4 Fast (Free)",provider:"xai",contextLength:2e6},{id:"openai/gpt-5-nano",name:"GPT-5 Nano (Free)",provider:"openai",contextLength:16e3},{id:"anthropic/claude-sonnet-4.5",name:"Claude Sonnet 4.5 (Free)",provider:"anthropic",contextLength:1e6},{id:"anthropic/claude-haiku-4.5",name:"Claude Haiku 4.5 (Free)",provider:"anthropic",contextLength:2e5},{id:"openai/gpt-5-codex",name:"GPT-5 Codex (Free)",provider:"openai",contextLength:4e5},{id:"openai/gpt-5",name:"GPT-5 (Free)",provider:"openai",contextLength:4e5},{id:"openai/gpt-5-mini",name:"GPT-5 Mini (Free)",provider:"openai",contextLength:128e3},{id:"google/gemini-2.5-flash-preview-09-2025",name:"Gemini 2.5 Flash Preview (Free)",provider:"google",contextLength:1048576},{id:"moonshotai/kimi-k2-thinking",name:"Kimi K2 Thinking (Free)",provider:"moonshotai",contextLength:262144},{id:"moonshotai/kimi-k2-0905",name:"Kimi K2 (Free)",provider:"moonshotai",contextLength:262144},{id:"google/gemini-2.5-flash",name:"Gemini 2.5 Flash (Free)",provider:"google",contextLength:1048576},{id:"z-ai/glm-4.6",name:"GLM 4.6 (Free)",provider:"z-ai",contextLength:2e5},{id:"openai/gpt-5.2-chat",name:"GPT-5.2 Chat (Free)",provider:"openai",contextLength:4e5},{id:"x-ai/grok-code-fast-1",name:"Grok Code Fast 1 (Free)",provider:"xai",contextLength:256e3},{id:"deepseek/deepseek-v3.2",name:"DeepSeek V3.2 (Free)",provider:"deepseek",contextLength:128e3},{id:"mistral-large-latest",name:"Mistral Large",provider:"mistral",contextLength:131072},{id:"mistral-small-latest",name:"Mistral Small",provider:"mistral",contextLength:128e3},{id:"codestral-latest",name:"Codestral",provider:"mistral",contextLength:256e3},{id:"ministral-8b-latest",name:"Ministral 8B",provider:"mistral",contextLength:128e3},{id:"ministral-3b-latest",name:"Ministral 3B",provider:"mistral",contextLength:128e3},{id:"grok-3",name:"Grok 3",provider:"xai",contextLength:131072},{id:"grok-3-mini",name:"Grok 3 Mini",provider:"xai",contextLength:131072},{id:"grok-code-fast-1",name:"Grok Code Fast 1",provider:"xai",contextLength:256e3},{id:"grok-4-fast-non-reasoning",name:"Grok 4 Fast Non-Reasoning",provider:"xai",contextLength:2e6},{id:"grok-4-fast-reasoning",name:"Grok 4 Fast Reasoning",provider:"xai",contextLength:2e6},{id:"azure/gpt-5.1",name:"GPT-5.1 (Azure)",provider:"azure",contextLength:4e5},{id:"azure/gpt-5.1-codex",name:"GPT-5.1 Codex (Azure)",provider:"azure",contextLength:4e5},{id:"azure/gpt-5.1-codex-mini",name:"GPT-5.1 Codex Mini (Azure)",provider:"azure",contextLength:4e5}],ZIt=e=>dK.find(t=>t.id===e),koe={serverUrl:"",tokens:null,isAuthenticating:!1,error:null,statusMessage:null};var PRe="vercel.ai.error",YIt=Symbol.for(PRe),Eoe,Toe,Pc=class $Re extends(Toe=Error,Eoe=YIt,Toe){constructor({name:t,message:n,cause:r}){super(n),this[Eoe]=!0,this.name=t,this.cause=r}static isInstance(t){return $Re.hasMarker(t,PRe)}static hasMarker(t,n){const r=Symbol.for(n);return t!=null&&typeof t=="object"&&r in t&&typeof t[r]=="boolean"&&t[r]===!0}};function MRe(e){return e==null?"unknown error":typeof e=="string"?e:e instanceof Error?e.message:JSON.stringify(e)}var DRe="AI_InvalidArgumentError",LRe=`vercel.ai.error.${DRe}`,XIt=Symbol.for(LRe),Noe,Coe,JIt=class extends(Coe=Pc,Noe=XIt,Coe){constructor({message:e,cause:t,argument:n}){super({name:DRe,message:e,cause:t}),this[Noe]=!0,this.argument=n}static isInstance(e){return Pc.hasMarker(e,LRe)}},zRe="AI_JSONParseError",URe=`vercel.ai.error.${zRe}`,QIt=Symbol.for(URe),Aoe,Ioe,joe=class extends(Ioe=Pc,Aoe=QIt,Ioe){constructor({text:e,cause:t}){super({name:zRe,message:`JSON parsing failed: Text: ${e}.
|
|
1701
1701
|
Error message: ${MRe(t)}`,cause:t}),this[Aoe]=!0,this.text=e}static isInstance(e){return Pc.hasMarker(e,URe)}},FRe="AI_TypeValidationError",BRe=`vercel.ai.error.${FRe}`,ejt=Symbol.for(BRe),Ooe,Roe,Ey=class fF extends(Roe=Pc,Ooe=ejt,Roe){constructor({value:t,cause:n,context:r}){let i="Type validation failed";if(r?.field&&(i+=` for ${r.field}`),r?.entityName||r?.entityId){i+=" (";const a=[];r.entityName&&a.push(r.entityName),r.entityId&&a.push(`id: "${r.entityId}"`),i+=a.join(", "),i+=")"}super({name:FRe,message:`${i}: Value: ${JSON.stringify(t)}.
|
|
1702
1702
|
Error message: ${MRe(n)}`,cause:n}),this[Ooe]=!0,this.value=t,this.context=r}static isInstance(t){return Pc.hasMarker(t,BRe)}static wrap({value:t,cause:n,context:r}){var i,a,s;return fF.isInstance(n)&&n.value===t&&((i=n.context)==null?void 0:i.field)===r?.field&&((a=n.context)==null?void 0:a.entityName)===r?.entityName&&((s=n.context)==null?void 0:s.entityId)===r?.entityId?n:new fF({value:t,cause:n,context:r})}};class Poe extends Error{constructor(t,n){super(t),this.name="ParseError",this.type=n.type,this.field=n.field,this.value=n.value,this.line=n.line}}function iD(e){}function tjt(e){if(typeof e=="function")throw new TypeError("`callbacks` must be an object, got a function instead. Did you mean `{onEvent: fn}`?");const{onEvent:t=iD,onError:n=iD,onRetry:r=iD,onComment:i}=e;let a="",s=!0,o,u="",c="";function d(v){const x=s?v.replace(/^\xEF\xBB\xBF/,""):v,[_,S]=njt(`${a}${x}`);for(const w of _)f(w);a=S,s=!1}function f(v){if(v===""){m();return}if(v.startsWith(":")){i&&i(v.slice(v.startsWith(": ")?2:1));return}const x=v.indexOf(":");if(x!==-1){const _=v.slice(0,x),S=v[x+1]===" "?2:1,w=v.slice(x+S);p(_,w,v);return}p(v,"",v)}function p(v,x,_){switch(v){case"event":c=x;break;case"data":u=`${u}${x}
|
|
@@ -1766,7 +1766,7 @@ ${o.content}
|
|
|
1766
1766
|
});
|
|
1767
1767
|
<\/script>
|
|
1768
1768
|
</body>
|
|
1769
|
-
</html>`),A.close(),f.current=A.getElementById("middle"),m(!0)};if(N.contentDocument?.readyState==="complete")E();else return N.addEventListener("load",E),()=>N.removeEventListener("load",E)},[_,S,p]),b.useEffect(()=>{!y||!t||x.current||(x.current=!0,console.log("[ChatGPTSandboxedIframe] Sending widget URL to proxy:",t),d.current?.contentWindow?.postMessage({type:"openai:load-widget",url:t,sandbox:n},"*"),setTimeout(()=>r?.(),100))},[y,t,n,r]),b.useEffect(()=>{x.current=!1,v(!1),m(!1)},[t]),l.jsx("iframe",{ref:d,src:"about:blank",sandbox:"allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox allow-forms",allow:"local-network-access *; microphone *; midi *",title:u,className:s,style:o})});function hRt({className:e,...t}){return l.jsx(QKe,{"data-slot":"radio-group",className:Ie("grid gap-3",e),...t})}function mRt({className:e,...t}){return l.jsx(eZe,{"data-slot":"radio-group-item",className:Ie("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:l.jsx(tZe,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:l.jsx(zm,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function gF(e,t){const n=typeof e=="number"?e:Number(e);if(!Number.isFinite(n))return String(e??"");const r=(t||"USD").toUpperCase();try{return new Intl.NumberFormat(void 0,{style:"currency",currency:r}).format(n/100)}catch{return`${n/100} ${r}`}}const am={success:{number:"4242424242424242",behavior:{behavior:"success"}},decline_generic:{number:"4000000000000002",behavior:{behavior:"decline",errorCode:"payment_declined",errorMessage:"Your card was declined."}},decline_insufficient:{number:"4000000000009995",behavior:{behavior:"insufficient_funds",errorCode:"payment_declined",errorMessage:"Insufficient funds."}},decline_expired:{number:"4000000000000069",behavior:{behavior:"expired",errorCode:"payment_declined",errorMessage:"Card has expired."}},requires_3ds:{number:"4000000000003155",behavior:{behavior:"3ds",errorCode:"requires_3ds",errorMessage:"3D Secure required."}},processing_error:{number:"4000000000000119",behavior:{behavior:"processing_error",errorMessage:"Processing error occurred."}}};function gRt(e){const t=e.replace(/\s/g,"");for(const n of Object.values(am))if(n.number===t)return n.behavior;return null}const vRt={none:{label:"Normal",description:"Use card behavior"},network_timeout:{label:"Timeout",description:"10s network timeout"},server_error:{label:"500 Error",description:"Server error"},slow_response:{label:"Slow",description:"5s delay"}},Yoe=[{key:"success",label:"Success",number:am.success.number,icon:"✓"},{key:"decline",label:"Decline",number:am.decline_generic.number,icon:"✗"},{key:"insufficient",label:"Insufficient",number:am.decline_insufficient.number,icon:"$"},{key:"3ds",label:"",number:am.requires_3ds.number,icon:"3DS"},{key:"expired",label:"Expired",number:am.decline_expired.number,icon:"⏱"},{key:"error",label:"Error",number:am.processing_error.number,icon:"⚠"}];function Xoe(e){return e.replace(/\D/g,"").slice(0,16).replace(/(\d{4})(?=\d)/g,"$1 ")}function yRt(e){const t=e.replace(/\D/g,"").slice(0,4);return t.length>=2?`${t.slice(0,2)}/${t.slice(2)}`:t}function xRt(e,t){try{const n=new Date(e),r=new Date(t),i={month:"short",day:"numeric"},a=n.toLocaleDateString("en-US",i),s=r.toLocaleDateString("en-US",i);return a===s?a:`${a} - ${s}`}catch{return""}}function bRt({onClick:e,disabled:t}){return l.jsxs("button",{onClick:e,disabled:t,className:"w-full h-11 bg-black hover:bg-black/90 disabled:bg-black/50 text-white rounded-full flex items-center justify-center gap-1.5 transition-colors",children:[l.jsx("svg",{viewBox:"0 0 24 24",className:"h-5 w-5 fill-current",children:l.jsx("path",{d:"M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09l.01-.01zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"})}),l.jsx("span",{className:"font-medium",children:"Pay"})]})}function _Rt({onClick:e,disabled:t}){return l.jsxs("button",{onClick:e,disabled:t,className:"w-full h-11 bg-white hover:bg-gray-50 disabled:bg-gray-100 border border-gray-300 rounded-full flex items-center justify-center gap-1.5 transition-colors",children:[l.jsxs("svg",{viewBox:"0 0 24 24",className:"h-5 w-5",children:[l.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"}),l.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),l.jsx("path",{fill:"#FBBC05",d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),l.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]}),l.jsx("span",{className:"font-medium text-gray-700",children:"Pay"})]})}function wRt({option:e,selected:t,onSelect:n,currency:r}){const i=e.type==="shipping";return l.jsx("div",{onClick:n,className:`rounded-xl border-2 p-4 cursor-pointer transition-all ${t?"border-black bg-gray-50":"border-gray-200 hover:border-gray-300"}`,children:l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsx("div",{className:`rounded-full p-2 ${t?"bg-black text-white":"bg-gray-100"}`,children:i?l.jsx(net,{className:"h-4 w-4"}):l.jsx(yet,{className:"h-4 w-4"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"font-medium",children:e.title}),l.jsx("span",{className:"font-medium tabular-nums",children:e.total===0?"FREE":gF(e.total,r)})]}),e.subtitle&&l.jsx("div",{className:"text-sm text-gray-500 mt-0.5",children:e.subtitle}),i&&"carrier_info"in e&&l.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:[l.jsx("span",{children:e.carrier_info}),e.earliest_delivery_time&&e.latest_delivery_time&&l.jsxs("span",{className:"ml-2",children:["Est."," ",xRt(e.earliest_delivery_time,e.latest_delivery_time)]})]})]}),l.jsx(mRt,{value:e.id,checked:t,className:"mt-1"})]})})}function SRt({open:e,onOpenChange:t,checkoutSession:n,checkoutCallId:r,onRespond:i,serverInfo:a,onCallTool:s}){const[o,u]=b.useState("payment"),[c,d]=b.useState(""),[f,p]=b.useState(""),[m,y]=b.useState(""),[v,x]=b.useState(""),[_,S]=b.useState(""),[w,T]=b.useState({}),[N,E]=b.useState(null),[A,I]=b.useState(null),[M,$]=b.useState(null),[O,R]=b.useState(n),[U,z]=b.useState(null),[F,D]=b.useState(!1),[W,q]=b.useState(!1),[X,L]=b.useState("none"),[Y,G]=b.useState(!1),[P,V]=b.useState(null);b.useEffect(()=>{if(n){R(n);const ce=n.fulfillment_options;n.fulfillment_option_id?z(n.fulfillment_option_id):ce?.length===1?z(ce[0].id):z(null)}},[n]);const K=b.useCallback(()=>{u("payment"),d(""),p(""),y(""),x(""),S(""),T({}),E(null),I(null),$(null),z(null),D(!1),q(!1),L("none"),V(null),G(!1)},[]),Q=b.useCallback(async()=>{if(!(!O||r==null))if(q(!0),E(null),s)try{const Te=await s("cancel_checkout",{checkout_session_id:O.id});if(Te?.isError||Te?.error){const we=typeof Te.error=="string"?Te.error:"Failed to cancel checkout";E(we),q(!1);return}i({error:"Checkout canceled"}),K(),t(!1)}catch(ce){const Te=ce instanceof Error?ce.message:"Cancel failed";E(Te),q(!1)}else i({error:"Checkout canceled"}),K(),t(!1)},[O,r,s,i,K,t]),oe=b.useCallback(async ce=>{if(!O||!s)return!1;D(!0),E(null);try{const we=await s("update_checkout",{checkout_session_id:O.id,...ce});if(we?.isError||we?.error){const Ue=typeof we.error=="string"?we.error:"Failed to update checkout";return E(Ue),D(!1),!1}const Oe=we?.structuredContent?.checkout_session||we?.checkout_session;return Oe&&R(Oe),D(!1),!0}catch(Te){const we=Te instanceof Error?Te.message:"Update failed";return E(we),D(!1),!1}},[O,s]);b.useEffect(()=>{O?.id&&(K(),z(O.fulfillment_option_id??null))},[O?.id,K]);const re=b.useCallback(ce=>{ce||(r!=null&&(o==="payment"||o==="card_entry"||o==="fulfillment")&&i({error:"Checkout canceled"}),K()),t(ce)},[r,o,i,t,K]),ee=b.useMemo(()=>{if(!O)return!1;const ce=O.fulfillment_options;return!ce||ce.length===0||ce.length===1&&O.fulfillment_option_id?!1:ce.length>1&&!U},[O,U]),le=b.useMemo(()=>{if(!O)return null;const ce=[...O.totals||[]];if(U&&O.fulfillment_options){const Te=O.fulfillment_options.find(we=>we.id===U);if(Te){const we=ce.findIndex(Ue=>Ue.type==="fulfillment");we>=0&&(ce[we]={...ce[we],amount:Te.total});const Oe=ce.findIndex(Ue=>Ue.type==="total");if(Oe>=0){const Ue=ce.filter(be=>be.type!=="total"&&be.type!=="items_discount"&&be.type!=="discount").reduce((be,je)=>be+je.amount,0),Me=ce.filter(be=>be.type==="items_discount"||be.type==="discount").reduce((be,je)=>be+je.amount,0);ce[Oe]={...ce[Oe],amount:Ue-Me}}}}return ce},[O,U]),te=b.useMemo(()=>le?.find(ce=>ce.type==="total")?.amount??0,[le]),Z=b.useCallback(async()=>{if(!U){E("Please select a shipping method");return}E(null),!(s&&O&&!await oe({fulfillment_option_id:U}))&&u("payment")},[U,s,O,oe]),ne=b.useCallback(ce=>{d(Xoe(ce)),p("12/29"),y("123"),v||x("Test User")},[v]),J=b.useCallback(()=>{const ce=c.replace(/\s/g,"");if(ce.length!==16){E("Please enter a valid 16-digit card number");return}if(f.length!==5){E("Please enter a valid expiry date (MM/YY)");return}if(m.length<3){E("Please enter a valid CVC");return}if(!v.trim()){E("Please enter the cardholder name");return}let Te="Card";ce.startsWith("4")?Te="Visa":ce.startsWith("5")?Te="Mastercard":ce.startsWith("3")&&(Te="Amex"),V({last4:ce.slice(-4),brand:Te}),E(null),u("payment")},[c,f,m,v]),se=b.useCallback(async()=>{if(!O||r==null)return;if(ee&&!U){u("fulfillment");return}if(!P){u("card_entry");return}const ce=c.replace(/\s/g,"");if(E(null),I(null),u("processing"),X!=="none"){if(X==="network_timeout"){await new Promise(Xe=>setTimeout(Xe,1e4)),E("Network timeout: Request timed out after 10 seconds"),u("error");return}if(X==="server_error"){await new Promise(Xe=>setTimeout(Xe,500)),E("Server error (500): Internal server error occurred"),u("error");return}X==="slow_response"&&await new Promise(Xe=>setTimeout(Xe,5e3))}const Te=`tok_${Date.now()}_${ce.slice(-4)}`,we=O.payment_provider?.provider||"stripe",Oe={name:v.trim(),email:_.trim()||void 0},Ue=w.line1&&w.city&&w.postal_code&&w.country,Me={token:Te,provider:we,billing_address:Ue?w:void 0},be=gRt(ce);if(await new Promise(Xe=>setTimeout(Xe,1500)),(be?.behavior==="decline"||be?.behavior==="insufficient_funds"||be?.behavior==="expired"||be?.behavior==="processing_error"||be?.behavior==="3ds")&&be){const Xe=be.errorCode??null,ue=be.errorMessage??"Payment failed.";I(Xe),E(ue),u("error");return}if(s)try{const ue=await s("complete_checkout",{checkout_session_id:O.id,buyer:Oe,payment_data:Me,fulfillment_option_id:U});if(ue?.isError||ue?.error){const xe=typeof ue.error=="string"?ue.error:"Payment processing failed";E(xe),u("error");return}const fe=ue?.structuredContent;if(fe?.checkout_session&&fe?.order){$(fe),u("success");return}if(ue?.checkout_session&&ue?.order){$(ue),u("success");return}$({checkout_session:{...O,status:"completed",buyer:Oe,fulfillment_option_id:U??void 0},order:{id:`order_${Date.now()}`,checkout_session_id:O.id,permalink_url:""}}),u("success")}catch(Xe){const ue=Xe instanceof Error?Xe.message:"Payment failed";E(ue),u("error")}else $({checkout_session:{...O,status:"completed",buyer:Oe,fulfillment_option_id:U??void 0},order:{id:`order_${Date.now()}`,checkout_session_id:O.id,permalink_url:""}}),u("success")},[O,r,c,v,_,w,s,U,X,P,ee]),ie=b.useCallback(()=>{M&&i({result:M}),K(),t(!1)},[M,i,K,t]),he=b.useCallback(()=>{E(null),I(null),u("payment")},[]),ye=O?.links?.find(ce=>ce.type==="terms_of_service"),Ne=O?.links?.find(ce=>ce.type==="privacy_policy");return l.jsx(si,{open:e,onOpenChange:re,children:l.jsxs(oi,{className:"sm:max-w-[400px] p-0 gap-0 overflow-hidden rounded-2xl",children:[o==="payment"&&O&&l.jsxs("div",{className:"flex flex-col",children:[l.jsx("div",{className:"flex items-center gap-3 p-6 pb-4",children:l.jsx("span",{className:"text-xl font-semibold",children:"Payment"})}),l.jsx("div",{className:"px-6 pb-4",children:l.jsxs("button",{onClick:()=>u("card_entry"),className:"w-full flex items-center justify-between p-4 rounded-xl border border-gray-200 hover:border-gray-300 transition-colors",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"w-10 h-6 bg-gradient-to-r from-blue-600 to-blue-700 rounded flex items-center justify-center",children:l.jsx("span",{className:"text-white text-xs font-bold",children:P?.brand==="Visa"?"VISA":P?.brand==="Mastercard"?"MC":"💳"})}),P?l.jsxs("span",{className:"text-gray-900",children:[P.brand," ****",P.last4]}):l.jsx("span",{className:"text-gray-500",children:"Add payment method"})]}),l.jsx(wr,{className:"h-5 w-5 text-gray-400"})]})}),l.jsx("div",{className:"px-6 pb-6",children:l.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-gray-100",children:[l.jsx("span",{className:"text-gray-500",children:"Total"}),l.jsx("span",{className:"text-xl font-semibold tabular-nums",children:gF(te,O.currency)})]})}),l.jsx("div",{className:"px-6 pb-4",children:l.jsx(Ee,{onClick:se,disabled:!P||W||F,className:"w-full h-12 rounded-full bg-black hover:bg-gray-800 text-white font-medium text-base",children:W?l.jsxs(l.Fragment,{children:[l.jsx(Pn,{className:"h-4 w-4 animate-spin mr-2"}),"Canceling..."]}):F?l.jsxs(l.Fragment,{children:[l.jsx(Pn,{className:"h-4 w-4 animate-spin mr-2"}),"Updating..."]}):"Pay"})}),l.jsxs("div",{className:"px-6 pb-4 space-y-2",children:[l.jsx(bRt,{onClick:se,disabled:!P||W||F}),l.jsx(_Rt,{onClick:se,disabled:!P||W||F}),l.jsx("button",{onClick:()=>u("card_entry"),className:"w-full h-11 border border-gray-200 hover:border-gray-300 rounded-full text-gray-700 font-medium transition-colors",children:"Pay with card"})]}),l.jsx("div",{className:"px-6 pb-2",children:l.jsxs("button",{onClick:()=>G(!Y),className:"flex items-center gap-1 text-xs text-gray-400 hover:text-gray-600 transition-colors",children:[Y?l.jsx(Ex,{className:"h-3 w-3"}):l.jsx(Wr,{className:"h-3 w-3"}),"Dev Tools"]})}),Y&&l.jsx("div",{className:"px-6 pb-4 space-y-3",children:l.jsxs("div",{className:"rounded-lg bg-gray-50 p-3 space-y-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-xs font-medium text-gray-600",children:"Quick fill test card:"}),l.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Yoe.map(ce=>l.jsxs("button",{onClick:()=>{ne(ce.number);let Te="Card";ce.number.startsWith("4")?Te="Visa":ce.number.startsWith("5")&&(Te="Mastercard"),V({last4:ce.number.slice(-4),brand:Te})},className:`px-2 py-1.5 text-xs rounded-md border transition-colors ${P?.last4===ce.number.slice(-4)?"bg-black text-white border-black":"bg-white border-gray-200 hover:border-gray-300"}`,children:[l.jsx("span",{className:"mr-1",children:ce.icon}),ce.label]},ce.key))})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-xs font-medium text-gray-600",children:"Simulate error:"}),l.jsx("select",{value:X,onChange:ce=>L(ce.target.value),className:"w-full text-xs px-3 py-2 rounded-md border border-gray-200 bg-white",children:Object.entries(vRt).map(([ce,{label:Te,description:we}])=>l.jsxs("option",{value:ce,children:[Te," - ",we]},ce))})]}),l.jsx("button",{onClick:Q,disabled:W,className:"w-full text-xs py-2 text-red-600 hover:text-red-700 border border-red-200 rounded-md hover:bg-red-50 transition-colors",children:W?"Canceling...":"Cancel Checkout"})]})}),N&&l.jsx("div",{className:"px-6 pb-4",children:l.jsxs("div",{className:"rounded-lg bg-red-50 border border-red-100 px-4 py-3 text-sm text-red-600 flex items-center gap-2",children:[l.jsx(Gs,{className:"h-4 w-4 flex-shrink-0"}),N]})}),l.jsxs("div",{className:"px-6 py-4 bg-gray-50 text-center space-y-2",children:[l.jsxs("p",{className:"text-xs text-gray-500",children:["By clicking Pay, you agree to the"," ",ye?l.jsx("a",{href:ye.url,target:"_blank",rel:"noreferrer",className:"underline",children:"Terms"}):l.jsx("span",{className:"underline",children:"Terms"})," ","and"," ",Ne?l.jsx("a",{href:Ne.url,target:"_blank",rel:"noreferrer",className:"underline",children:"Privacy Policy"}):l.jsx("span",{className:"underline",children:"Privacy Policy"})]}),l.jsx("p",{className:"text-xs text-gray-400",children:"OpenAI does not process your order, collect payment, or handle fulfillment."})]})]}),o==="card_entry"&&O&&l.jsxs("div",{className:"flex flex-col",children:[l.jsx("div",{className:"flex items-center justify-between p-6 pb-4",children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("button",{onClick:()=>u("payment"),className:"p-1 -ml-1 rounded-full hover:bg-gray-100 transition-colors",children:l.jsx(wr,{className:"h-5 w-5 text-gray-900 rotate-180"})}),l.jsx("span",{className:"text-lg font-semibold",children:"Add payment method"})]})}),l.jsxs("div",{className:"px-6 pb-6 space-y-5",children:[l.jsxs("div",{className:"border border-gray-200 rounded-xl overflow-hidden",children:[l.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-gray-200",children:[l.jsx(eJe,{className:"h-5 w-5 text-gray-600"}),l.jsx("span",{className:"font-medium text-gray-900",children:"Card"})]}),l.jsxs("div",{className:"bg-gray-50/50",children:[l.jsxs("div",{className:"relative border-b border-gray-200",children:[l.jsx(Ct,{id:"cardNumber",placeholder:"Card number",value:c,onChange:ce=>d(Xoe(ce.target.value)),className:"h-12 pr-36 border-0 rounded-none bg-transparent font-mono text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"cc-number"}),l.jsxs("div",{className:"absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-1",children:[l.jsx("img",{src:"https://js.stripe.com/v3/fingerprinted/img/visa-729c05c240c4bdb47b03ac81d9945bfe.svg",alt:"Visa",className:"h-6"}),l.jsx("img",{src:"https://js.stripe.com/v3/fingerprinted/img/mastercard-4d8844094130711885b5e41b28c9848f.svg",alt:"Mastercard",className:"h-6"}),l.jsx("img",{src:"https://js.stripe.com/v3/fingerprinted/img/amex-a49b82f46c5cd6a96a6e418a6ca1717c.svg",alt:"Amex",className:"h-6"}),l.jsx("img",{src:"https://js.stripe.com/v3/fingerprinted/img/discover-ac52cd46f89fa40a29a0bfb954e33173.svg",alt:"Discover",className:"h-6"})]})]}),l.jsxs("div",{className:"flex",children:[l.jsx("div",{className:"flex-1 border-r border-gray-200",children:l.jsx(Ct,{id:"expiry",placeholder:"Expiration date",value:f,onChange:ce=>p(yRt(ce.target.value)),className:"h-12 border-0 rounded-none bg-transparent font-mono text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"cc-exp"})}),l.jsxs("div",{className:"flex-1 relative",children:[l.jsx(Ct,{id:"cvc",placeholder:"Security code",value:m,onChange:ce=>y(ce.target.value.replace(/\D/g,"").slice(0,4)),className:"h-12 pr-12 border-0 rounded-none bg-transparent font-mono text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"cc-csc"}),l.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:l.jsxs("svg",{viewBox:"0 0 32 21",className:"h-5 w-8 text-gray-400",children:[l.jsx("rect",{x:"0",y:"0",width:"32",height:"21",rx:"3",fill:"none",stroke:"currentColor",strokeWidth:"2"}),l.jsx("rect",{x:"20",y:"4",width:"8",height:"5",rx:"1",fill:"currentColor",opacity:"0.6"}),l.jsx("text",{x:"21",y:"17",fontSize:"7",fill:"currentColor",fontFamily:"monospace",children:"123"})]})})]})]})]})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"font-medium text-gray-900",children:"Billing address"}),l.jsxs("div",{className:"border border-gray-200 rounded-xl overflow-hidden",children:[l.jsxs("div",{className:"relative border-b border-gray-200",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"Full name"}),l.jsx(Ct,{id:"cardholderName",placeholder:"",value:v,onChange:ce=>x(ce.target.value),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"cc-name"})]}),l.jsxs("div",{className:"relative border-b border-gray-200",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"Address line 1"}),l.jsx(Ct,{placeholder:"",value:w.line1||"",onChange:ce=>T(Te=>({...Te,line1:ce.target.value})),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"address-line1"})]}),l.jsxs("div",{className:"relative border-b border-gray-200",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"Address line 2"}),l.jsx(Ct,{placeholder:"",value:w.line2||"",onChange:ce=>T(Te=>({...Te,line2:ce.target.value})),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"address-line2"})]}),l.jsxs("div",{className:"relative border-b border-gray-200",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"City"}),l.jsx(Ct,{placeholder:"",value:w.city||"",onChange:ce=>T(Te=>({...Te,city:ce.target.value})),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"address-level2"})]}),l.jsxs("div",{className:"flex border-b border-gray-200",children:[l.jsxs("div",{className:"flex-1 relative border-r border-gray-200",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"State"}),l.jsx(Ct,{placeholder:"",value:w.state||"",onChange:ce=>T(Te=>({...Te,state:ce.target.value})),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"address-level1"})]}),l.jsxs("div",{className:"flex-1 relative",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"ZIP code"}),l.jsx(Ct,{placeholder:"",value:w.postal_code||"",onChange:ce=>T(Te=>({...Te,postal_code:ce.target.value})),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"postal-code"})]})]}),l.jsxs("div",{className:"relative",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"Phone number"}),l.jsxs("div",{className:"flex items-center h-14 pt-3",children:[l.jsxs("div",{className:"flex items-center gap-1 pl-3 pr-2 text-gray-600",children:[l.jsx("span",{className:"text-sm",children:"🇺🇸"}),l.jsx("span",{className:"text-sm",children:"+1"}),l.jsx(Wr,{className:"h-3 w-3"})]}),l.jsx(Ct,{placeholder:"",value:w.phone||"",onChange:ce=>T(Te=>({...Te,phone:ce.target.value})),className:"h-10 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0 pl-0",autoComplete:"tel"})]})]})]})]}),l.jsxs("div",{className:"rounded-lg bg-amber-50 border border-amber-100 p-3",children:[l.jsx("div",{className:"text-xs font-medium text-amber-700 mb-2",children:"Quick fill test card:"}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:Yoe.slice(0,4).map(ce=>l.jsxs("button",{onClick:()=>ne(ce.number),className:"px-2 py-1 text-xs rounded border border-amber-200 bg-white hover:bg-amber-50 transition-colors",children:[ce.icon," ",ce.label]},ce.key))})]}),N&&l.jsxs("div",{className:"rounded-lg bg-red-50 border border-red-100 px-4 py-3 text-sm text-red-600 flex items-center gap-2",children:[l.jsx(Gs,{className:"h-4 w-4 flex-shrink-0"}),N]}),l.jsx(Ee,{onClick:J,className:"w-full h-12 rounded-full bg-black hover:bg-gray-800 text-white font-medium",children:"Continue"})]})]}),o==="fulfillment"&&O&&l.jsxs("div",{className:"flex flex-col",children:[l.jsxs("div",{className:"flex items-center gap-3 p-6 pb-4",children:[l.jsx("button",{onClick:()=>u("payment"),className:"p-1.5 -ml-1.5 rounded-full hover:bg-gray-100 transition-colors",children:l.jsx(wr,{className:"h-5 w-5 text-gray-500 rotate-180"})}),l.jsx("span",{className:"text-xl font-semibold",children:"Shipping"})]}),l.jsxs("div",{className:"px-6 pb-6 space-y-4",children:[l.jsx(hRt,{value:U??"",onValueChange:z,className:"space-y-3",children:O.fulfillment_options?.map(ce=>l.jsx(wRt,{option:ce,selected:U===ce.id,onSelect:()=>z(ce.id),currency:O.currency},ce.id))}),N&&l.jsxs("div",{className:"rounded-lg bg-red-50 border border-red-100 px-4 py-3 text-sm text-red-600 flex items-center gap-2",children:[l.jsx(Gs,{className:"h-4 w-4 flex-shrink-0"}),N]}),l.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[l.jsx("span",{className:"text-gray-500",children:"Total"}),l.jsx("span",{className:"text-xl font-semibold tabular-nums",children:gF(te,O.currency)})]}),l.jsx(Ee,{onClick:Z,disabled:F||!U,className:"w-full h-12 rounded-full bg-black hover:bg-gray-800 text-white font-medium",children:F?l.jsxs(l.Fragment,{children:[l.jsx(Pn,{className:"h-4 w-4 animate-spin mr-2"}),"Updating..."]}):"Continue"})]})]}),o==="processing"&&l.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[l.jsx(Pn,{className:"h-10 w-10 animate-spin text-gray-400 mb-4"}),l.jsx("div",{className:"text-lg font-medium text-gray-900",children:"Processing payment..."}),l.jsx("div",{className:"text-sm text-gray-500 mt-1",children:s?"Completing checkout...":"Please wait..."})]}),o==="success"&&M&&l.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6",children:[l.jsx("div",{className:"rounded-full bg-green-100 p-4 mb-4",children:l.jsx(ko,{className:"h-10 w-10 text-green-600"})}),l.jsx("div",{className:"text-xl font-semibold text-gray-900 mb-1",children:"Payment successful"}),l.jsxs("div",{className:"text-sm text-gray-500 mb-6",children:["Order #",M.order.id.slice(-8)]}),l.jsx(Ee,{onClick:ie,className:"w-full h-12 rounded-full bg-black hover:bg-gray-800 text-white font-medium",children:"Done"})]}),o==="error"&&l.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6",children:[l.jsx("div",{className:"rounded-full bg-red-100 p-4 mb-4",children:l.jsx(Gs,{className:"h-10 w-10 text-red-600"})}),l.jsx("div",{className:"text-xl font-semibold text-gray-900 mb-1",children:"Payment failed"}),A&&l.jsx(Cn,{variant:"outline",className:"mb-2 text-xs bg-red-50 border-red-200 text-red-600",children:A}),l.jsx("div",{className:"text-sm text-gray-500 text-center mb-6",children:N||"An error occurred during payment processing."}),l.jsxs("div",{className:"flex gap-3 w-full",children:[l.jsx(Ee,{variant:"outline",onClick:()=>{i({error:N||"Payment failed"}),K(),t(!1)},className:"flex-1 h-12 rounded-full",children:"Cancel"}),l.jsx(Ee,{onClick:he,className:"flex-1 h-12 rounded-full bg-black hover:bg-gray-800 text-white",children:"Try again"})]})]})]})})}function kRt(e){if(!e||typeof e!="string")return null;const t={},n=e.matchAll(/(\w+)="([^"]+)"/g);for(const r of n){const[,i,a]=r;i==="realm"?t.realm=a:i==="error"?t.error=a:i==="error_description"&&(t.errorDescription=a)}return Object.keys(t).length>0?t:null}function Joe(e,t){const n=kRt(e);console.warn(`[OAuth Challenge] Tool "${t}" requires authentication`,n?{realm:n.realm,error:n.error,description:n.errorDescription}:{raw:e}),n?.error||n?.errorDescription?Pe.warning(`OAuth Required: ${n.errorDescription||n.error||"Authentication required"}`,{description:`Tool "${t}" needs authentication. Configure OAuth in server settings.`,duration:8e3}):Pe.warning(`OAuth Required for "${t}"`,{description:"The tool requires authentication. Configure OAuth in server settings.",duration:8e3})}function ERt(e,t,n,r,i){const a=b.useMemo(()=>e??`${t||"chatgpt-app"}-${Date.now()}`,[e,t]),s=b.useMemo(()=>i?.["openai/outputTemplate"],[i]),o=b.useMemo(()=>r&&typeof r=="object"&&r!==null&&"structuredContent"in r?r.structuredContent:null,[r]),u=b.useMemo(()=>{if(r&&typeof r=="object"&&r!==null){if("_meta"in r)return r._meta;if("meta"in r)return r.meta}return null},[r]),c=b.useMemo(()=>n??{},[n]),d=b.useMemo(()=>o??r??null,[o,r]);return{resolvedToolCallId:a,outputTemplate:s,toolResponseMetadata:u,resolvedToolInput:c,resolvedToolOutput:d}}function TRt(){const e=window.innerWidth;return e<768?"mobile":e<1024?"tablet":"desktop"}let mN=null,gN=null;const NRt={hover:!0,touch:!1},CRt={top:0,bottom:0,left:0,right:0};async function ARt(){return mN||gN||(gN=(async()=>{try{const e=await fetch("http://ip-api.com/json/?fields=status,country,regionName,city",{signal:AbortSignal.timeout(3e3)});if(!e.ok)return null;const t=await e.json();return t.status!=="success"?null:(mN={country:t.country||"",region:t.regionName||"",city:t.city||""},mN)}catch(e){return console.debug("[OpenAI SDK] IP geolocation unavailable:",e),null}})(),gN)}function IRt(e,t,n,r,i,a,s,o,u,c,d,f,p,m,y,v,x,_){const[S,w]=b.useState(null),[T,N]=b.useState(!1),[E,A]=b.useState(null),[I,M]=b.useState(!1),[$,O]=b.useState(null),[R,U]=b.useState(d),[z,F]=b.useState(!0),[D,W]=b.useState(!1),q=b.useRef(null),X=b.useRef(null);b.useEffect(()=>{X.current!==null&&X.current!==t&&(w(null),W(!1),q.current=null),X.current=t},[t]),b.useEffect(()=>{D||w(null)},[x,D]);const L=b.useRef(a);L.current=a;const Y=b.useRef(s);Y.current=s;const G=b.useRef(o);G.current=o;const P=b.useRef(y);P.current=y,b.useEffect(()=>{d!==R&&S&&(U(d),w(null))},[d,R,S]);const V=b.useMemo(()=>JSON.stringify({input:a,output:s}),[a,s]),[K,Q]=b.useState(V);return b.useEffect(()=>{const oe=setTimeout(()=>{Q(V)},300);return()=>clearTimeout(oe)},[V]),b.useEffect(()=>{if(e==="output-available"){if(q.current===null){q.current=K;return}q.current!==K&&(q.current=K,n&&r&&!v&&(W(!0),w(null)))}},[e,K,n,r,v]),b.useEffect(()=>{let oe=!1;const re=!!x&&!D,ee=!!n&&!!r,le=S&&(re&&S===x||!re&&S.includes("/api/apps/chatgpt/widget-content/"));if(e!=="output-available"||le||!re&&!ee){S&&M(!1),!re&&!n&&(w(null),O(null),M(!1)),!r&&n&&!re&&(w(null),O("Tool name is required"),M(!1));return}return(async()=>{M(!0),O(null);try{if(x&&!D){oe||(w(x),M(!1));return}if(v){oe||(O("Server offline and no cached widget HTML available"),M(!1));return}const Z=await ARt(),ne=await Yt("/api/apps/chatgpt/widget/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:i,uri:n,toolInput:L.current,toolOutput:Y.current,toolResponseMetadata:G.current,toolId:t,toolName:r,theme:u,locale:c,deviceType:f,userLocation:Z,cspMode:d,capabilities:p,safeAreaInsets:m})});if(!ne.ok)throw new Error(`Failed to store widget data: ${ne.statusText}`);if(oe)return;const J=await fetch(`/api/apps/chatgpt/widget-html/${t}`);if(J.ok){const ie=await J.json();if(ie.csp&&P.current&&P.current({mode:ie.csp.mode,connectDomains:ie.csp.connectDomains,resourceDomains:ie.csp.resourceDomains,frameDomains:ie.csp.frameDomains,headerString:ie.csp.headerString,widgetDeclared:ie.csp.widgetDeclared}),ie.closeWidget){N(!0),A("completed"),M(!1);return}F(ie.prefersBorder??!0)}const se=`/api/apps/chatgpt/widget-content/${t}?csp_mode=${d}`;if(_)try{const ie=await fetch(se);if(ie.ok){const he=await ie.text();_(t,he)}}catch(ie){console.warn("Failed to capture widget HTML for caching:",ie)}w(se)}catch(Z){if(oe)return;console.error("Error storing widget data:",Z),O(Z instanceof Error?Z.message:"Failed to prepare widget")}finally{oe||M(!1)}})(),()=>{oe=!0}},[e,t,S,n,r,i,u,c,d,f,p,m,v,x,_,D]),{widgetUrl:S,widgetClosed:T,widgetClosedReason:E,isStoringWidget:I,storeError:$,setWidgetUrl:w,setWidgetClosed:N,setWidgetClosedReason:A,prefersBorder:z}}function vK({serverId:e,toolCallId:t,toolName:n,toolState:r,toolInput:i,toolOutput:a,toolMetadata:s,onSendFollowUp:o,onCallTool:u,onWidgetStateChange:c,pipWidgetId:d,fullscreenWidgetId:f,onRequestPip:p,onExitPip:m,serverInfo:y,displayMode:v,onDisplayModeChange:x,onRequestFullscreen:_,onExitFullscreen:S,isOffline:w,cachedWidgetHtmlUrl:T,initialWidgetState:N}){const E=b.useRef(null),A=b.useRef(null),I=eo(Ve=>Ve.themeMode),$=Zt(Ve=>Ve.globals.locale)||navigator.language||"en-US",{resolvedToolCallId:O,outputTemplate:R,toolResponseMetadata:U,resolvedToolInput:z,resolvedToolOutput:F}=ERt(t,n,i,a,s),D=v!==void 0,[W,q]=b.useState("inline"),X=D?v:W,L=b.useMemo(()=>D?X==="fullscreen"&&f===O?"fullscreen":X==="pip"&&d===O?"pip":"inline":X,[X,f,D,d,O]),Y=b.useCallback(Ve=>{D?x?.(Ve):q(Ve),Ve==="fullscreen"?_?.(O):X==="fullscreen"&&S?.(O)},[D,x,O,_,S,X]),[G,P]=b.useState(null),[V,K]=b.useState(320),[Q,oe]=b.useState(!1),[re,ee]=b.useState(null),[le,te]=b.useState(!1),[Z,ne]=b.useState({}),[J,se]=b.useState(""),[ie,he]=b.useState(null),[ye,Ne]=b.useState(!1),[ce,Te]=b.useState(null),[we,Oe]=b.useState(null),[Ue,Me]=b.useState("inline"),be=b.useRef(null),[je,Xe]=b.useState(!1),ue=b.useRef(0),[fe,xe]=b.useState(!1),[Ce,He]=b.useState(!1),Ze=Zt(Ve=>Ve.isPlaygroundActive),st=Zt(Ve=>Ve.cspMode),ot=Zt(Ve=>Ve.deviceType),mt=Zt(Ve=>Ve.capabilities),Bt=Zt(Ve=>Ve.safeAreaInsets),Mt=Ze?st:"permissive",It=Ze?ot:TRt(),gn=Ze?mt:NRt,nt=Ze?Bt:CRt,yt=bs(Ve=>Ve.setWidgetCsp),ut=bs(Ve=>Ve.setWidgetHtml),vt=Ze&&It==="mobile",Wt=Ze&&(It==="mobile"||It==="tablet"),Qn=b.useCallback(Ve=>{yt(O,Ve)},[O,yt]),Gi=b.useCallback((Ve,Br)=>{ut(Ve,Br)},[ut]),Pt=L==="fullscreen",sn=L==="pip",Mn=!Pt&&!sn,{widgetUrl:ln,widgetClosed:ir,widgetClosedReason:Ga,isStoringWidget:ja,storeError:Zc,setWidgetClosed:qu,setWidgetClosedReason:Is,prefersBorder:Hu}=IRt(r,O,R,n,e,z,F,U,I,$,Mt,It,gn,nt,Qn,w,T,Gi),Ao=b.useCallback(Ve=>{const Br=Number(Ve);if(!Number.isFinite(Br)||Br<=0)return;const Un=Math.ceil(Br),Yr=Mn?Un+2:Un;if(Yr===ue.current)return;if(ue.current=Yr,K(Xr=>Xr!==Yr?Yr:Xr),Mn){const Xr=typeof G=="number"&&Number.isFinite(G)?Math.min(Yr,G):Yr;E.current?.setHeight?.(Xr)}},[Mn,G]),Ai=b.useMemo(()=>{const Ve=V>0?V:320;return typeof G=="number"&&Number.isFinite(G)?Math.min(Ve,G):Ve},[V,G]),Wa=b.useMemo(()=>Pt?"100%":L==="pip"?vt&&sn?"100%":sn?"400px":`${Ai}px`:`${Ai}px`,[Ai,L,Pt,sn,vt]),hs=b.useMemo(()=>{if(!ln||!le)return null;const Ve=new URL(ln,"http://placeholder");return Ve.searchParams.set("view_mode","modal"),Ve.searchParams.set("view_params",JSON.stringify(Z)),ie&&Ve.searchParams.set("template",ie),Ve.pathname+Ve.search},[ln,le,Z,ie]),vr=km(Ve=>Ve.addLog),Yc=bs(Ve=>Ve.setWidgetDebugInfo),Xl=bs(Ve=>Ve.setWidgetState),ht=bs(Ve=>Ve.setWidgetGlobals),Nt=bs(Ve=>Ve.addCspViolation);b.useEffect(()=>{n&&Yc(O,{toolName:n,protocol:"openai-apps",widgetState:N??null,globals:{theme:I,displayMode:L,maxHeight:G??void 0,locale:$,safeArea:{insets:nt},userAgent:{device:{type:It},capabilities:gn}}})},[O,n,Yc,I,L,G,$,It,gn,nt,N]),b.useEffect(()=>{ht(O,{theme:I,displayMode:L,maxHeight:G??void 0})},[O,I,L,G,ht]),b.useEffect(()=>{if(ue.current=0,xe(!1),He(!1),!!ln&&(K(320),L==="inline")){const Ve=typeof G=="number"&&Number.isFinite(G)?Math.min(320,G):320;E.current?.setHeight?.(Ve)}},[ln,G]),b.useEffect(()=>{!ln||L!=="inline"||!Q||E.current?.postMessage({type:"openai:requestResize"})},[ln,L,Q]),b.useEffect(()=>{L==="inline"&&(!Number.isFinite(Ai)||Ai<=0||(ue.current=Math.round(Ai),E.current?.setHeight?.(Ai)))},[Ai,L]);const Tt=b.useCallback((Ve,Br)=>{vr({widgetId:O,serverId:e,direction:"host-to-ui",protocol:"openai-apps",method:L1(Ve,"openai-apps"),message:Ve}),Br?je&&A.current?.postMessage(Ve):E.current?.postMessage(Ve)},[vr,O,e,je]),Cr=b.useCallback(Ve=>{we!=null&&(Tt({type:"openai:requestCheckout:response",callId:we,...Ve},Ue==="modal"),Oe(null),Te(null),Ne(!1))},[we,Ue,Tt]),vn=b.useCallback(Ve=>{E.current?.postMessage({type:"openai:navigate",direction:Ve,toolId:O})},[O]),yr=b.useCallback(async Ve=>{const Br=Ve.data?.type;switch(vr({widgetId:O,serverId:e,direction:"ui-to-host",protocol:"openai-apps",method:L1(Ve.data,"openai-apps"),message:Ve.data}),Br){case"openai:resize":{Ao(Ve.data.height);break}case"openai:setWidgetState":{if(Ve.data.toolId===O){const Un=Ve.data.state,Yr=Un===null?null:JSON.stringify(Un);Yr!==be.current&&(be.current=Yr,Xl(O,Un),c?.(O,Un))}break}case"openai:callTool":{const Un=Ve.data.callId,Yr=Ve.data.toolName;if(!u){Tt({type:"openai:callTool:response",callId:Un,error:"callTool is not supported in this context"});break}try{const Wi=await u(Yr,Ve.data.args||Ve.data.params||{},Ve.data._meta||{}),Vu=(Wi?._meta||Wi?.meta)?.["mcp/www_authenticate"];Vu&&typeof Vu=="string"&&Joe(Vu,Yr),Tt({type:"openai:callTool:response",callId:Un,result:Wi})}catch(Wi){Tt({type:"openai:callTool:response",callId:Un,error:Wi instanceof Error?Wi.message:"Unknown error"})}break}case"openai:sendFollowup":{if(o&&Ve.data.message){const Un=typeof Ve.data.message=="string"?Ve.data.message:Ve.data.message.prompt||JSON.stringify(Ve.data.message);o(Un)}break}case"openai:requestDisplayMode":{const Un=Ve.data.mode||"inline",Wi=window.innerWidth<768&&Un==="pip"?"fullscreen":Un;Y(Wi),Wi==="pip"?p?.(O):(Wi==="inline"||Wi==="fullscreen")&&d===O&&m?.(O),typeof Ve.data.maxHeight=="number"?P(Ve.data.maxHeight):Ve.data.maxHeight==null&&P(null),Tt({type:"openai:set_globals",globals:{displayMode:Wi}});break}case"openai:requestClose":{qu(!0),Is("closed"),d===O&&m?.(O);break}case"openai:csp-violation":{const{directive:Un,blockedUri:Yr,sourceFile:Wi,lineNumber:Xr,columnNumber:Vu,effectiveDirective:tb,timestamp:Sf}=Ve.data;Nt(O,{directive:Un,effectiveDirective:tb,blockedUri:Yr,sourceFile:Wi,lineNumber:Xr,columnNumber:Vu,timestamp:Sf||Date.now()});break}case"openai:openExternal":{if(Ve.data.href&&typeof Ve.data.href=="string"){const Un=Ve.data.href;if(Un.startsWith("http://localhost")||Un.startsWith("http://127.0.0.1"))break;window.open(Un,"_blank","noopener,noreferrer")}break}case"openai:requestCheckout":{if(typeof Ve.data.callId!="number")break;const Un=Ve.data.session&&typeof Ve.data.session=="object"?Ve.data.session:null;if(!Un)break;if(we!=null){Tt({type:"openai:requestCheckout:response",callId:Ve.data.callId,error:"Another checkout is already in progress"});break}Me("inline"),Oe(Ve.data.callId),Te(Un),Ne(!0);break}case"openai:requestModal":{se(Ve.data.title||"Modal"),ne(Ve.data.params||{}),he(Ve.data.template||null),te(!0);break}case"openai:navigationStateChanged":{Ve.data.toolId===O&&(xe(Ve.data.canGoBack??!1),He(Ve.data.canGoForward??!1));break}}},[u,o,c,O,d,p,m,vr,Tt,e,Xl,Ao,Nt,we,qu,Is]),Ka=b.useCallback(Ve=>{if(Ve.data?.type&&vr({widgetId:O,serverId:e,direction:"ui-to-host",protocol:"openai-apps",method:L1(Ve.data,"openai-apps"),message:Ve.data}),Ve.data?.type==="openai:setWidgetState"&&Ve.data.toolId===O){const Br=Ve.data.state,Un=Br===null?null:JSON.stringify(Br);Un!==be.current&&(be.current=Un,Xl(O,Br),c?.(O,Br))}if(Ve.data?.type==="openai:requestCheckout"){if(typeof Ve.data.callId!="number")return;const Br=Ve.data.session&&typeof Ve.data.session=="object"?Ve.data.session:null;if(!Br)return;if(we!=null){Tt({type:"openai:requestCheckout:response",callId:Ve.data.callId,error:"Another checkout is already in progress"},!0);return}Me("modal"),Oe(Ve.data.callId),Te(Br),Ne(!0)}if(Ve.data?.type==="openai:callTool"){const Br=Ve.data.callId,Un=Ve.data.toolName;if(!u){Tt({type:"openai:callTool:response",callId:Br,error:"callTool is not supported in this context"},!0);return}(async()=>{try{const Yr=await u(Un,Ve.data.args||Ve.data.params||{},Ve.data._meta||{}),Xr=(Yr?._meta||Yr?.meta)?.["mcp/www_authenticate"];Xr&&typeof Xr=="string"&&Joe(Xr,Un),Tt({type:"openai:callTool:response",callId:Br,result:Yr},!0)}catch(Yr){Tt({type:"openai:callTool:response",callId:Br,error:Yr instanceof Error?Yr.message:"Unknown error"},!0)}})()}},[vr,O,e,Xl,c,we,Tt,u]),ms=b.useCallback(()=>{Xe(!0);const Ve={theme:I,displayMode:"inline",maxHeight:null,locale:$,safeArea:{insets:nt},userAgent:{device:{type:It},capabilities:gn},toolInput:z,toolOutput:F};N!==void 0&&(Ve.widgetState=N),A.current?.postMessage({type:"openai:set_globals",globals:Ve})},[I,$,It,gn,nt,z,F,N]);b.useEffect(()=>{le||(Xe(!1),he(null))},[le]),b.useEffect(()=>{!D&&X==="pip"&&d!==O&&Y("inline")},[X,d,O,D,Y]),b.useEffect(()=>{if(!Q)return;const Ve={theme:I,displayMode:L,locale:$,safeArea:{insets:nt},userAgent:{device:{type:It},capabilities:gn},toolInput:z,toolOutput:F};N!==void 0&&(Ve.widgetState=N),typeof G=="number"&&Number.isFinite(G)&&(Ve.maxHeight=G),Tt({type:"openai:set_globals",globals:Ve}),le&&Tt({type:"openai:set_globals",globals:Ve},!0)},[I,G,L,$,It,gn,nt,z,F,N,Q,le,Tt]);const js=s?.["openai/toolInvocation/invoking"],Xc=s?.["openai/toolInvocation/invoked"];if(r==="output-denied")return l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Tool execution was denied."});if(r==="input-streaming"||r==="input-available")return l.jsxs("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2 flex items-center gap-2",children:[l.jsx(Pn,{className:"h-3 w-3 animate-spin"}),js||"Executing tool..."]});if(ja)return l.jsxs("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2 flex items-center gap-2",children:[l.jsx(Pn,{className:"h-3 w-3 animate-spin"}),"Loading ChatGPT App widget..."]});if(Zc)return l.jsxs("div",{className:"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",children:["Failed to load widget: ",Zc,R&&l.jsxs(l.Fragment,{children:[" ","(Template ",l.jsx("code",{children:R}),")"]})]});if(ir)return l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:Ga==="closed"?"Widget closed.":Xc||"Tool completed successfully."});if(!R&&!T)return r!=="output-available"?l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Widget UI will appear once the tool finishes executing."}):l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Unable to render ChatGPT App UI for this tool result."});if(!ln)return l.jsxs("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2 flex items-center gap-2",children:[l.jsx(Pn,{className:"h-3 w-3 animate-spin"}),"Preparing widget..."]});const ol=Pt?Wt?"absolute inset-0 z-10 w-full h-full bg-background flex flex-col":"fixed inset-0 z-40 w-full h-full bg-background flex flex-col":sn?vt?"absolute inset-0 z-10 w-full h-full bg-background flex flex-col":"fixed top-4 inset-x-0 z-40 w-full max-w-4xl mx-auto space-y-2 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 shadow-xl border border-border/60 rounded-xl p-3":"mt-3 space-y-2 relative group";return l.jsxs("div",{className:ol,children:[(Pt&&Wt||sn&&vt)&&l.jsx("button",{onClick:()=>{Y("inline"),d===O&&m?.(O)},className:"absolute left-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer","aria-label":"Close",children:l.jsx(Yn,{className:"w-5 h-5"})}),Pt&&!Wt&&l.jsxs("div",{className:"flex items-center justify-between px-4 h-14 border-b border-border/40 bg-background/95 backdrop-blur z-40 shrink-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{onClick:()=>vn("back"),disabled:!fe,className:`p-2 rounded-lg transition-colors ${fe?"hover:bg-muted text-muted-foreground hover:text-foreground cursor-pointer":"text-muted-foreground/50 cursor-not-allowed"}`,"aria-label":"Go back",children:l.jsx(Dq,{className:"w-5 h-5"})}),l.jsx("button",{onClick:()=>vn("forward"),disabled:!Ce,className:`p-2 rounded-lg transition-colors ${Ce?"hover:bg-muted text-muted-foreground hover:text-foreground cursor-pointer":"text-muted-foreground/50 cursor-not-allowed"}`,"aria-label":"Go forward",children:l.jsx(wr,{className:"w-5 h-5"})})]}),l.jsx("div",{className:"font-medium text-sm text-muted-foreground",children:n||"ChatGPT App"}),l.jsx("button",{onClick:()=>{Y("inline"),d===O&&m?.(O)},className:"p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors","aria-label":"Exit fullscreen",children:l.jsx(Yn,{className:"w-5 h-5"})})]}),sn&&!vt&&l.jsx("button",{onClick:()=>{Y("inline"),m?.(O)},className:"absolute left-2 top-2 z-10 flex h-6 w-6 items-center justify-center rounded-md bg-background/80 hover:bg-background border border-border/50 text-muted-foreground hover:text-foreground transition-colors cursor-pointer","aria-label":"Close PiP mode",title:"Close PiP mode",children:l.jsx(Yn,{className:"w-4 h-4"})}),re&&l.jsxs("div",{className:"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",children:["Failed to load widget: ",re]}),l.jsx(Zoe,{ref:E,url:ln,allowAutoResize:Mn,onMessage:yr,onReady:()=>{oe(!0),ee(null)},title:`ChatGPT App Widget: ${n||"tool"}`,className:`w-full bg-background overflow-hidden ${Pt?"flex-1 border-0 rounded-none":`rounded-md ${Hu?"border border-border/40":""}`}`,style:{height:Wa,maxHeight:L==="pip"&&!vt?"90vh":void 0}}),R&&l.jsxs("div",{className:"text-[11px] text-muted-foreground/70",children:["Template: ",l.jsx("code",{children:R})]}),l.jsx(si,{open:le,onOpenChange:te,children:l.jsxs(oi,{className:"w-fit max-w-[90vw] h-fit max-h-[70vh] flex flex-col",children:[l.jsx(vi,{children:l.jsx(yi,{children:J})}),l.jsx("div",{className:"flex-1 w-full h-full min-h-0 overflow-y-auto",children:hs&&l.jsx(Zoe,{ref:A,url:hs,onMessage:Ka,onReady:ms,title:`ChatGPT App Modal: ${J}`,className:"w-full h-full border-0 rounded-md bg-background overflow-hidden"})})]})}),l.jsx(SRt,{open:ye,onOpenChange:Ne,checkoutSession:ce,checkoutCallId:we,onRespond:Cr,serverInfo:y??{name:e},onCallTool:u})]})}const jRt=b.forwardRef(function({html:t,sandbox:n="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",csp:r,permissions:i,permissive:a,onProxyReady:s,onMessage:o,className:u,style:c,title:d="Sandboxed Content"},f){const p=b.useRef(null),[m,y]=b.useState(!1),[v]=b.useState(()=>{const w=window.location.hostname,T=window.location.port,N=window.location.protocol;let E;w==="localhost"?E="127.0.0.1":w==="127.0.0.1"?E="localhost":(console.warn("[SandboxedIframe] Cross-origin isolation not available for hostname:",w,"- falling back to same-origin sandbox"),E=w);const A=T?`:${T}`:"";return`${N}//${E}${A}/api/mcp/sandbox-proxy?v=${Date.now()}`}),x=b.useMemo(()=>{try{return new URL(v).origin}catch{return"*"}},[v]);b.useImperativeHandle(f,()=>({postMessage:w=>{p.current?.contentWindow?.postMessage(w,x)},getIframeElement:()=>p.current}),[x]);const _=b.useCallback(w=>{if(w.origin!==x&&x!=="*"||w.source!==p.current?.contentWindow)return;if(w.data?.type==="mcp-apps:csp-violation"){o(w);return}const{jsonrpc:T,method:N}=w.data||{};if(T==="2.0"){if(N==="ui/notifications/sandbox-proxy-ready"){y(!0),s?.();return}N?.startsWith("ui/notifications/sandbox-")||o(w)}},[o,s,x]);b.useEffect(()=>(window.addEventListener("message",_),()=>window.removeEventListener("message",_)),[_]);const S=b.useMemo(()=>{const w=["local-network-access *","midi *"];return i?.camera&&w.push("camera *"),i?.microphone&&w.push("microphone *"),i?.geolocation&&w.push("geolocation *"),i?.clipboardWrite&&w.push("clipboard-write *"),w.join("; ")},[i]);return b.useEffect(()=>{!m||!t||p.current?.contentWindow?.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-resource-ready",params:{html:t,sandbox:n,csp:r,permissions:i,permissive:a}},x)},[m,t,n,r,i,a,x]),l.jsx("iframe",{ref:p,src:v,sandbox:n,allow:S,title:d,className:u,style:c})}),ORt=e=>{const t=e==="dark";return{"--color-background-primary":t?"#171717":"#ffffff","--color-background-secondary":t?"#262626":"#f5f5f5","--color-background-tertiary":void 0,"--color-background-inverse":void 0,"--color-background-ghost":void 0,"--color-background-info":void 0,"--color-background-danger":void 0,"--color-background-success":void 0,"--color-background-warning":void 0,"--color-background-disabled":void 0,"--color-text-primary":t?"#fafafa":"#171717","--color-text-secondary":t?"#a3a3a3":"#737373","--color-text-tertiary":void 0,"--color-text-inverse":void 0,"--color-text-info":void 0,"--color-text-danger":void 0,"--color-text-success":void 0,"--color-text-warning":void 0,"--color-text-disabled":void 0,"--color-text-ghost":void 0,"--color-border-primary":t?"#404040":"#e5e5e5","--color-border-secondary":void 0,"--color-border-tertiary":void 0,"--color-border-inverse":void 0,"--color-border-ghost":void 0,"--color-border-info":void 0,"--color-border-danger":void 0,"--color-border-success":void 0,"--color-border-warning":void 0,"--color-border-disabled":void 0,"--color-ring-primary":void 0,"--color-ring-secondary":void 0,"--color-ring-inverse":void 0,"--color-ring-info":void 0,"--color-ring-danger":void 0,"--color-ring-success":void 0,"--color-ring-warning":void 0,"--font-sans":"system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif","--font-mono":"ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace","--font-weight-normal":void 0,"--font-weight-medium":void 0,"--font-weight-semibold":void 0,"--font-weight-bold":void 0,"--font-text-xs-size":void 0,"--font-text-sm-size":void 0,"--font-text-md-size":void 0,"--font-text-lg-size":void 0,"--font-heading-xs-size":void 0,"--font-heading-sm-size":void 0,"--font-heading-md-size":void 0,"--font-heading-lg-size":void 0,"--font-heading-xl-size":void 0,"--font-heading-2xl-size":void 0,"--font-heading-3xl-size":void 0,"--font-text-xs-line-height":void 0,"--font-text-sm-line-height":void 0,"--font-text-md-line-height":void 0,"--font-text-lg-line-height":void 0,"--font-heading-xs-line-height":void 0,"--font-heading-sm-line-height":void 0,"--font-heading-md-line-height":void 0,"--font-heading-lg-line-height":void 0,"--font-heading-xl-line-height":void 0,"--font-heading-2xl-line-height":void 0,"--font-heading-3xl-line-height":void 0,"--border-radius-xs":void 0,"--border-radius-sm":"4px","--border-radius-md":"8px","--border-radius-lg":"12px","--border-radius-xl":void 0,"--border-radius-full":void 0,"--border-width-regular":void 0,"--shadow-hairline":void 0,"--shadow-sm":void 0,"--shadow-md":void 0,"--shadow-lg":void 0}},RRt={type:"object"};class PRt{inner;onSend;onReceive;_sessionId;onclose;onerror;onmessage;setProtocolVersion;constructor(t,n){this.inner=t,this.onSend=n.onSend,this.onReceive=n.onReceive}get sessionId(){return this._sessionId??this.inner.sessionId}set sessionId(t){this._sessionId=t,this.inner.sessionId=t}async start(){this.inner.onmessage=(t,n)=>{this.onReceive?.(t),this.onmessage?.(t,n)},this.inner.onerror=t=>{this.onerror?.(t)},this.inner.onclose=()=>{this.onclose?.()},this.inner.setProtocolVersion=t=>{this.setProtocolVersion?.(t)},await this.inner.start()}async send(t,n){this.onSend?.(t),await this.inner.send(t,n)}async close(){await this.inner.close()}}function yK({serverId:e,toolCallId:t,toolName:n,toolState:r,toolInput:i,toolOutput:a,toolErrorText:s,resourceUri:o,toolMetadata:u,toolsMetadata:c,onSendFollowUp:d,onCallTool:f,pipWidgetId:p,fullscreenWidgetId:m,onRequestPip:y,onExitPip:v,displayMode:x,onDisplayModeChange:_,onRequestFullscreen:S,onExitFullscreen:w,onModelContextUpdate:T,onAppSupportedDisplayModesChange:N,isOffline:E,cachedWidgetHtmlUrl:A}){const I=b.useRef(null),M=eo(ht=>ht.themeMode),$=Zt(ht=>ht.isPlaygroundActive),O=Zt(ht=>ht.mcpAppsCspMode),R=$?O:"permissive",U=Zt(ht=>ht.globals.locale),z=Zt(ht=>ht.globals.timeZone),F=$?U:navigator.language||"en-US",D=$?z:Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",W=Zt(ht=>ht.displayMode),q=Zt(ht=>ht.capabilities),X=b.useMemo(()=>$?q:{hover:!0,touch:!1},[$,q]),L=Zt(ht=>ht.safeAreaInsets),Y=b.useMemo(()=>$?L:{top:0,right:0,bottom:0,left:0},[$,L]),G=Zt(ht=>ht.deviceType),P=b.useMemo(()=>{if(!$)return"web";switch(G){case"mobile":case"tablet":return"mobile";case"desktop":default:return"web"}},[$,G]),V=x!==void 0,[K,Q]=b.useState($?W:"inline"),oe=V?x:K,re=b.useMemo(()=>V?oe==="fullscreen"&&m===t?"fullscreen":oe==="pip"&&p===t?"pip":"inline":oe,[oe,m,V,p,t]),ee=b.useCallback(ht=>{V?_?.(ht):Q(ht),ht==="fullscreen"?S?.(t):oe==="fullscreen"&&w?.(t)},[V,_,t,S,w,oe]),[le,te]=b.useState(!1),[Z,ne]=b.useState(null),[J,se]=b.useState(null),[ie,he]=b.useState(void 0),[ye,Ne]=b.useState(void 0),[ce,Te]=b.useState(!1),[we,Oe]=b.useState(!0),[Ue,Me]=b.useState(null);b.useEffect(()=>{se(null),Me(null)},[A]);const be=b.useRef(null),je=b.useRef(null),Xe=b.useRef(null),ue=b.useRef(null),fe=b.useRef(null),xe=b.useRef(!1),Ce=b.useRef(d),He=b.useRef(f),Ze=b.useRef(y),st=b.useRef(v),ot=b.useRef(ee),mt=b.useRef($),Bt=b.useRef(G),Mt=b.useRef(re),It=b.useRef(e),gn=b.useRef(t),nt=b.useRef(p),yt=b.useRef(c),ut=b.useRef(T),vt=b.useRef(N),Wt=b.useRef(i);Wt.current=i;const Qn=b.useRef(a);Qn.current=a;const Gi=b.useRef(M);Gi.current=M,b.useEffect(()=>{if(r!=="output-available"||J&&Ue===R)return;(async()=>{try{if(A){const ol=await fetch(A);if(!ol.ok)throw new Error(`Failed to fetch cached widget HTML: ${ol.statusText}`);const Ve=await ol.text();se(Ve),Te(!0),Oe(!0),Me(R);return}if(E){ne("Server is offline and this view was saved without cached HTML. Connect the server and re-save the view to enable offline rendering.");return}const Nt=await Yt("/api/mcp/apps/widget/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:e,resourceUri:o,toolInput:Wt.current,toolOutput:Qn.current,toolId:t,toolName:n,theme:Gi.current,protocol:"mcp-apps",cspMode:R})});if(!Nt.ok)throw new Error(`Failed to store widget: ${Nt.statusText}`);const Tt=await fetch(`/api/mcp/apps/widget-content/${t}?csp_mode=${R}`);if(!Tt.ok){const ol=await Tt.json().catch(()=>({}));throw new Error(ol.error||`Failed to fetch widget: ${Tt.statusText}`)}const{html:Cr,csp:vn,permissions:yr,permissive:Ka,mimeTypeWarning:ms,mimeTypeValid:js,prefersBorder:Xc}=await Tt.json();if(!js){ne(ms||'Invalid mimetype - SEP-1865 requires "text/html;profile=mcp-app"');return}se(Cr),he(vn),Ne(yr),Te(Ka??!1),Oe(Xc??!0),Me(R),Zc(t,Cr),(vn||yr||!Ka)&&ln(t,{mode:Ka?"permissive":"widget-declared",connectDomains:vn?.connectDomains||[],resourceDomains:vn?.resourceDomains||[],frameDomains:vn?.frameDomains||[],baseUriDomains:vn?.baseUriDomains||[],permissions:yr,widgetDeclared:vn?{connectDomains:vn.connectDomains,resourceDomains:vn.resourceDomains,frameDomains:vn.frameDomains,baseUriDomains:vn.baseUriDomains}:null})}catch(Nt){ne(Nt instanceof Error?Nt.message:"Failed to prepare widget")}})()},[r,t,J,Ue,e,o,n,R,E,A]);const Pt=km(ht=>ht.addLog),sn=bs(ht=>ht.setWidgetDebugInfo),Mn=bs(ht=>ht.setWidgetGlobals),ln=bs(ht=>ht.setWidgetCsp),ir=bs(ht=>ht.addCspViolation),Ga=bs(ht=>ht.clearCspViolations),ja=bs(ht=>ht.setWidgetModelContext),Zc=bs(ht=>ht.setWidgetHtml);b.useEffect(()=>{Ue!==null&&Ue!==R&&Ga(t)},[R,Ue,t,Ga]),b.useEffect(()=>{Ue!==null&&Ue!==R&&(te(!1),xe.current=!1,Xe.current=null,ue.current=null,fe.current=null)},[R,Ue]),b.useEffect(()=>{$&&!V&&Q(W)},[$,W,V]),b.useEffect(()=>{sn(t,{toolName:n,protocol:"mcp-apps",widgetState:null,globals:{theme:M,displayMode:re,locale:F,timeZone:D,deviceCapabilities:X,safeAreaInsets:Y}})},[t,n,sn,M,re,F,D,X,Y]),b.useEffect(()=>{Mn(t,{theme:M,displayMode:re,locale:F,timeZone:D,deviceCapabilities:X,safeAreaInsets:Y})},[t,M,re,F,D,X,Y,Mn]);const qu=b.useMemo(()=>ORt(M),[M]),Is=b.useMemo(()=>({theme:M,displayMode:re,availableDisplayModes:["inline","pip","fullscreen"],locale:F,timeZone:D,platform:P,userAgent:navigator.userAgent,deviceCapabilities:X,safeAreaInsets:Y,styles:{variables:qu},toolInfo:{id:t,tool:{name:n,inputSchema:u?.inputSchema??RRt,description:u?.description}}}),[M,re,F,D,P,X,Y,qu,t,n,u]);b.useEffect(()=>{je.current=Is},[Is]),b.useEffect(()=>{Ce.current=d,He.current=f,Ze.current=y,st.current=v,ot.current=ee,mt.current=$,Bt.current=G,Mt.current=re,It.current=e,gn.current=t,nt.current=p,yt.current=c,ut.current=T,vt.current=N},[d,f,y,v,ee,$,G,re,e,t,p,c,T,N]);const Hu=b.useCallback(ht=>{ht.oninitialized=()=>{te(!0),xe.current=!0;const Nt=ht.getAppCapabilities();vt.current?.(Nt?.availableDisplayModes)},ht.onmessage=async({content:Nt})=>{const Tt=Nt.find(Cr=>Cr.type==="text")?.text;return Tt&&Ce.current?.(Tt),{}},ht.onopenlink=async({url:Nt})=>(Nt&&window.open(Nt,"_blank","noopener,noreferrer"),{}),ht.oncalltool=async({name:Nt,arguments:Tt},Cr)=>{const vn=yt.current?.[Nt];if(Smt(vn)){const yr=new Error(`Tool "${Nt}" is not callable by apps (visibility: model-only)`);throw ht.sendToolCancelled({reason:yr.message}),yr}if(!He.current){const yr=new Error("Tool calls not supported");throw ht.sendToolCancelled({reason:yr.message}),yr}try{return await He.current(Nt,Tt??{})}catch(yr){throw ht.sendToolCancelled({reason:yr instanceof Error?yr.message:String(yr)}),yr}},ht.onreadresource=async({uri:Nt})=>{const Tt=await Yt("/api/mcp/resources/read",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:It.current,uri:Nt})});if(!Tt.ok)throw new Error(`Resource read failed: ${Tt.statusText}`);return(await Tt.json()).content},ht.onlistresources=async Nt=>{const Tt=await Yt("/api/mcp/resources/list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:It.current,...Nt??{}})});if(!Tt.ok)throw new Error(`Resource list failed: ${Tt.statusText}`);return Tt.json()},ht.onlistresourcetemplates=async Nt=>{const Tt=await Yt("/api/mcp/resource-templates/list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:It.current,...Nt??{}})});if(!Tt.ok)throw new Error(`Resource template list failed: ${Tt.statusText}`);return Tt.json()},ht.onlistprompts=async Nt=>{const Tt=await Yt("/api/mcp/prompts/list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:It.current,...Nt??{}})});if(!Tt.ok)throw new Error(`Prompt list failed: ${Tt.statusText}`);return Tt.json()},ht.onloggingmessage=({level:Nt,data:Tt,logger:Cr})=>{const yr=`${Cr?`[${Cr}]`:"[MCP Apps]"} ${Nt.toUpperCase()}:`;if(Nt==="error"||Nt==="critical"||Nt==="alert"){console.error(yr,Tt);return}if(Nt==="warning"){console.warn(yr,Tt);return}console.info(yr,Tt)},ht.onsizechange=({height:Nt})=>{if(Mt.current!=="inline")return;const Tt=I.current?.getIframeElement();if(!Tt||Nt===void 0)return;const Cr=getComputedStyle(Tt),vn=Cr.boxSizing==="border-box",yr={},Ka={};let ms=Nt;ms!==void 0&&(vn&&(ms+=parseFloat(Cr.borderTopWidth)+parseFloat(Cr.borderBottomWidth)),yr.height=`${Tt.offsetHeight}px`,Tt.style.height=Ka.height=`${ms}px`),Tt.animate([yr,Ka],{duration:300,easing:"ease-out"})},ht.onrequestdisplaymode=async({mode:Nt})=>{const Tt=Nt??"inline",vn=(mt.current?Bt.current==="mobile"||Bt.current==="tablet":!0)&&Tt==="pip"?"fullscreen":Tt;return ot.current(vn),vn==="pip"?Ze.current?.(gn.current):(vn==="inline"||vn==="fullscreen")&&nt.current===gn.current&&st.current?.(gn.current),{mode:vn}},ht.onupdatemodelcontext=async({content:Nt,structuredContent:Tt})=>(ja(t,{content:Nt,structuredContent:Tt}),ut.current?.(t,{content:Nt,structuredContent:Tt}),{})},[te,t,ja]);b.useEffect(()=>{if(!J)return;const ht=I.current?.getIframeElement();if(!ht?.contentWindow)return;te(!1),xe.current=!1;const Nt=new xmt(null,{name:"mcpjam-inspector",version:"1.5.13"},{openLinks:{},serverTools:{},serverResources:{},logging:{},sandbox:{csp:ce?void 0:ie,permissions:ye}},{hostContext:je.current??{}});Hu(Nt),be.current=Nt;const Tt=new PRt(new gmt(ht.contentWindow,ht.contentWindow),{onSend:vn=>{Pt({widgetId:t,serverId:e,direction:"host-to-ui",protocol:"mcp-apps",method:L1(vn,"mcp-apps"),message:vn})},onReceive:vn=>{Pt({widgetId:t,serverId:e,direction:"ui-to-host",protocol:"mcp-apps",method:L1(vn,"mcp-apps"),message:vn})}});let Cr=!0;return Nt.connect(Tt).catch(vn=>{Cr&&ne(vn instanceof Error?vn.message:"Failed to connect MCP App")}),()=>{Cr=!1,be.current=null,xe.current&&Nt.teardownResource({}).catch(()=>{}),Nt.close().catch(()=>{}),ja(t,null)}},[Pt,e,t,J,Hu,ja]),b.useEffect(()=>{const ht=be.current;!ht||!le||ht.setHostContext(Is)},[Is,le]),b.useEffect(()=>{if(!le||r!=="output-available")return;const ht=be.current;if(!ht)return;const Nt=i??{},Tt=JSON.stringify(Nt);Xe.current!==Tt&&(Xe.current=Tt,ht.sendToolInput({arguments:Nt}))},[le,i,r]),b.useEffect(()=>{if(!le||r!=="output-available")return;const ht=be.current;if(!ht||!a)return;const Nt=JSON.stringify(a);ue.current!==Nt&&(ue.current=Nt,ht.sendToolResult(a))},[le,a,r]),b.useEffect(()=>{if(!le||r!=="output-error")return;const ht=be.current;if(!ht)return;const Nt=s??(a instanceof Error?a.message:typeof a=="string"?a:"Tool execution failed");fe.current!==Nt&&(fe.current=Nt,ht.sendToolCancelled({reason:Nt}))},[le,s,a,r]),b.useEffect(()=>{Xe.current=null,ue.current=null,fe.current=null},[t]);const Ao=ht=>{if(ht.data?.type!=="mcp-apps:csp-violation")return;const{directive:Nt,blockedUri:Tt,sourceFile:Cr,lineNumber:vn,columnNumber:yr,effectiveDirective:Ka,timestamp:ms}=ht.data;Pt({widgetId:t,serverId:e,direction:"ui-to-host",protocol:"mcp-apps",method:"csp-violation",message:ht.data}),ir(t,{directive:Nt,effectiveDirective:Ka,blockedUri:Tt,sourceFile:Cr,lineNumber:vn,columnNumber:yr,timestamp:ms||Date.now()}),console.warn(`[MCP Apps CSP Violation] ${Nt}: Blocked ${Tt}`,Cr?`at ${Cr}:${vn}:${yr}`:"")};if(r==="output-denied")return l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Tool execution was denied."});if(r!=="output-available")return l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Waiting for tool to finish executing..."});if(Z)return l.jsxs("div",{className:"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",children:["Failed to load MCP App: ",Z]});if(!J)return l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Preparing MCP App widget..."});const Ai=re==="pip",Wa=re==="fullscreen",hs=$&&G==="mobile",vr=$&&(G==="mobile"||G==="tablet"),Yc=Wa?vr?"absolute inset-0 z-10 w-full h-full bg-background flex flex-col":"fixed inset-0 z-40 w-full h-full bg-background flex flex-col":Ai?hs?"absolute inset-0 z-10 w-full h-full bg-background flex flex-col":["fixed top-4 left-1/2 -translate-x-1/2 z-40 w-full min-w-[300px] max-w-[min(90vw,1200px)] space-y-2","bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80","shadow-xl border border-border/60 rounded-xl p-3"].join(" "):"mt-3 space-y-2 relative group",Xl={height:Wa?"100%":"400px",width:"100%",maxWidth:"100%",transition:Wa?void 0:"height 300ms ease-out"};return l.jsxs("div",{className:Yc,children:[(Wa&&vr||Ai&&hs)&&l.jsx("button",{onClick:()=>{ee("inline"),Ai&&v?.(t)},className:"absolute left-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer","aria-label":"Close",children:l.jsx(Yn,{className:"w-5 h-5"})}),Wa&&!vr&&l.jsxs("div",{className:"flex items-center justify-between px-4 h-14 border-b border-border/40 bg-background/95 backdrop-blur z-40 shrink-0",children:[l.jsx("div",{}),l.jsx("div",{className:"font-medium text-sm text-muted-foreground",children:n}),l.jsx("button",{onClick:()=>{ee("inline"),p===t&&v?.(t)},className:"p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors","aria-label":"Exit fullscreen",children:l.jsx(Yn,{className:"w-5 h-5"})})]}),Ai&&!hs&&l.jsx("button",{onClick:()=>{ee("inline"),v?.(t)},className:"absolute left-2 top-2 z-10 flex h-6 w-6 items-center justify-center rounded-md bg-background/80 hover:bg-background border border-border/50 text-muted-foreground hover:text-foreground transition-colors cursor-pointer","aria-label":"Close PiP mode",title:"Close PiP mode",children:l.jsx(Yn,{className:"w-4 h-4"})}),l.jsx(jRt,{ref:I,html:J,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",csp:ie,permissions:ye,permissive:ce,onMessage:Ao,title:`MCP App: ${n}`,className:`bg-background overflow-hidden ${Wa?"flex-1 border-0 rounded-none":`rounded-md ${we?"border border-border/40":""}`}`,style:Xl}),l.jsxs("div",{className:"text-[11px] text-muted-foreground/70",children:["MCP App: ",l.jsx("code",{children:o})]})]})}function $Rt(e){const t=[];let n=[];for(const r of e){if(r.type==="step-start"){n.length>0&&t.push(n),n=[];continue}n.push(r)}return n.length>0&&t.push(n),t.length>0?t:[e.filter(r=>r.type!=="step-start")]}function uD(e){const t=e.type;return typeof t=="string"&&t.startsWith("tool-")}function Q1(e){return!!e&&typeof e.type=="string"&&e.type==="dynamic-tool"}function Qoe(e){if(Q1(e))return{toolName:e.toolName,toolCallId:e.toolCallId,toolState:e.state,input:e.input,output:e.output,rawOutput:e.output,errorText:e.errorText};const t=e,n=t.output;return{toolName:TPe(t.type),toolCallId:t.toolCallId,toolState:t.state,input:t.input,output:t.output?.value??n,rawOutput:n,errorText:t.errorText??t.error}}function MRt(e){const t=e?.value?.content??e?.content;return Array.isArray(t)?t.find(r=>oke(r))??null:null}function DRt(e){const t=e.type;return typeof t=="string"&&t.startsWith("data-")}function LRt(e){return e==="data-"?"Data":`Data (${e.replace(/^data-/,"")})`}function TPe(e){return e&&e.startsWith("tool-")?e.replace(/^tool-/,""):"Tool"}function zRt(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function URt(e){if(!e)return null;switch(e){case"input-streaming":return{Icon:Pn,label:"Input streaming",className:"h-4 w-4 animate-spin text-muted-foreground"};case"input-available":return{Icon:ko,label:"Input available",className:"h-4 w-4 text-muted-foreground"};case"output-available":return{Icon:ko,label:"Output available",className:"h-4 w-4 text-emerald-500"};case"approval-requested":return{Icon:DQe,label:"Approval requested",className:"h-4 w-4 text-amber-500"};case"output-denied":return{Icon:Lv,label:"Denied",className:"h-4 w-4 text-destructive"};case"output-error":return{Icon:wo,label:"Output error",className:"h-4 w-4 text-destructive"};default:return null}}function FRt(e){if(!e||e==="inline"||e==="eval"||e==="data"||e==="blob")return null;try{return new URL(e).origin}catch{const t=e.match(/^(https?:\/\/[^/]+)/);return t?t[1]:null}}function BRt(e){const t=e.replace(/-src$/,"");return t==="connect"?"connect_domains":["script","style","img","font","media","default"].includes(t)?"resource_domains":null}function qRt(e){const t=new Map,n=new Map;for(const i of e){const a=i.effectiveDirective||i.directive,s=BRt(a),o=FRt(i.blockedUri);if(!s||!o)continue;const u=s==="connect_domains"?t:n,c=u.get(o)||[];c.push(i),u.set(o,c)}const r=[];return t.size>0&&r.push({field:"connect_domains",domains:Array.from(t.keys()),violations:Array.from(t.values()).flat()}),n.size>0&&r.push({field:"resource_domains",domains:Array.from(n.keys()),violations:Array.from(n.values()).flat()}),r}function HRt(e,t,n){const r=new Set([...t?.connect_domains||[],...t?.connectDomains||[]]),i=new Set([...t?.resource_domains||[],...t?.resourceDomains||[]]);for(const o of e){const u=o.field==="connect_domains"?r:i;for(const c of o.domains)u.add(c)}const a=n!=="openai-apps",s={};if(r.size>0){const o=a?"connectDomains":"connect_domains";s[o]=Array.from(r)}if(i.size>0){const o=a?"resourceDomains":"resource_domains";s[o]=Array.from(i)}return JSON.stringify(s,null,2)}function VRt({cspInfo:e,protocol:t}){const n=e?.mode??"permissive",r=e?.violations??[],i=r.length>0,[a,s]=b.useState(!1),o=e?.widgetDeclared?.connect_domains??e?.widgetDeclared?.connectDomains??[],u=e?.widgetDeclared?.resource_domains??e?.widgetDeclared?.resourceDomains??[],c=e?.widgetDeclared?.frame_domains??e?.widgetDeclared?.frameDomains??[],d=e?.widgetDeclared?.baseUriDomains??[],f=b.useMemo(()=>qRt(r),[r]),p=b.useMemo(()=>i?HRt(f,e?.widgetDeclared,t):"",[f,e?.widgetDeclared,i,t]),m=async()=>{try{await navigator.clipboard.writeText(p),s(!0),setTimeout(()=>s(!1),2e3)}catch(y){console.error("Failed to copy:",y)}};return l.jsxs("div",{className:"space-y-4 text-xs",children:[i&&f.length>0&&l.jsxs("details",{className:"group",children:[l.jsxs("summary",{className:"flex items-center gap-1.5 text-amber-600 dark:text-amber-400 cursor-pointer list-none",children:[l.jsx(wr,{className:"h-3.5 w-3.5 transition-transform group-open:rotate-90"}),l.jsx(PJe,{className:"h-3.5 w-3.5"}),l.jsx("span",{className:"font-medium",children:"Suggested fix"})]}),l.jsxs("div",{className:"mt-2 pl-5 space-y-1",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx(Zn,{className:"text-[10px] text-muted-foreground",children:t==="mcp-apps"?"Add the following to your ui.csp field":"Add the following to your openai/widgetCSP field"}),l.jsx("button",{onClick:m,className:"p-1 hover:bg-muted rounded transition-colors",title:"Copy to clipboard",children:a?l.jsx(xi,{className:"h-3 w-3 text-green-500"}):l.jsx(Ca,{className:"h-3 w-3 text-muted-foreground"})})]}),l.jsx("pre",{className:"font-mono text-[10px] bg-muted/50 p-2 rounded overflow-auto max-h-32 text-foreground",children:p})]})]}),i&&l.jsxs("details",{className:"group",children:[l.jsxs("summary",{className:"flex items-center gap-1.5 text-destructive cursor-pointer list-none",children:[l.jsx(wr,{className:"h-3.5 w-3.5 transition-transform group-open:rotate-90"}),l.jsx(Gs,{className:"h-3.5 w-3.5"}),l.jsxs("span",{className:"font-medium",children:[r.length," blocked request",r.length!==1?"s":""]})]}),l.jsx("div",{className:"mt-2 space-y-1 max-h-32 overflow-auto pl-5",children:r.map((y,v)=>l.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-muted-foreground",children:[l.jsx(Cn,{variant:"outline",className:"text-[9px] px-1 py-0 h-4 shrink-0",children:y.effectiveDirective||y.directive}),l.jsx("span",{className:"font-mono truncate",children:y.blockedUri||"(inline)"})]},v))})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{className:"text-[10px] text-muted-foreground",children:"connect_domains"}),l.jsx("div",{className:"text-[10px]",children:n==="permissive"?l.jsx("span",{className:"text-muted-foreground italic",children:"Not enforced in permissive mode"}):o.length>0?l.jsx("div",{className:"font-mono space-y-0.5",children:o.map((y,v)=>l.jsx("div",{className:"truncate",children:y},v))}):l.jsx("span",{className:"text-muted-foreground italic",children:"Not declared"})})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{className:"text-[10px] text-muted-foreground",children:"resource_domains"}),l.jsx("div",{className:"text-[10px]",children:n==="permissive"?l.jsx("span",{className:"text-muted-foreground italic",children:"Not enforced in permissive mode"}):u.length>0?l.jsx("div",{className:"font-mono space-y-0.5",children:u.map((y,v)=>l.jsx("div",{className:"truncate",children:y},v))}):l.jsx("span",{className:"text-muted-foreground italic",children:"Not declared"})})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{className:"text-[10px] text-muted-foreground",children:t==="openai-apps"?"frame_domains":"frameDomains"}),l.jsx("div",{className:"text-[10px]",children:n==="permissive"?l.jsx("span",{className:"text-muted-foreground italic",children:"Not enforced in permissive mode"}):c.length>0?l.jsx("div",{className:"font-mono space-y-0.5",children:c.map((y,v)=>l.jsx("div",{className:"truncate",children:y},v))}):l.jsx("span",{className:"text-muted-foreground italic",children:"Not declared"})})]}),t==="mcp-apps"&&l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{className:"text-[10px] text-muted-foreground",children:"baseUriDomains"}),l.jsx("div",{className:"text-[10px]",children:n==="permissive"?l.jsx("span",{className:"text-muted-foreground italic",children:"Not enforced in permissive mode"}):d.length>0?l.jsx("div",{className:"font-mono space-y-0.5",children:d.map((y,v)=>l.jsx("div",{className:"truncate",children:y},v))}):l.jsx("span",{className:"text-muted-foreground italic",children:"Not declared"})})]})]}),e?.headerString&&l.jsxs("details",{children:[l.jsx("summary",{className:"text-[10px] text-muted-foreground cursor-pointer hover:text-foreground",children:"Full CSP header"}),l.jsx("div",{className:"mt-1 font-mono text-[9px] text-muted-foreground bg-muted/50 p-2 rounded max-h-24 overflow-auto break-all",children:e.headerString})]}),l.jsxs("a",{href:t==="mcp-apps"?"https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#ui-resource-format":"https://developers.openai.com/apps-sdk/reference/#component-resource-configuration",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground",children:[l.jsx(Iu,{className:"h-3 w-3"}),t==="mcp-apps"?"MCP Apps UI format docs":"openai/widgetCSP docs"]})]})}function Yh({part:e,uiType:t,displayMode:n,pipWidgetId:r,fullscreenWidgetId:i,onDisplayModeChange:a,onRequestFullscreen:s,onExitFullscreen:o,onRequestPip:u,onExitPip:c,appSupportedDisplayModes:d,approvalId:f,onApprove:p,onDeny:m,onSaveView:y,canSaveView:v,saveDisabledReason:x,isSaving:_}){const S=Q1(e)?e.toolName:TPe(e.type),w=e.toolCallId,T=e.state,N=URt(T),E=N?.Icon,I=eo(Z=>Z.themeMode)==="dark"?"h-3 w-3 filter invert":"h-3 w-3",M=T==="approval-requested"&&!!f,[$,O]=b.useState("pending"),U=$==="denied"||T==="output-denied"||M,[z,F]=b.useState(!1),D=M||z,[W,q]=b.useState("data"),X=e.input,L=e.output,Y=e.errorText??e.error,G=X!=null,P=L!=null,V=T==="output-error"&&!!Y,K=bs(Z=>w?Z.widgets.get(w):void 0),Q=!!K,oe=n!==void 0&&a!==void 0&&Q&&!U,re=[{mode:"inline",icon:Bm,label:"Inline"},{mode:"pip",icon:xQe,label:"Picture in Picture"},{mode:"fullscreen",icon:R1e,label:"Fullscreen"}],ee=b.useMemo(()=>{const Z=[{tab:"data",icon:nJe,label:"Data"}];return t===bn.OPENAI_SDK&&Z.push({tab:"state",icon:AXe,label:"Widget State"}),t===bn.MCP_APPS&&K?.modelContext&&Z.push({tab:"context",icon:Bm,label:"Model Context"}),Z.push({tab:"csp",icon:lA,label:"CSP",badge:K?.csp?.violations?.length}),Z},[t,K?.csp?.violations?.length,K?.modelContext]),le=Z=>{W===Z?(q(null),F(!1)):(q(Z),F(!0))},te=Z=>{w&&(n==="fullscreen"&&Z!=="fullscreen"?o?.(i??w):n==="pip"&&Z!=="pip"&&c?.(r??w),Z==="fullscreen"?s?.(w):Z==="pip"&&u?.(w)),a?.(Z)};return l.jsxs("div",{className:hu("rounded-lg border text-xs",M&&$==="pending"?"border-pending/40 bg-pending/5":M&&$==="approved"?"border-success/40 bg-success/5":M&&$==="denied"?"border-destructive/40 bg-destructive/5":"border-border/50 bg-background/70"),children:[l.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wide text-muted-foreground cursor-pointer",onClick:()=>F(Z=>!Z),"aria-expanded":D,children:[l.jsxs("span",{className:"inline-flex items-center gap-2 font-medium normal-case text-foreground min-w-0",children:[l.jsxs("span",{className:"inline-flex items-center gap-2 min-w-0",children:[l.jsx("img",{src:"/mcp.svg",alt:"",role:"presentation","aria-hidden":"true",className:`${I} shrink-0`}),l.jsx("span",{className:"font-mono text-xs tracking-tight text-muted-foreground/80 truncate",children:S})]}),M&&$==="pending"&&l.jsx("span",{className:"text-[11px] font-medium text-pending-foreground dark:text-pending",children:"Approve tool call?"}),M&&$==="approved"&&l.jsxs("span",{className:"flex items-center gap-1 text-[11px] font-medium text-success dark:text-success",children:[l.jsx(M1e,{className:"h-3.5 w-3.5"}),"Approved"]}),M&&$==="denied"&&l.jsxs("span",{className:"flex items-center gap-1 text-[11px] font-medium text-destructive",children:[l.jsx(Lv,{className:"h-3.5 w-3.5"}),"Denied"]})]}),l.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground shrink-0",children:[oe&&l.jsx("span",{className:"inline-flex items-center gap-0.5 border border-border/40 rounded-md p-0.5 bg-muted/30",onClick:Z=>Z.stopPropagation(),children:l.jsx("div",{className:"inline-flex items-center gap-0.5",children:re.map(({mode:Z,icon:ne,label:J})=>{const se=n===Z,ie=d!==void 0&&!d.includes(Z);return l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("button",{type:"button",disabled:ie,onClick:he=>{he.stopPropagation(),!ie&&te(Z)},className:`p-1 rounded transition-colors ${ie?"text-muted-foreground/30 cursor-not-allowed":se?"bg-background text-foreground shadow-sm cursor-pointer":"text-muted-foreground/60 hover:text-muted-foreground hover:bg-background/50 cursor-pointer"}`,children:l.jsx(ne,{className:"h-3.5 w-3.5"})})}),l.jsx(zt,{children:ie?`${J} (not supported by this app)`:J})]},Z)})})}),Q&&!U&&l.jsxs(l.Fragment,{children:[oe&&Q&&l.jsx("div",{className:"h-4 w-px bg-border/40"}),l.jsx("span",{className:"inline-flex items-center gap-0.5 border border-border/40 rounded-md p-0.5 bg-muted/30",onClick:Z=>Z.stopPropagation(),children:ee.map(({tab:Z,icon:ne,label:J,badge:se})=>l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsxs("button",{type:"button",onClick:ie=>{ie.stopPropagation(),le(Z)},className:`p-1 rounded transition-colors cursor-pointer relative ${W===Z?"bg-background text-foreground shadow-sm":se&&se>0?"text-destructive hover:text-destructive hover:bg-destructive/10":"text-muted-foreground/60 hover:text-muted-foreground hover:bg-background/50"}`,children:[l.jsx(ne,{className:"h-3.5 w-3.5"}),se!==void 0&&se>0&&l.jsx(Cn,{variant:"destructive",className:"absolute -top-1.5 -right-1.5 h-3.5 min-w-[14px] px-1 text-[8px] leading-none",children:se})]})}),l.jsx(zt,{children:J})]},Z))})]}),y&&t&&t!==bn.MCP_UI&&l.jsxs(l.Fragment,{children:[Q&&l.jsx("div",{className:"h-4 w-px bg-border/40"}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("button",{type:"button",disabled:!v||_,onClick:Z=>{Z.stopPropagation(),y()},className:`p-1 rounded transition-colors ${v&&!_?"text-muted-foreground/60 hover:text-muted-foreground hover:bg-background/50 cursor-pointer":"text-muted-foreground/30 cursor-not-allowed"}`,children:_?l.jsx(Pn,{className:"h-3.5 w-3.5 animate-spin"}):l.jsx(N1,{className:"h-3.5 w-3.5"})})}),l.jsx(zt,{children:_?"Saving...":v?"Save as View":x||"No output to save"})]})]}),N&&E&&l.jsxs("span",{className:"inline-flex h-5 w-5 items-center justify-center",title:N.label,children:[l.jsx(E,{className:N.className}),l.jsx("span",{className:"sr-only",children:N.label})]}),!M&&l.jsx(Wr,{className:`h-4 w-4 transition-transform duration-150 ${D?"rotate-180":""}`})]})]}),D&&l.jsxs("div",{className:"border-t border-border/40 px-3 py-3",children:[Q&&W==="data"&&l.jsxs("div",{className:"space-y-4",children:[G&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Input"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[300px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:X,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),P&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Result"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[300px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:L,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),V&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Error"}),l.jsx("div",{className:"rounded border border-destructive/40 bg-destructive/10 p-2 text-destructive",children:Y})]}),!G&&!P&&!V&&l.jsx("div",{className:"text-muted-foreground/70",children:"No tool details available."})]}),Q&&W==="state"&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Widget State"}),l.jsxs("div",{className:"text-[9px] text-muted-foreground/50",children:["Updated:"," ",new Date(K.updatedAt).toLocaleTimeString()]})]}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[300px] overflow-auto",children:K.widgetState?l.jsx(zn,{viewOnly:!0,value:K.widgetState,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2}):l.jsx("div",{className:"p-2 text-[11px] text-muted-foreground",children:"null (no state set)"})}),l.jsx("div",{className:"text-[9px] text-muted-foreground/50 mt-2",children:"Tip: Widget state persists across follow-up turns. Keep under 4k tokens."})]}),Q&&W==="csp"&&l.jsx(VRt,{cspInfo:K.csp,protocol:K.protocol}),Q&&W==="context"&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Model Context"}),K.modelContext&&l.jsxs("div",{className:"text-[9px] text-muted-foreground/50",children:["Updated:"," ",new Date(K.modelContext.updatedAt).toLocaleTimeString()]})]}),K.modelContext?l.jsxs("div",{className:"space-y-3",children:[K.modelContext.content&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-medium text-muted-foreground",children:"Content (for model)"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[200px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:K.modelContext.content,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),K.modelContext.structuredContent&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-medium text-muted-foreground",children:"Structured Content"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[200px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:K.modelContext.structuredContent,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),l.jsx("div",{className:"text-[9px] text-muted-foreground/50 mt-2",children:"This context will be included in future turns with the model. Each update overwrites the previous context from this widget."})]}):l.jsx("div",{className:"text-muted-foreground/70 text-[11px]",children:"No model context set by this widget."})]}),!Q&&l.jsxs("div",{className:"space-y-4",children:[G&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Input"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[300px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:X,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),P&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Result"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[300px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:L,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),V&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Error"}),l.jsx("div",{className:"rounded border border-destructive/40 bg-destructive/10 p-2 text-destructive",children:Y})]}),!G&&!P&&!V&&l.jsx("div",{className:"text-muted-foreground/70",children:"No tool details available."})]}),M&&$==="pending"&&l.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border/40 mt-3",children:[l.jsxs(Ee,{type:"button",size:"sm",variant:"outline",className:"h-7 px-3 text-xs border-success/40 text-success hover:bg-success/10",onClick:Z=>{Z.stopPropagation(),f&&(O("approved"),F(!1),p?.(f))},children:[l.jsx(xi,{className:"h-3 w-3 mr-1"}),"Approve"]}),l.jsxs(Ee,{type:"button",size:"sm",variant:"outline",className:"h-7 px-3 text-xs border-destructive/40 text-destructive hover:bg-destructive/10",onClick:Z=>{Z.stopPropagation(),f&&(O("denied"),F(!1),m?.(f))},children:[l.jsx(Yn,{className:"h-3 w-3 mr-1"}),"Deny"]})]})]})]})}function GRt({text:e}){return e?l.jsx("div",{className:"rounded-lg border border-border/30 bg-muted/10 p-3 text-xs text-muted-foreground",children:l.jsx("pre",{className:"whitespace-pre-wrap break-words",children:e})}):null}function WRt(e){return e?.startsWith("image/")??!1}function KRt(e){return e?e.startsWith("image/")?XO:e==="application/pdf"||e==="text/plain"?Um:e==="text/csv"||e==="application/vnd.ms-excel"||e.includes("spreadsheet")?I1e:Fm:Fm}function ele(e,t=24){if(e.length<=t)return e;const n=e.lastIndexOf(".");if(n===-1)return e.slice(0,t-3)+"...";const r=e.slice(n),i=e.slice(0,n),a=t-r.length-3;return a<=0?"..."+r:i.slice(0,a)+"..."+r}function ZRt({part:e}){const t=e.filename??"Attachment";if(WRt(e.mediaType)&&e.url)return l.jsxs("div",{className:"inline-block",children:[l.jsx("img",{src:e.url,alt:t,className:"max-w-xs max-h-48 rounded-md object-contain border border-border"}),e.filename&&l.jsx("div",{className:"text-xs text-muted-foreground mt-1 truncate max-w-xs text-right",title:e.filename,children:ele(e.filename)})]});const r=KRt(e.mediaType);return l.jsxs("div",{className:"inline-flex items-center gap-2 rounded-md border border-border bg-muted/50 px-3 py-2 text-sm",children:[l.jsx(r,{className:"h-5 w-5 text-muted-foreground flex-shrink-0"}),l.jsx("span",{className:"font-medium text-foreground truncate max-w-[200px]",title:t,children:ele(t)})]})}function YRt({part:e}){return l.jsxs("div",{className:"space-y-1 text-xs",children:[l.jsxs("div",{className:"font-medium",children:["🔗 ",e.title??e.url]}),l.jsx("pre",{className:"whitespace-pre-wrap break-words text-muted-foreground",children:zRt({sourceId:e.sourceId,url:e.url})})]})}function XRt({part:e}){return l.jsxs("div",{className:"space-y-1 text-xs",children:[l.jsxs("div",{className:"font-medium",children:["📄 ",e.title]}),l.jsx(zn,{viewOnly:!0,value:{sourceId:e.sourceId,mediaType:e.mediaType,filename:e.filename}})]})}function tle({label:e,value:t}){return l.jsxs("div",{className:"space-y-1 text-xs",children:[l.jsx("div",{className:"font-medium",children:e}),l.jsx(zn,{value:t,viewOnly:!0})]})}function JRt({text:e,role:t}){const n="text-foreground",r=t==="user"?"text-right":"";return l.jsx(NI,{content:e,className:`max-w-full break-words overflow-auto ${n} ${r}`})}function QRt({resource:e,onSendFollowUp:t}){const n=async r=>{switch(r.type){case"tool":console.info("MCP UI tool action received:",r.payload),t(`Call tool ${r.payload.toolName} with parameters ${JSON.stringify(r.payload.params)}`);break;case"link":if(r.payload?.url&&typeof window<"u")return window.open(r.payload.url,"_blank","noopener,noreferrer"),{status:"handled"};break;case"prompt":if(r.payload?.prompt)return t(`Prompt: ${r.payload.prompt}`),{status:"handled"};break;case"intent":if(r.payload?.intent)return t(`Intent: ${r.payload.intent}`),{status:"handled"};break;case"notify":if(r.payload?.message)return t(`Notification: ${r.payload.message}`),{status:"handled"};break}return{status:"unhandled"}};return l.jsx("div",{className:"w-full overflow-hidden rounded-2xl border border-border/40 bg-muted/20 shadow-sm",children:l.jsx(ske,{resource:e,htmlProps:{style:{border:"2px",borderRadius:"4px",minHeight:"400px"},iframeProps:{title:"Custom MCP Resource",className:"mcp-resource-frame"}},remoteDomProps:{library:YH,remoteElements:[hdt,mdt,gdt,pdt,vdt]},onUIAction:n})})}function xK({isAuthenticated:e,workspaceId:t}){const n=e&&!!t,r=Ua("views:listAllByWorkspace",n?{workspaceId:t}:"skip"),i=n&&r===void 0,a=b.useMemo(()=>r?[...r].sort((c,d)=>d.updatedAt-c.updatedAt):[],[r]),s=b.useMemo(()=>{if(!r)return new Map;const c=new Map;for(const d of r){const f=c.get(d.serverId)||[];c.set(d.serverId,[...f,d])}return c},[r]),o=b.useMemo(()=>{if(!r)return new Map;const c=new Map;for(const d of r){const f=d.category||"Uncategorized",p=c.get(f)||[];c.set(f,[...p,d])}return c},[r]),u=b.useMemo(()=>r?{mcp:r.filter(c=>c.protocol==="mcp-apps"),openai:r.filter(c=>c.protocol==="openai-apps")}:{mcp:[],openai:[]},[r]);return{views:r,sortedViews:a,viewsByServer:s,viewsByCategory:o,viewsByProtocol:u,isLoading:i,hasViews:(r?.length??0)>0}}function NPe(){const e=_n("mcpAppViews:create"),t=_n("mcpAppViews:update"),n=_n("mcpAppViews:remove"),r=_n("mcpAppViews:generateUploadUrl"),i=_n("openaiAppViews:create"),a=_n("openaiAppViews:update"),s=_n("openaiAppViews:remove"),o=_n("openaiAppViews:generateUploadUrl");return{createMcpView:e,updateMcpView:t,removeMcpView:n,generateMcpUploadUrl:r,createOpenaiView:i,updateOpenaiView:a,removeOpenaiView:s,generateOpenaiUploadUrl:o}}function bK({isAuthenticated:e,workspaceId:t}){const n=e&&!!t,r=Ua("servers:getWorkspaceServers",n?{workspaceId:t}:"skip"),i=n&&r===void 0,a=b.useMemo(()=>{if(!r)return new Map;const o=new Map;for(const u of r)o.set(u.name,u._id);return o},[r]),s=b.useMemo(()=>{if(!r)return new Map;const o=new Map;for(const u of r)o.set(u._id,u.name);return o},[r]);return{servers:r,serversByName:a,serversById:s,isLoading:i}}function ePt(){return{createServer:_n("servers:createServer")}}function CPe(){const e=Zt(a=>a.deviceType),t=Zt(a=>a.customViewport),n=Zt(a=>a.globals),r=Zt(a=>a.capabilities),i=Zt(a=>a.safeAreaInsets);return{theme:n.theme,displayMode:n.displayMode,deviceType:e==="custom"?void 0:e,viewport:e==="custom"?{width:t.width,height:t.height}:void 0,locale:n.locale,timeZone:n.timeZone,capabilities:r,safeAreaInsets:i}}function nle(e,t){return JSON.stringify(e)===JSON.stringify(t)}function tPt(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e} (${n})`);)n++;return`${e} (${n})`}function nPt({isAuthenticated:e,workspaceId:t,serverName:n,existingViewNames:r=new Set}){const[i,a]=b.useState(!1),s=CPe(),{createMcpView:o,createOpenaiView:u,generateMcpUploadUrl:c,generateOpenaiUploadUrl:d}=NPe(),{serversByName:f}=bK({isAuthenticated:e,workspaceId:t}),{createServer:p}=ePt(),m=b.useCallback(async S=>{const w=f.get(S);if(w)return w;if(!t)throw new Error("No workspace selected");return await p({workspaceId:t,name:S,enabled:!0,transportType:"http"})},[f,t,p]),y=b.useCallback(async(S,w)=>{const T=w==="mcp-apps"?await c({}):await d({}),N=new Blob([JSON.stringify(S)],{type:"application/json"}),E=await fetch(T,{method:"POST",body:N});if(!E.ok)throw new Error("Failed to upload output blob");return(await E.json()).storageId},[c,d]),v=b.useCallback(async(S,w)=>{const T=w==="mcp-apps"?await c({}):await d({}),N=new Blob([S],{type:"text/html"}),E=await fetch(T,{method:"POST",body:N});if(!E.ok)throw new Error("Failed to upload widget HTML blob");return(await E.json()).storageId},[c,d]),x=b.useCallback(async(S,w)=>{if(!t)return Pe.error("No workspace selected"),null;if(!w.name.trim())return Pe.error("View name is required"),null;a(!0);try{const T=S.uiType===bn.OPENAI_SDK?"openai-apps":"mcp-apps",N=await m(n),E=await y(S.output,T);let A;S.widgetHtml&&(A=await v(S.widgetHtml,T));const I={workspaceId:t,serverId:N,name:w.name.trim(),description:w.description,toolName:S.toolName,toolState:S.state,toolInput:S.input,toolOutputBlobId:E,toolErrorText:S.errorText,prefersBorder:w.prefersBorder,tags:w.tags,category:w.category,defaultContext:w.defaultContext,toolMetadata:S.toolMetadata};let M;if(T==="mcp-apps"){const $=S.widgetDebugInfo?.csp,O=$?{connectDomains:$.connectDomains,resourceDomains:$.resourceDomains,frameDomains:$.frameDomains,baseUriDomains:$.baseUriDomains}:void 0;M=await o({...I,resourceUri:S.resourceUri||`mcp://${n}/${S.toolName}`,toolsMetadata:S.toolsMetadata,widgetCsp:O,widgetPermissions:S.widgetPermissions,widgetPermissive:S.widgetPermissive,widgetHtmlBlobId:A})}else M=await u({...I,outputTemplate:S.outputTemplate||"",serverInfo:S.serverInfo,widgetHtmlBlobId:A});return Pe.success(`View "${w.name}" saved successfully`),M}catch(T){console.error("Failed to save view:",T);const N=T instanceof Error?T.message:"Failed to save view";return Pe.error(N),null}finally{a(!1)}},[t,n,m,y,v,o,u]),_=b.useCallback(async S=>{const w=`${n}-${S.toolName}`,T=tPt(w,r);return x(S,{name:T,defaultContext:s})},[x,n,r,s]);return{saveView:x,saveViewInstant:_,isSaving:i}}function cD({part:e,role:t,onSendFollowUp:n,toolsMetadata:r,toolServerMap:i,onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y,selectedProtocolOverrideIfBothExists:v=bn.OPENAI_SDK,onToolApprovalResponse:x,messageParts:_}){const[S,w]=b.useState(),{isAuthenticated:T}=Ba(),N=ci(),E=Rx(),I=E.workspaces[E.activeWorkspaceId]?.sharedWorkspaceId??null,M=uD(e)||Q1(e)?Qoe(e):null,$=(M?JU(M.toolName,i):void 0)??E.selectedServer??"unknown",{sortedViews:O}=xK({isAuthenticated:T,workspaceId:I}),R=b.useMemo(()=>new Set(O.map(q=>q.name)),[O]),{saveViewInstant:U,isSaving:z}=nPt({isAuthenticated:T,workspaceId:I,serverName:$,existingViewNames:R}),F=uD(e)||Q1(e)?e.toolCallId:void 0,D=bs(q=>F?q.widgets.get(F):void 0),W=b.useCallback((q,X,L,Y,G,P,V,K,Q)=>async()=>{N.capture("save_as_view_clicked",{location:"chat_tool_result",platform:Et(),environment:void 0});const oe={uiType:P,toolName:q,toolCallId:F,input:X,output:L,errorText:Y,state:G,widgetDebugInfo:D?{csp:D.csp,protocol:D.protocol,modelContext:D.modelContext}:void 0,resourceUri:V,outputTemplate:K,toolMetadata:Q,widgetHtml:D?.widgetHtml};await U(oe)},[F,D,U,N]);if(uD(e)||Q1(e)){const q=e,X=M??Qoe(q),L=q.approval?.id,Y=L?{approvalId:L,onApprove:ne=>x?.({id:ne,approved:!0}),onDeny:ne=>x?.({id:ne,approved:!1})}:{},G=r[X.toolName],P=oh(G,X.rawOutput),V=_mt(P,G),K=P===bn.MCP_UI?MRt(X.rawOutput):null,Q=JU(X.toolName,i),oe=X.output!==void 0||X.rawOutput!==void 0||X.toolState==="output-available"||X.toolState==="output-error",re=T&&!!I&&oe;let ee;T?I?oe||(ee="No output to save"):ee="Select a shared workspace to save views":ee="Sign in to save views";const le=X.output??X.rawOutput,te=G?.["openai/outputTemplate"],Z=W(X.toolName,X.input,le,X.errorText,X.toolState==="output-error"?"output-error":"output-available",P||bn.MCP_APPS,V??void 0,te,G);return K?l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y}),l.jsx(QRt,{resource:K.resource,onSendFollowUp:n})]}):P===bn.OPENAI_SDK||P===bn.OPENAI_SDK_AND_MCP_APPS&&v===bn.OPENAI_SDK?X.toolState!=="output-available"&&X.toolState!=="approval-requested"&&X.toolState!=="output-denied"?l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,onSaveView:Z,canSaveView:!1,isSaving:z,...Y}),l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Waiting for tool to finish executing..."})]}):Q?l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,displayMode:m,pipWidgetId:o,fullscreenWidgetId:u,onDisplayModeChange:y,onRequestFullscreen:f,onExitFullscreen:p,onRequestPip:c,onExitPip:d,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y}),l.jsx(vK,{serverId:Q,toolCallId:X.toolCallId,toolName:X.toolName,toolState:X.toolState,toolInput:X.input??null,toolOutput:X.output??null,toolMetadata:r[X.toolName]??void 0,onSendFollowUp:n,onCallTool:(ne,J)=>kne(Q,ne,J),onWidgetStateChange:a,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y})]}):l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y}),l.jsx("div",{className:"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",children:"Failed to load tool server id."})]}):P===bn.MCP_APPS||P===bn.OPENAI_SDK_AND_MCP_APPS&&v===bn.MCP_APPS?!Q||!V||!X.toolCallId?l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y}),l.jsx("div",{className:"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",children:"Failed to load server id or resource uri for MCP App."})]}):l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,displayMode:m,pipWidgetId:o,fullscreenWidgetId:u,onDisplayModeChange:y,onRequestFullscreen:f,onExitFullscreen:p,onRequestPip:c,onExitPip:d,appSupportedDisplayModes:S,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y}),l.jsx(yK,{serverId:Q,toolCallId:X.toolCallId,toolName:X.toolName,toolState:X.toolState,toolInput:X.input,toolOutput:X.output,toolErrorText:X.errorText,resourceUri:V,toolMetadata:G,toolsMetadata:r,onSendFollowUp:n,onCallTool:(ne,J)=>kne(Q,ne,J),onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,displayMode:m,onDisplayModeChange:y,onRequestFullscreen:f,onExitFullscreen:p,onAppSupportedDisplayModesChange:w})]}):l.jsx(Yh,{part:q,uiType:P,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y})}if(DRt(e))return l.jsx(tle,{label:LRt(e.type),value:e.data});switch(e.type){case"text":return l.jsx(JRt,{text:e.text,role:t});case"reasoning":return l.jsx(GRt,{text:e.text,state:e.state});case"file":return l.jsx(ZRt,{part:e});case"source-url":return l.jsx(YRt,{part:e});case"source-document":return l.jsx(XRt,{part:e});case"step-start":return null;default:return l.jsx(tle,{label:"Unknown part",value:e})}}function rPt({message:e,model:t,onSendFollowUp:n,toolsMetadata:r,toolServerMap:i,onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y,selectedProtocolOverrideIfBothExists:v,onToolApprovalResponse:x}){const _=eo(N=>N.themeMode),S=gPe(t,_);if(e.id?.startsWith("widget-state-")||e.id?.startsWith("model-context-"))return null;const w=e.role;if(w!=="user"&&w!=="assistant")return null;if(w==="user"){const N=e.parts?.filter(A=>A.type==="file")??[],E=e.parts?.filter(A=>A.type!=="file")??[];return l.jsxs("div",{className:"flex flex-col items-end gap-2",children:[N.length>0&&l.jsx("div",{className:"flex flex-wrap justify-end gap-2 max-w-3xl",children:N.map((A,I)=>l.jsx(cD,{part:A,role:w,onSendFollowUp:n,toolsMetadata:r,toolServerMap:i,onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y,selectedProtocolOverrideIfBothExists:v},`file-${I}`))}),(E.length>0||N.length===0)&&l.jsx(pRt,{children:E.map((A,I)=>l.jsx(cD,{part:A,role:w,onSendFollowUp:n,toolsMetadata:r,toolServerMap:i,onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y,selectedProtocolOverrideIfBothExists:v},I))})]})}const T=$Rt(e.parts??[]);return l.jsxs("article",{className:"flex gap-4 w-full",children:[l.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border/40 bg-muted/40",children:S?l.jsx("img",{src:S,alt:`${t.id} logo`,className:"h-4 w-4 object-contain"}):l.jsx(Bm,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx("div",{className:"flex-1 min-w-0 space-y-6 text-sm leading-6",children:T.map((N,E)=>l.jsx("div",{className:"space-y-3",children:N.map((A,I)=>l.jsx(cD,{part:A,role:w,onSendFollowUp:n,toolsMetadata:r,toolServerMap:i,onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y,selectedProtocolOverrideIfBothExists:v,onToolApprovalResponse:x,messageParts:e.parts},`${E}-${I}`))},E))})]})}function iPt({model:e}){const t=eo(r=>r.themeMode),n=gPe(e,t);return l.jsxs("article",{className:"flex w-full gap-4 text-sm leading-6 text-muted-foreground","aria-live":"polite","aria-busy":"true",children:[l.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border/40 bg-muted/40",children:n?l.jsx("img",{src:n,alt:`${e.id} logo`,className:"h-4 w-4 object-contain"}):l.jsx(Bm,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx("div",{className:"flex-1 min-w-0",children:l.jsx("div",{className:"inline-flex items-center gap-2 text-muted-foreground/80",children:l.jsxs("span",{className:"text-sm italic",children:["Thinking",l.jsxs("span",{className:"inline-flex",children:[l.jsx("span",{className:"animate-[blink_1.4s_ease-in-out_infinite]",children:"."}),l.jsx("span",{className:"animate-[blink_1.4s_ease-in-out_0.2s_infinite]",children:"."}),l.jsx("span",{className:"animate-[blink_1.4s_ease-in-out_0.4s_infinite]",children:"."})]})]})})})]})}function aPt(e){const n=(Array.isArray(e?.parts)?e.parts:[]).map(r=>!r||typeof r!="object"?"":r.type==="text"&&typeof r.text=="string"||"text"in r&&typeof r.text=="string"?r.text:"").filter(Boolean);return n.length>0?n.join(`
|
|
1769
|
+
</html>`),A.close(),f.current=A.getElementById("middle"),m(!0)};if(N.contentDocument?.readyState==="complete")E();else return N.addEventListener("load",E),()=>N.removeEventListener("load",E)},[_,S,p]),b.useEffect(()=>{!y||!t||x.current||(x.current=!0,console.log("[ChatGPTSandboxedIframe] Sending widget URL to proxy:",t),d.current?.contentWindow?.postMessage({type:"openai:load-widget",url:t,sandbox:n},"*"),setTimeout(()=>r?.(),100))},[y,t,n,r]),b.useEffect(()=>{x.current=!1,v(!1),m(!1)},[t]),l.jsx("iframe",{ref:d,src:"about:blank",sandbox:"allow-scripts allow-same-origin allow-popups allow-popups-to-escape-sandbox allow-forms",allow:"local-network-access *; microphone *; midi *",title:u,className:s,style:o})});function hRt({className:e,...t}){return l.jsx(QKe,{"data-slot":"radio-group",className:Ie("grid gap-3",e),...t})}function mRt({className:e,...t}){return l.jsx(eZe,{"data-slot":"radio-group-item",className:Ie("border-input text-primary focus-visible:border-ring focus-visible:ring-ring/50 aria-invalid:ring-destructive/20 dark:aria-invalid:ring-destructive/40 aria-invalid:border-destructive dark:bg-input/30 aspect-square size-4 shrink-0 rounded-full border shadow-xs transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50",e),...t,children:l.jsx(tZe,{"data-slot":"radio-group-indicator",className:"relative flex items-center justify-center",children:l.jsx(zm,{className:"fill-primary absolute top-1/2 left-1/2 size-2 -translate-x-1/2 -translate-y-1/2"})})})}function gF(e,t){const n=typeof e=="number"?e:Number(e);if(!Number.isFinite(n))return String(e??"");const r=(t||"USD").toUpperCase();try{return new Intl.NumberFormat(void 0,{style:"currency",currency:r}).format(n/100)}catch{return`${n/100} ${r}`}}const am={success:{number:"4242424242424242",behavior:{behavior:"success"}},decline_generic:{number:"4000000000000002",behavior:{behavior:"decline",errorCode:"payment_declined",errorMessage:"Your card was declined."}},decline_insufficient:{number:"4000000000009995",behavior:{behavior:"insufficient_funds",errorCode:"payment_declined",errorMessage:"Insufficient funds."}},decline_expired:{number:"4000000000000069",behavior:{behavior:"expired",errorCode:"payment_declined",errorMessage:"Card has expired."}},requires_3ds:{number:"4000000000003155",behavior:{behavior:"3ds",errorCode:"requires_3ds",errorMessage:"3D Secure required."}},processing_error:{number:"4000000000000119",behavior:{behavior:"processing_error",errorMessage:"Processing error occurred."}}};function gRt(e){const t=e.replace(/\s/g,"");for(const n of Object.values(am))if(n.number===t)return n.behavior;return null}const vRt={none:{label:"Normal",description:"Use card behavior"},network_timeout:{label:"Timeout",description:"10s network timeout"},server_error:{label:"500 Error",description:"Server error"},slow_response:{label:"Slow",description:"5s delay"}},Yoe=[{key:"success",label:"Success",number:am.success.number,icon:"✓"},{key:"decline",label:"Decline",number:am.decline_generic.number,icon:"✗"},{key:"insufficient",label:"Insufficient",number:am.decline_insufficient.number,icon:"$"},{key:"3ds",label:"",number:am.requires_3ds.number,icon:"3DS"},{key:"expired",label:"Expired",number:am.decline_expired.number,icon:"⏱"},{key:"error",label:"Error",number:am.processing_error.number,icon:"⚠"}];function Xoe(e){return e.replace(/\D/g,"").slice(0,16).replace(/(\d{4})(?=\d)/g,"$1 ")}function yRt(e){const t=e.replace(/\D/g,"").slice(0,4);return t.length>=2?`${t.slice(0,2)}/${t.slice(2)}`:t}function xRt(e,t){try{const n=new Date(e),r=new Date(t),i={month:"short",day:"numeric"},a=n.toLocaleDateString("en-US",i),s=r.toLocaleDateString("en-US",i);return a===s?a:`${a} - ${s}`}catch{return""}}function bRt({onClick:e,disabled:t}){return l.jsxs("button",{onClick:e,disabled:t,className:"w-full h-11 bg-black hover:bg-black/90 disabled:bg-black/50 text-white rounded-full flex items-center justify-center gap-1.5 transition-colors",children:[l.jsx("svg",{viewBox:"0 0 24 24",className:"h-5 w-5 fill-current",children:l.jsx("path",{d:"M17.05 20.28c-.98.95-2.05.8-3.08.35-1.09-.46-2.09-.48-3.24 0-1.44.62-2.2.44-3.06-.35C2.79 15.25 3.51 7.59 9.05 7.31c1.35.07 2.29.74 3.08.8 1.18-.24 2.31-.93 3.57-.84 1.51.12 2.65.72 3.4 1.8-3.12 1.87-2.38 5.98.48 7.13-.57 1.5-1.31 2.99-2.54 4.09l.01-.01zM12.03 7.25c-.15-2.23 1.66-4.07 3.74-4.25.29 2.58-2.34 4.5-3.74 4.25z"})}),l.jsx("span",{className:"font-medium",children:"Pay"})]})}function _Rt({onClick:e,disabled:t}){return l.jsxs("button",{onClick:e,disabled:t,className:"w-full h-11 bg-white hover:bg-gray-50 disabled:bg-gray-100 border border-gray-300 rounded-full flex items-center justify-center gap-1.5 transition-colors",children:[l.jsxs("svg",{viewBox:"0 0 24 24",className:"h-5 w-5",children:[l.jsx("path",{fill:"#4285F4",d:"M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z"}),l.jsx("path",{fill:"#34A853",d:"M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z"}),l.jsx("path",{fill:"#FBBC05",d:"M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z"}),l.jsx("path",{fill:"#EA4335",d:"M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z"})]}),l.jsx("span",{className:"font-medium text-gray-700",children:"Pay"})]})}function wRt({option:e,selected:t,onSelect:n,currency:r}){const i=e.type==="shipping";return l.jsx("div",{onClick:n,className:`rounded-xl border-2 p-4 cursor-pointer transition-all ${t?"border-black bg-gray-50":"border-gray-200 hover:border-gray-300"}`,children:l.jsxs("div",{className:"flex items-start gap-3",children:[l.jsx("div",{className:`rounded-full p-2 ${t?"bg-black text-white":"bg-gray-100"}`,children:i?l.jsx(net,{className:"h-4 w-4"}):l.jsx(yet,{className:"h-4 w-4"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center justify-between gap-2",children:[l.jsx("span",{className:"font-medium",children:e.title}),l.jsx("span",{className:"font-medium tabular-nums",children:e.total===0?"FREE":gF(e.total,r)})]}),e.subtitle&&l.jsx("div",{className:"text-sm text-gray-500 mt-0.5",children:e.subtitle}),i&&"carrier_info"in e&&l.jsxs("div",{className:"text-sm text-gray-500 mt-1",children:[l.jsx("span",{children:e.carrier_info}),e.earliest_delivery_time&&e.latest_delivery_time&&l.jsxs("span",{className:"ml-2",children:["Est."," ",xRt(e.earliest_delivery_time,e.latest_delivery_time)]})]})]}),l.jsx(mRt,{value:e.id,checked:t,className:"mt-1"})]})})}function SRt({open:e,onOpenChange:t,checkoutSession:n,checkoutCallId:r,onRespond:i,serverInfo:a,onCallTool:s}){const[o,u]=b.useState("payment"),[c,d]=b.useState(""),[f,p]=b.useState(""),[m,y]=b.useState(""),[v,x]=b.useState(""),[_,S]=b.useState(""),[w,T]=b.useState({}),[N,E]=b.useState(null),[A,I]=b.useState(null),[M,$]=b.useState(null),[O,R]=b.useState(n),[U,z]=b.useState(null),[F,D]=b.useState(!1),[W,q]=b.useState(!1),[X,L]=b.useState("none"),[Y,G]=b.useState(!1),[P,V]=b.useState(null);b.useEffect(()=>{if(n){R(n);const ce=n.fulfillment_options;n.fulfillment_option_id?z(n.fulfillment_option_id):ce?.length===1?z(ce[0].id):z(null)}},[n]);const K=b.useCallback(()=>{u("payment"),d(""),p(""),y(""),x(""),S(""),T({}),E(null),I(null),$(null),z(null),D(!1),q(!1),L("none"),V(null),G(!1)},[]),Q=b.useCallback(async()=>{if(!(!O||r==null))if(q(!0),E(null),s)try{const Te=await s("cancel_checkout",{checkout_session_id:O.id});if(Te?.isError||Te?.error){const we=typeof Te.error=="string"?Te.error:"Failed to cancel checkout";E(we),q(!1);return}i({error:"Checkout canceled"}),K(),t(!1)}catch(ce){const Te=ce instanceof Error?ce.message:"Cancel failed";E(Te),q(!1)}else i({error:"Checkout canceled"}),K(),t(!1)},[O,r,s,i,K,t]),oe=b.useCallback(async ce=>{if(!O||!s)return!1;D(!0),E(null);try{const we=await s("update_checkout",{checkout_session_id:O.id,...ce});if(we?.isError||we?.error){const Ue=typeof we.error=="string"?we.error:"Failed to update checkout";return E(Ue),D(!1),!1}const Oe=we?.structuredContent?.checkout_session||we?.checkout_session;return Oe&&R(Oe),D(!1),!0}catch(Te){const we=Te instanceof Error?Te.message:"Update failed";return E(we),D(!1),!1}},[O,s]);b.useEffect(()=>{O?.id&&(K(),z(O.fulfillment_option_id??null))},[O?.id,K]);const re=b.useCallback(ce=>{ce||(r!=null&&(o==="payment"||o==="card_entry"||o==="fulfillment")&&i({error:"Checkout canceled"}),K()),t(ce)},[r,o,i,t,K]),ee=b.useMemo(()=>{if(!O)return!1;const ce=O.fulfillment_options;return!ce||ce.length===0||ce.length===1&&O.fulfillment_option_id?!1:ce.length>1&&!U},[O,U]),le=b.useMemo(()=>{if(!O)return null;const ce=[...O.totals||[]];if(U&&O.fulfillment_options){const Te=O.fulfillment_options.find(we=>we.id===U);if(Te){const we=ce.findIndex(Ue=>Ue.type==="fulfillment");we>=0&&(ce[we]={...ce[we],amount:Te.total});const Oe=ce.findIndex(Ue=>Ue.type==="total");if(Oe>=0){const Ue=ce.filter(be=>be.type!=="total"&&be.type!=="items_discount"&&be.type!=="discount").reduce((be,je)=>be+je.amount,0),Me=ce.filter(be=>be.type==="items_discount"||be.type==="discount").reduce((be,je)=>be+je.amount,0);ce[Oe]={...ce[Oe],amount:Ue-Me}}}}return ce},[O,U]),te=b.useMemo(()=>le?.find(ce=>ce.type==="total")?.amount??0,[le]),Z=b.useCallback(async()=>{if(!U){E("Please select a shipping method");return}E(null),!(s&&O&&!await oe({fulfillment_option_id:U}))&&u("payment")},[U,s,O,oe]),ne=b.useCallback(ce=>{d(Xoe(ce)),p("12/29"),y("123"),v||x("Test User")},[v]),J=b.useCallback(()=>{const ce=c.replace(/\s/g,"");if(ce.length!==16){E("Please enter a valid 16-digit card number");return}if(f.length!==5){E("Please enter a valid expiry date (MM/YY)");return}if(m.length<3){E("Please enter a valid CVC");return}if(!v.trim()){E("Please enter the cardholder name");return}let Te="Card";ce.startsWith("4")?Te="Visa":ce.startsWith("5")?Te="Mastercard":ce.startsWith("3")&&(Te="Amex"),V({last4:ce.slice(-4),brand:Te}),E(null),u("payment")},[c,f,m,v]),se=b.useCallback(async()=>{if(!O||r==null)return;if(ee&&!U){u("fulfillment");return}if(!P){u("card_entry");return}const ce=c.replace(/\s/g,"");if(E(null),I(null),u("processing"),X!=="none"){if(X==="network_timeout"){await new Promise(Xe=>setTimeout(Xe,1e4)),E("Network timeout: Request timed out after 10 seconds"),u("error");return}if(X==="server_error"){await new Promise(Xe=>setTimeout(Xe,500)),E("Server error (500): Internal server error occurred"),u("error");return}X==="slow_response"&&await new Promise(Xe=>setTimeout(Xe,5e3))}const Te=`tok_${Date.now()}_${ce.slice(-4)}`,we=O.payment_provider?.provider||"stripe",Oe={name:v.trim(),email:_.trim()||void 0},Ue=w.line1&&w.city&&w.postal_code&&w.country,Me={token:Te,provider:we,billing_address:Ue?w:void 0},be=gRt(ce);if(await new Promise(Xe=>setTimeout(Xe,1500)),(be?.behavior==="decline"||be?.behavior==="insufficient_funds"||be?.behavior==="expired"||be?.behavior==="processing_error"||be?.behavior==="3ds")&&be){const Xe=be.errorCode??null,ue=be.errorMessage??"Payment failed.";I(Xe),E(ue),u("error");return}if(s)try{const ue=await s("complete_checkout",{checkout_session_id:O.id,buyer:Oe,payment_data:Me,fulfillment_option_id:U});if(ue?.isError||ue?.error){const xe=typeof ue.error=="string"?ue.error:"Payment processing failed";E(xe),u("error");return}const fe=ue?.structuredContent;if(fe?.checkout_session&&fe?.order){$(fe),u("success");return}if(ue?.checkout_session&&ue?.order){$(ue),u("success");return}$({checkout_session:{...O,status:"completed",buyer:Oe,fulfillment_option_id:U??void 0},order:{id:`order_${Date.now()}`,checkout_session_id:O.id,permalink_url:""}}),u("success")}catch(Xe){const ue=Xe instanceof Error?Xe.message:"Payment failed";E(ue),u("error")}else $({checkout_session:{...O,status:"completed",buyer:Oe,fulfillment_option_id:U??void 0},order:{id:`order_${Date.now()}`,checkout_session_id:O.id,permalink_url:""}}),u("success")},[O,r,c,v,_,w,s,U,X,P,ee]),ie=b.useCallback(()=>{M&&i({result:M}),K(),t(!1)},[M,i,K,t]),he=b.useCallback(()=>{E(null),I(null),u("payment")},[]),ye=O?.links?.find(ce=>ce.type==="terms_of_service"),Ne=O?.links?.find(ce=>ce.type==="privacy_policy");return l.jsx(si,{open:e,onOpenChange:re,children:l.jsxs(oi,{className:"sm:max-w-[400px] p-0 gap-0 overflow-hidden rounded-2xl",children:[o==="payment"&&O&&l.jsxs("div",{className:"flex flex-col",children:[l.jsx("div",{className:"flex items-center gap-3 p-6 pb-4",children:l.jsx("span",{className:"text-xl font-semibold",children:"Payment"})}),l.jsx("div",{className:"px-6 pb-4",children:l.jsxs("button",{onClick:()=>u("card_entry"),className:"w-full flex items-center justify-between p-4 rounded-xl border border-gray-200 hover:border-gray-300 transition-colors",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("div",{className:"w-10 h-6 bg-gradient-to-r from-blue-600 to-blue-700 rounded flex items-center justify-center",children:l.jsx("span",{className:"text-white text-xs font-bold",children:P?.brand==="Visa"?"VISA":P?.brand==="Mastercard"?"MC":"💳"})}),P?l.jsxs("span",{className:"text-gray-900",children:[P.brand," ****",P.last4]}):l.jsx("span",{className:"text-gray-500",children:"Add payment method"})]}),l.jsx(wr,{className:"h-5 w-5 text-gray-400"})]})}),l.jsx("div",{className:"px-6 pb-6",children:l.jsxs("div",{className:"flex items-center justify-between py-3 border-t border-gray-100",children:[l.jsx("span",{className:"text-gray-500",children:"Total"}),l.jsx("span",{className:"text-xl font-semibold tabular-nums",children:gF(te,O.currency)})]})}),l.jsx("div",{className:"px-6 pb-4",children:l.jsx(Ee,{onClick:se,disabled:!P||W||F,className:"w-full h-12 rounded-full bg-black hover:bg-gray-800 text-white font-medium text-base",children:W?l.jsxs(l.Fragment,{children:[l.jsx(Pn,{className:"h-4 w-4 animate-spin mr-2"}),"Canceling..."]}):F?l.jsxs(l.Fragment,{children:[l.jsx(Pn,{className:"h-4 w-4 animate-spin mr-2"}),"Updating..."]}):"Pay"})}),l.jsxs("div",{className:"px-6 pb-4 space-y-2",children:[l.jsx(bRt,{onClick:se,disabled:!P||W||F}),l.jsx(_Rt,{onClick:se,disabled:!P||W||F}),l.jsx("button",{onClick:()=>u("card_entry"),className:"w-full h-11 border border-gray-200 hover:border-gray-300 rounded-full text-gray-700 font-medium transition-colors",children:"Pay with card"})]}),l.jsx("div",{className:"px-6 pb-2",children:l.jsxs("button",{onClick:()=>G(!Y),className:"flex items-center gap-1 text-xs text-gray-400 hover:text-gray-600 transition-colors",children:[Y?l.jsx(Ex,{className:"h-3 w-3"}):l.jsx(Wr,{className:"h-3 w-3"}),"Dev Tools"]})}),Y&&l.jsx("div",{className:"px-6 pb-4 space-y-3",children:l.jsxs("div",{className:"rounded-lg bg-gray-50 p-3 space-y-3",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-xs font-medium text-gray-600",children:"Quick fill test card:"}),l.jsx("div",{className:"grid grid-cols-3 gap-1.5",children:Yoe.map(ce=>l.jsxs("button",{onClick:()=>{ne(ce.number);let Te="Card";ce.number.startsWith("4")?Te="Visa":ce.number.startsWith("5")&&(Te="Mastercard"),V({last4:ce.number.slice(-4),brand:Te})},className:`px-2 py-1.5 text-xs rounded-md border transition-colors ${P?.last4===ce.number.slice(-4)?"bg-black text-white border-black":"bg-white border-gray-200 hover:border-gray-300"}`,children:[l.jsx("span",{className:"mr-1",children:ce.icon}),ce.label]},ce.key))})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("div",{className:"text-xs font-medium text-gray-600",children:"Simulate error:"}),l.jsx("select",{value:X,onChange:ce=>L(ce.target.value),className:"w-full text-xs px-3 py-2 rounded-md border border-gray-200 bg-white",children:Object.entries(vRt).map(([ce,{label:Te,description:we}])=>l.jsxs("option",{value:ce,children:[Te," - ",we]},ce))})]}),l.jsx("button",{onClick:Q,disabled:W,className:"w-full text-xs py-2 text-red-600 hover:text-red-700 border border-red-200 rounded-md hover:bg-red-50 transition-colors",children:W?"Canceling...":"Cancel Checkout"})]})}),N&&l.jsx("div",{className:"px-6 pb-4",children:l.jsxs("div",{className:"rounded-lg bg-red-50 border border-red-100 px-4 py-3 text-sm text-red-600 flex items-center gap-2",children:[l.jsx(Gs,{className:"h-4 w-4 flex-shrink-0"}),N]})}),l.jsxs("div",{className:"px-6 py-4 bg-gray-50 text-center space-y-2",children:[l.jsxs("p",{className:"text-xs text-gray-500",children:["By clicking Pay, you agree to the"," ",ye?l.jsx("a",{href:ye.url,target:"_blank",rel:"noreferrer",className:"underline",children:"Terms"}):l.jsx("span",{className:"underline",children:"Terms"})," ","and"," ",Ne?l.jsx("a",{href:Ne.url,target:"_blank",rel:"noreferrer",className:"underline",children:"Privacy Policy"}):l.jsx("span",{className:"underline",children:"Privacy Policy"})]}),l.jsx("p",{className:"text-xs text-gray-400",children:"OpenAI does not process your order, collect payment, or handle fulfillment."})]})]}),o==="card_entry"&&O&&l.jsxs("div",{className:"flex flex-col",children:[l.jsx("div",{className:"flex items-center justify-between p-6 pb-4",children:l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("button",{onClick:()=>u("payment"),className:"p-1 -ml-1 rounded-full hover:bg-gray-100 transition-colors",children:l.jsx(wr,{className:"h-5 w-5 text-gray-900 rotate-180"})}),l.jsx("span",{className:"text-lg font-semibold",children:"Add payment method"})]})}),l.jsxs("div",{className:"px-6 pb-6 space-y-5",children:[l.jsxs("div",{className:"border border-gray-200 rounded-xl overflow-hidden",children:[l.jsxs("div",{className:"flex items-center gap-2 px-4 py-3 border-b border-gray-200",children:[l.jsx(eJe,{className:"h-5 w-5 text-gray-600"}),l.jsx("span",{className:"font-medium text-gray-900",children:"Card"})]}),l.jsxs("div",{className:"bg-gray-50/50",children:[l.jsxs("div",{className:"relative border-b border-gray-200",children:[l.jsx(Ct,{id:"cardNumber",placeholder:"Card number",value:c,onChange:ce=>d(Xoe(ce.target.value)),className:"h-12 pr-36 border-0 rounded-none bg-transparent font-mono text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"cc-number"}),l.jsxs("div",{className:"absolute right-3 top-1/2 -translate-y-1/2 flex items-center gap-1",children:[l.jsx("img",{src:"https://js.stripe.com/v3/fingerprinted/img/visa-729c05c240c4bdb47b03ac81d9945bfe.svg",alt:"Visa",className:"h-6"}),l.jsx("img",{src:"https://js.stripe.com/v3/fingerprinted/img/mastercard-4d8844094130711885b5e41b28c9848f.svg",alt:"Mastercard",className:"h-6"}),l.jsx("img",{src:"https://js.stripe.com/v3/fingerprinted/img/amex-a49b82f46c5cd6a96a6e418a6ca1717c.svg",alt:"Amex",className:"h-6"}),l.jsx("img",{src:"https://js.stripe.com/v3/fingerprinted/img/discover-ac52cd46f89fa40a29a0bfb954e33173.svg",alt:"Discover",className:"h-6"})]})]}),l.jsxs("div",{className:"flex",children:[l.jsx("div",{className:"flex-1 border-r border-gray-200",children:l.jsx(Ct,{id:"expiry",placeholder:"Expiration date",value:f,onChange:ce=>p(yRt(ce.target.value)),className:"h-12 border-0 rounded-none bg-transparent font-mono text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"cc-exp"})}),l.jsxs("div",{className:"flex-1 relative",children:[l.jsx(Ct,{id:"cvc",placeholder:"Security code",value:m,onChange:ce=>y(ce.target.value.replace(/\D/g,"").slice(0,4)),className:"h-12 pr-12 border-0 rounded-none bg-transparent font-mono text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"cc-csc"}),l.jsx("div",{className:"absolute right-3 top-1/2 -translate-y-1/2",children:l.jsxs("svg",{viewBox:"0 0 32 21",className:"h-5 w-8 text-gray-400",children:[l.jsx("rect",{x:"0",y:"0",width:"32",height:"21",rx:"3",fill:"none",stroke:"currentColor",strokeWidth:"2"}),l.jsx("rect",{x:"20",y:"4",width:"8",height:"5",rx:"1",fill:"currentColor",opacity:"0.6"}),l.jsx("text",{x:"21",y:"17",fontSize:"7",fill:"currentColor",fontFamily:"monospace",children:"123"})]})})]})]})]})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsx("div",{className:"font-medium text-gray-900",children:"Billing address"}),l.jsxs("div",{className:"border border-gray-200 rounded-xl overflow-hidden",children:[l.jsxs("div",{className:"relative border-b border-gray-200",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"Full name"}),l.jsx(Ct,{id:"cardholderName",placeholder:"",value:v,onChange:ce=>x(ce.target.value),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"cc-name"})]}),l.jsxs("div",{className:"relative border-b border-gray-200",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"Address line 1"}),l.jsx(Ct,{placeholder:"",value:w.line1||"",onChange:ce=>T(Te=>({...Te,line1:ce.target.value})),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"address-line1"})]}),l.jsxs("div",{className:"relative border-b border-gray-200",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"Address line 2"}),l.jsx(Ct,{placeholder:"",value:w.line2||"",onChange:ce=>T(Te=>({...Te,line2:ce.target.value})),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"address-line2"})]}),l.jsxs("div",{className:"relative border-b border-gray-200",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"City"}),l.jsx(Ct,{placeholder:"",value:w.city||"",onChange:ce=>T(Te=>({...Te,city:ce.target.value})),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"address-level2"})]}),l.jsxs("div",{className:"flex border-b border-gray-200",children:[l.jsxs("div",{className:"flex-1 relative border-r border-gray-200",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"State"}),l.jsx(Ct,{placeholder:"",value:w.state||"",onChange:ce=>T(Te=>({...Te,state:ce.target.value})),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"address-level1"})]}),l.jsxs("div",{className:"flex-1 relative",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"ZIP code"}),l.jsx(Ct,{placeholder:"",value:w.postal_code||"",onChange:ce=>T(Te=>({...Te,postal_code:ce.target.value})),className:"h-14 pt-5 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0",autoComplete:"postal-code"})]})]}),l.jsxs("div",{className:"relative",children:[l.jsx("label",{className:"absolute left-3 top-2 text-xs text-gray-500",children:"Phone number"}),l.jsxs("div",{className:"flex items-center h-14 pt-3",children:[l.jsxs("div",{className:"flex items-center gap-1 pl-3 pr-2 text-gray-600",children:[l.jsx("span",{className:"text-sm",children:"🇺🇸"}),l.jsx("span",{className:"text-sm",children:"+1"}),l.jsx(Wr,{className:"h-3 w-3"})]}),l.jsx(Ct,{placeholder:"",value:w.phone||"",onChange:ce=>T(Te=>({...Te,phone:ce.target.value})),className:"h-10 border-0 rounded-none text-base focus-visible:ring-0 focus-visible:ring-offset-0 pl-0",autoComplete:"tel"})]})]})]})]}),l.jsxs("div",{className:"rounded-lg bg-amber-50 border border-amber-100 p-3",children:[l.jsx("div",{className:"text-xs font-medium text-amber-700 mb-2",children:"Quick fill test card:"}),l.jsx("div",{className:"flex flex-wrap gap-1.5",children:Yoe.slice(0,4).map(ce=>l.jsxs("button",{onClick:()=>ne(ce.number),className:"px-2 py-1 text-xs rounded border border-amber-200 bg-white hover:bg-amber-50 transition-colors",children:[ce.icon," ",ce.label]},ce.key))})]}),N&&l.jsxs("div",{className:"rounded-lg bg-red-50 border border-red-100 px-4 py-3 text-sm text-red-600 flex items-center gap-2",children:[l.jsx(Gs,{className:"h-4 w-4 flex-shrink-0"}),N]}),l.jsx(Ee,{onClick:J,className:"w-full h-12 rounded-full bg-black hover:bg-gray-800 text-white font-medium",children:"Continue"})]})]}),o==="fulfillment"&&O&&l.jsxs("div",{className:"flex flex-col",children:[l.jsxs("div",{className:"flex items-center gap-3 p-6 pb-4",children:[l.jsx("button",{onClick:()=>u("payment"),className:"p-1.5 -ml-1.5 rounded-full hover:bg-gray-100 transition-colors",children:l.jsx(wr,{className:"h-5 w-5 text-gray-500 rotate-180"})}),l.jsx("span",{className:"text-xl font-semibold",children:"Shipping"})]}),l.jsxs("div",{className:"px-6 pb-6 space-y-4",children:[l.jsx(hRt,{value:U??"",onValueChange:z,className:"space-y-3",children:O.fulfillment_options?.map(ce=>l.jsx(wRt,{option:ce,selected:U===ce.id,onSelect:()=>z(ce.id),currency:O.currency},ce.id))}),N&&l.jsxs("div",{className:"rounded-lg bg-red-50 border border-red-100 px-4 py-3 text-sm text-red-600 flex items-center gap-2",children:[l.jsx(Gs,{className:"h-4 w-4 flex-shrink-0"}),N]}),l.jsxs("div",{className:"flex items-center justify-between pt-2 border-t",children:[l.jsx("span",{className:"text-gray-500",children:"Total"}),l.jsx("span",{className:"text-xl font-semibold tabular-nums",children:gF(te,O.currency)})]}),l.jsx(Ee,{onClick:Z,disabled:F||!U,className:"w-full h-12 rounded-full bg-black hover:bg-gray-800 text-white font-medium",children:F?l.jsxs(l.Fragment,{children:[l.jsx(Pn,{className:"h-4 w-4 animate-spin mr-2"}),"Updating..."]}):"Continue"})]})]}),o==="processing"&&l.jsxs("div",{className:"flex flex-col items-center justify-center py-16 px-6",children:[l.jsx(Pn,{className:"h-10 w-10 animate-spin text-gray-400 mb-4"}),l.jsx("div",{className:"text-lg font-medium text-gray-900",children:"Processing payment..."}),l.jsx("div",{className:"text-sm text-gray-500 mt-1",children:s?"Completing checkout...":"Please wait..."})]}),o==="success"&&M&&l.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6",children:[l.jsx("div",{className:"rounded-full bg-green-100 p-4 mb-4",children:l.jsx(ko,{className:"h-10 w-10 text-green-600"})}),l.jsx("div",{className:"text-xl font-semibold text-gray-900 mb-1",children:"Payment successful"}),l.jsxs("div",{className:"text-sm text-gray-500 mb-6",children:["Order #",M.order.id.slice(-8)]}),l.jsx(Ee,{onClick:ie,className:"w-full h-12 rounded-full bg-black hover:bg-gray-800 text-white font-medium",children:"Done"})]}),o==="error"&&l.jsxs("div",{className:"flex flex-col items-center justify-center py-12 px-6",children:[l.jsx("div",{className:"rounded-full bg-red-100 p-4 mb-4",children:l.jsx(Gs,{className:"h-10 w-10 text-red-600"})}),l.jsx("div",{className:"text-xl font-semibold text-gray-900 mb-1",children:"Payment failed"}),A&&l.jsx(Cn,{variant:"outline",className:"mb-2 text-xs bg-red-50 border-red-200 text-red-600",children:A}),l.jsx("div",{className:"text-sm text-gray-500 text-center mb-6",children:N||"An error occurred during payment processing."}),l.jsxs("div",{className:"flex gap-3 w-full",children:[l.jsx(Ee,{variant:"outline",onClick:()=>{i({error:N||"Payment failed"}),K(),t(!1)},className:"flex-1 h-12 rounded-full",children:"Cancel"}),l.jsx(Ee,{onClick:he,className:"flex-1 h-12 rounded-full bg-black hover:bg-gray-800 text-white",children:"Try again"})]})]})]})})}function kRt(e){if(!e||typeof e!="string")return null;const t={},n=e.matchAll(/(\w+)="([^"]+)"/g);for(const r of n){const[,i,a]=r;i==="realm"?t.realm=a:i==="error"?t.error=a:i==="error_description"&&(t.errorDescription=a)}return Object.keys(t).length>0?t:null}function Joe(e,t){const n=kRt(e);console.warn(`[OAuth Challenge] Tool "${t}" requires authentication`,n?{realm:n.realm,error:n.error,description:n.errorDescription}:{raw:e}),n?.error||n?.errorDescription?Pe.warning(`OAuth Required: ${n.errorDescription||n.error||"Authentication required"}`,{description:`Tool "${t}" needs authentication. Configure OAuth in server settings.`,duration:8e3}):Pe.warning(`OAuth Required for "${t}"`,{description:"The tool requires authentication. Configure OAuth in server settings.",duration:8e3})}function ERt(e,t,n,r,i){const a=b.useMemo(()=>e??`${t||"chatgpt-app"}-${Date.now()}`,[e,t]),s=b.useMemo(()=>i?.["openai/outputTemplate"],[i]),o=b.useMemo(()=>r&&typeof r=="object"&&r!==null&&"structuredContent"in r?r.structuredContent:null,[r]),u=b.useMemo(()=>{if(r&&typeof r=="object"&&r!==null){if("_meta"in r)return r._meta;if("meta"in r)return r.meta}return null},[r]),c=b.useMemo(()=>n??{},[n]),d=b.useMemo(()=>o??r??null,[o,r]);return{resolvedToolCallId:a,outputTemplate:s,toolResponseMetadata:u,resolvedToolInput:c,resolvedToolOutput:d}}function TRt(){const e=window.innerWidth;return e<768?"mobile":e<1024?"tablet":"desktop"}let mN=null,gN=null;const NRt={hover:!0,touch:!1},CRt={top:0,bottom:0,left:0,right:0};async function ARt(){return mN||gN||(gN=(async()=>{try{const e=await fetch("http://ip-api.com/json/?fields=status,country,regionName,city",{signal:AbortSignal.timeout(3e3)});if(!e.ok)return null;const t=await e.json();return t.status!=="success"?null:(mN={country:t.country||"",region:t.regionName||"",city:t.city||""},mN)}catch(e){return console.debug("[OpenAI SDK] IP geolocation unavailable:",e),null}})(),gN)}function IRt(e,t,n,r,i,a,s,o,u,c,d,f,p,m,y,v,x,_){const[S,w]=b.useState(null),[T,N]=b.useState(!1),[E,A]=b.useState(null),[I,M]=b.useState(!1),[$,O]=b.useState(null),[R,U]=b.useState(d),[z,F]=b.useState(!0),[D,W]=b.useState(!1),q=b.useRef(null),X=b.useRef(null);b.useEffect(()=>{X.current!==null&&X.current!==t&&(w(null),W(!1),q.current=null),X.current=t},[t]),b.useEffect(()=>{D||w(null)},[x,D]);const L=b.useRef(a);L.current=a;const Y=b.useRef(s);Y.current=s;const G=b.useRef(o);G.current=o;const P=b.useRef(y);P.current=y,b.useEffect(()=>{d!==R&&S&&(U(d),w(null))},[d,R,S]);const V=b.useMemo(()=>JSON.stringify({input:a,output:s}),[a,s]),[K,Q]=b.useState(V);return b.useEffect(()=>{const oe=setTimeout(()=>{Q(V)},300);return()=>clearTimeout(oe)},[V]),b.useEffect(()=>{if(e==="output-available"){if(q.current===null){q.current=K;return}q.current!==K&&(q.current=K,n&&r&&!v&&(W(!0),w(null)))}},[e,K,n,r,v]),b.useEffect(()=>{let oe=!1;const re=!!x&&!D,ee=!!n&&!!r,le=S&&(re&&S===x||!re&&S.includes("/api/apps/chatgpt/widget-content/"));if(e!=="output-available"||le||!re&&!ee){S&&M(!1),!re&&!n&&(w(null),O(null),M(!1)),!r&&n&&!re&&(w(null),O("Tool name is required"),M(!1));return}return(async()=>{M(!0),O(null);try{if(x&&!D){oe||(w(x),M(!1));return}if(v){oe||(O("Server offline and no cached widget HTML available"),M(!1));return}const Z=await ARt(),ne=await Yt("/api/apps/chatgpt/widget/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:i,uri:n,toolInput:L.current,toolOutput:Y.current,toolResponseMetadata:G.current,toolId:t,toolName:r,theme:u,locale:c,deviceType:f,userLocation:Z,cspMode:d,capabilities:p,safeAreaInsets:m})});if(!ne.ok)throw new Error(`Failed to store widget data: ${ne.statusText}`);if(oe)return;const J=await fetch(`/api/apps/chatgpt/widget-html/${t}`);if(J.ok){const ie=await J.json();if(ie.csp&&P.current&&P.current({mode:ie.csp.mode,connectDomains:ie.csp.connectDomains,resourceDomains:ie.csp.resourceDomains,frameDomains:ie.csp.frameDomains,headerString:ie.csp.headerString,widgetDeclared:ie.csp.widgetDeclared}),ie.closeWidget){N(!0),A("completed"),M(!1);return}F(ie.prefersBorder??!0)}const se=`/api/apps/chatgpt/widget-content/${t}?csp_mode=${d}`;if(_)try{const ie=await fetch(se);if(ie.ok){const he=await ie.text();_(t,he)}}catch(ie){console.warn("Failed to capture widget HTML for caching:",ie)}w(se)}catch(Z){if(oe)return;console.error("Error storing widget data:",Z),O(Z instanceof Error?Z.message:"Failed to prepare widget")}finally{oe||M(!1)}})(),()=>{oe=!0}},[e,t,S,n,r,i,u,c,d,f,p,m,v,x,_,D]),{widgetUrl:S,widgetClosed:T,widgetClosedReason:E,isStoringWidget:I,storeError:$,setWidgetUrl:w,setWidgetClosed:N,setWidgetClosedReason:A,prefersBorder:z}}function vK({serverId:e,toolCallId:t,toolName:n,toolState:r,toolInput:i,toolOutput:a,toolMetadata:s,onSendFollowUp:o,onCallTool:u,onWidgetStateChange:c,pipWidgetId:d,fullscreenWidgetId:f,onRequestPip:p,onExitPip:m,serverInfo:y,displayMode:v,onDisplayModeChange:x,onRequestFullscreen:_,onExitFullscreen:S,isOffline:w,cachedWidgetHtmlUrl:T,initialWidgetState:N}){const E=b.useRef(null),A=b.useRef(null),I=eo(Ve=>Ve.themeMode),$=Zt(Ve=>Ve.globals.locale)||navigator.language||"en-US",{resolvedToolCallId:O,outputTemplate:R,toolResponseMetadata:U,resolvedToolInput:z,resolvedToolOutput:F}=ERt(t,n,i,a,s),D=v!==void 0,[W,q]=b.useState("inline"),X=D?v:W,L=b.useMemo(()=>D?X==="fullscreen"&&f===O?"fullscreen":X==="pip"&&d===O?"pip":"inline":X,[X,f,D,d,O]),Y=b.useCallback(Ve=>{D?x?.(Ve):q(Ve),Ve==="fullscreen"?_?.(O):X==="fullscreen"&&S?.(O)},[D,x,O,_,S,X]),[G,P]=b.useState(null),[V,K]=b.useState(320),[Q,oe]=b.useState(!1),[re,ee]=b.useState(null),[le,te]=b.useState(!1),[Z,ne]=b.useState({}),[J,se]=b.useState(""),[ie,he]=b.useState(null),[ye,Ne]=b.useState(!1),[ce,Te]=b.useState(null),[we,Oe]=b.useState(null),[Ue,Me]=b.useState("inline"),be=b.useRef(null),[je,Xe]=b.useState(!1),ue=b.useRef(0),[fe,xe]=b.useState(!1),[Ce,He]=b.useState(!1),Ze=Zt(Ve=>Ve.isPlaygroundActive),st=Zt(Ve=>Ve.cspMode),ot=Zt(Ve=>Ve.deviceType),mt=Zt(Ve=>Ve.capabilities),Bt=Zt(Ve=>Ve.safeAreaInsets),Mt=Ze?st:"permissive",It=Ze?ot:TRt(),gn=Ze?mt:NRt,nt=Ze?Bt:CRt,yt=bs(Ve=>Ve.setWidgetCsp),ut=bs(Ve=>Ve.setWidgetHtml),vt=Ze&&It==="mobile",Wt=Ze&&(It==="mobile"||It==="tablet"),Qn=b.useCallback(Ve=>{yt(O,Ve)},[O,yt]),Gi=b.useCallback((Ve,Br)=>{ut(Ve,Br)},[ut]),Pt=L==="fullscreen",sn=L==="pip",Mn=!Pt&&!sn,{widgetUrl:ln,widgetClosed:ir,widgetClosedReason:Ga,isStoringWidget:ja,storeError:Zc,setWidgetClosed:qu,setWidgetClosedReason:Is,prefersBorder:Hu}=IRt(r,O,R,n,e,z,F,U,I,$,Mt,It,gn,nt,Qn,w,T,Gi),Ao=b.useCallback(Ve=>{const Br=Number(Ve);if(!Number.isFinite(Br)||Br<=0)return;const Un=Math.ceil(Br),Yr=Mn?Un+2:Un;if(Yr===ue.current)return;if(ue.current=Yr,K(Xr=>Xr!==Yr?Yr:Xr),Mn){const Xr=typeof G=="number"&&Number.isFinite(G)?Math.min(Yr,G):Yr;E.current?.setHeight?.(Xr)}},[Mn,G]),Ai=b.useMemo(()=>{const Ve=V>0?V:320;return typeof G=="number"&&Number.isFinite(G)?Math.min(Ve,G):Ve},[V,G]),Wa=b.useMemo(()=>Pt?"100%":L==="pip"?vt&&sn?"100%":sn?"400px":`${Ai}px`:`${Ai}px`,[Ai,L,Pt,sn,vt]),hs=b.useMemo(()=>{if(!ln||!le)return null;const Ve=new URL(ln,"http://placeholder");return Ve.searchParams.set("view_mode","modal"),Ve.searchParams.set("view_params",JSON.stringify(Z)),ie&&Ve.searchParams.set("template",ie),Ve.pathname+Ve.search},[ln,le,Z,ie]),vr=km(Ve=>Ve.addLog),Yc=bs(Ve=>Ve.setWidgetDebugInfo),Xl=bs(Ve=>Ve.setWidgetState),ht=bs(Ve=>Ve.setWidgetGlobals),Nt=bs(Ve=>Ve.addCspViolation);b.useEffect(()=>{n&&Yc(O,{toolName:n,protocol:"openai-apps",widgetState:N??null,globals:{theme:I,displayMode:L,maxHeight:G??void 0,locale:$,safeArea:{insets:nt},userAgent:{device:{type:It},capabilities:gn}}})},[O,n,Yc,I,L,G,$,It,gn,nt,N]),b.useEffect(()=>{ht(O,{theme:I,displayMode:L,maxHeight:G??void 0})},[O,I,L,G,ht]),b.useEffect(()=>{if(ue.current=0,xe(!1),He(!1),!!ln&&(K(320),L==="inline")){const Ve=typeof G=="number"&&Number.isFinite(G)?Math.min(320,G):320;E.current?.setHeight?.(Ve)}},[ln,G]),b.useEffect(()=>{!ln||L!=="inline"||!Q||E.current?.postMessage({type:"openai:requestResize"})},[ln,L,Q]),b.useEffect(()=>{L==="inline"&&(!Number.isFinite(Ai)||Ai<=0||(ue.current=Math.round(Ai),E.current?.setHeight?.(Ai)))},[Ai,L]);const Tt=b.useCallback((Ve,Br)=>{vr({widgetId:O,serverId:e,direction:"host-to-ui",protocol:"openai-apps",method:L1(Ve,"openai-apps"),message:Ve}),Br?je&&A.current?.postMessage(Ve):E.current?.postMessage(Ve)},[vr,O,e,je]),Cr=b.useCallback(Ve=>{we!=null&&(Tt({type:"openai:requestCheckout:response",callId:we,...Ve},Ue==="modal"),Oe(null),Te(null),Ne(!1))},[we,Ue,Tt]),vn=b.useCallback(Ve=>{E.current?.postMessage({type:"openai:navigate",direction:Ve,toolId:O})},[O]),yr=b.useCallback(async Ve=>{const Br=Ve.data?.type;switch(vr({widgetId:O,serverId:e,direction:"ui-to-host",protocol:"openai-apps",method:L1(Ve.data,"openai-apps"),message:Ve.data}),Br){case"openai:resize":{Ao(Ve.data.height);break}case"openai:setWidgetState":{if(Ve.data.toolId===O){const Un=Ve.data.state,Yr=Un===null?null:JSON.stringify(Un);Yr!==be.current&&(be.current=Yr,Xl(O,Un),c?.(O,Un))}break}case"openai:callTool":{const Un=Ve.data.callId,Yr=Ve.data.toolName;if(!u){Tt({type:"openai:callTool:response",callId:Un,error:"callTool is not supported in this context"});break}try{const Wi=await u(Yr,Ve.data.args||Ve.data.params||{},Ve.data._meta||{}),Vu=(Wi?._meta||Wi?.meta)?.["mcp/www_authenticate"];Vu&&typeof Vu=="string"&&Joe(Vu,Yr),Tt({type:"openai:callTool:response",callId:Un,result:Wi})}catch(Wi){Tt({type:"openai:callTool:response",callId:Un,error:Wi instanceof Error?Wi.message:"Unknown error"})}break}case"openai:sendFollowup":{if(o&&Ve.data.message){const Un=typeof Ve.data.message=="string"?Ve.data.message:Ve.data.message.prompt||JSON.stringify(Ve.data.message);o(Un)}break}case"openai:requestDisplayMode":{const Un=Ve.data.mode||"inline",Wi=window.innerWidth<768&&Un==="pip"?"fullscreen":Un;Y(Wi),Wi==="pip"?p?.(O):(Wi==="inline"||Wi==="fullscreen")&&d===O&&m?.(O),typeof Ve.data.maxHeight=="number"?P(Ve.data.maxHeight):Ve.data.maxHeight==null&&P(null),Tt({type:"openai:set_globals",globals:{displayMode:Wi}});break}case"openai:requestClose":{qu(!0),Is("closed"),d===O&&m?.(O);break}case"openai:csp-violation":{const{directive:Un,blockedUri:Yr,sourceFile:Wi,lineNumber:Xr,columnNumber:Vu,effectiveDirective:tb,timestamp:Sf}=Ve.data;Nt(O,{directive:Un,effectiveDirective:tb,blockedUri:Yr,sourceFile:Wi,lineNumber:Xr,columnNumber:Vu,timestamp:Sf||Date.now()});break}case"openai:openExternal":{if(Ve.data.href&&typeof Ve.data.href=="string"){const Un=Ve.data.href;if(Un.startsWith("http://localhost")||Un.startsWith("http://127.0.0.1"))break;window.open(Un,"_blank","noopener,noreferrer")}break}case"openai:requestCheckout":{if(typeof Ve.data.callId!="number")break;const Un=Ve.data.session&&typeof Ve.data.session=="object"?Ve.data.session:null;if(!Un)break;if(we!=null){Tt({type:"openai:requestCheckout:response",callId:Ve.data.callId,error:"Another checkout is already in progress"});break}Me("inline"),Oe(Ve.data.callId),Te(Un),Ne(!0);break}case"openai:requestModal":{se(Ve.data.title||"Modal"),ne(Ve.data.params||{}),he(Ve.data.template||null),te(!0);break}case"openai:navigationStateChanged":{Ve.data.toolId===O&&(xe(Ve.data.canGoBack??!1),He(Ve.data.canGoForward??!1));break}}},[u,o,c,O,d,p,m,vr,Tt,e,Xl,Ao,Nt,we,qu,Is]),Ka=b.useCallback(Ve=>{if(Ve.data?.type&&vr({widgetId:O,serverId:e,direction:"ui-to-host",protocol:"openai-apps",method:L1(Ve.data,"openai-apps"),message:Ve.data}),Ve.data?.type==="openai:setWidgetState"&&Ve.data.toolId===O){const Br=Ve.data.state,Un=Br===null?null:JSON.stringify(Br);Un!==be.current&&(be.current=Un,Xl(O,Br),c?.(O,Br))}if(Ve.data?.type==="openai:requestCheckout"){if(typeof Ve.data.callId!="number")return;const Br=Ve.data.session&&typeof Ve.data.session=="object"?Ve.data.session:null;if(!Br)return;if(we!=null){Tt({type:"openai:requestCheckout:response",callId:Ve.data.callId,error:"Another checkout is already in progress"},!0);return}Me("modal"),Oe(Ve.data.callId),Te(Br),Ne(!0)}if(Ve.data?.type==="openai:callTool"){const Br=Ve.data.callId,Un=Ve.data.toolName;if(!u){Tt({type:"openai:callTool:response",callId:Br,error:"callTool is not supported in this context"},!0);return}(async()=>{try{const Yr=await u(Un,Ve.data.args||Ve.data.params||{},Ve.data._meta||{}),Xr=(Yr?._meta||Yr?.meta)?.["mcp/www_authenticate"];Xr&&typeof Xr=="string"&&Joe(Xr,Un),Tt({type:"openai:callTool:response",callId:Br,result:Yr},!0)}catch(Yr){Tt({type:"openai:callTool:response",callId:Br,error:Yr instanceof Error?Yr.message:"Unknown error"},!0)}})()}},[vr,O,e,Xl,c,we,Tt,u]),ms=b.useCallback(()=>{Xe(!0);const Ve={theme:I,displayMode:"inline",maxHeight:null,locale:$,safeArea:{insets:nt},userAgent:{device:{type:It},capabilities:gn},toolInput:z,toolOutput:F};N!==void 0&&(Ve.widgetState=N),A.current?.postMessage({type:"openai:set_globals",globals:Ve})},[I,$,It,gn,nt,z,F,N]);b.useEffect(()=>{le||(Xe(!1),he(null))},[le]),b.useEffect(()=>{!D&&X==="pip"&&d!==O&&Y("inline")},[X,d,O,D,Y]),b.useEffect(()=>{if(!Q)return;const Ve={theme:I,displayMode:L,locale:$,safeArea:{insets:nt},userAgent:{device:{type:It},capabilities:gn},toolInput:z,toolOutput:F};N!==void 0&&(Ve.widgetState=N),typeof G=="number"&&Number.isFinite(G)&&(Ve.maxHeight=G),Tt({type:"openai:set_globals",globals:Ve}),le&&Tt({type:"openai:set_globals",globals:Ve},!0)},[I,G,L,$,It,gn,nt,z,F,N,Q,le,Tt]);const js=s?.["openai/toolInvocation/invoking"],Xc=s?.["openai/toolInvocation/invoked"];if(r==="output-denied")return l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Tool execution was denied."});if(r==="input-streaming"||r==="input-available")return l.jsxs("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2 flex items-center gap-2",children:[l.jsx(Pn,{className:"h-3 w-3 animate-spin"}),js||"Executing tool..."]});if(ja)return l.jsxs("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2 flex items-center gap-2",children:[l.jsx(Pn,{className:"h-3 w-3 animate-spin"}),"Loading ChatGPT App widget..."]});if(Zc)return l.jsxs("div",{className:"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",children:["Failed to load widget: ",Zc,R&&l.jsxs(l.Fragment,{children:[" ","(Template ",l.jsx("code",{children:R}),")"]})]});if(ir)return l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:Ga==="closed"?"Widget closed.":Xc||"Tool completed successfully."});if(!R&&!T)return r!=="output-available"?l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Widget UI will appear once the tool finishes executing."}):l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Unable to render ChatGPT App UI for this tool result."});if(!ln)return l.jsxs("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2 flex items-center gap-2",children:[l.jsx(Pn,{className:"h-3 w-3 animate-spin"}),"Preparing widget..."]});const ol=Pt?Wt?"absolute inset-0 z-10 w-full h-full bg-background flex flex-col":"fixed inset-0 z-40 w-full h-full bg-background flex flex-col":sn?vt?"absolute inset-0 z-10 w-full h-full bg-background flex flex-col":"fixed top-4 inset-x-0 z-40 w-full max-w-4xl mx-auto space-y-2 bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80 shadow-xl border border-border/60 rounded-xl p-3":"mt-3 space-y-2 relative group";return l.jsxs("div",{className:ol,children:[(Pt&&Wt||sn&&vt)&&l.jsx("button",{onClick:()=>{Y("inline"),d===O&&m?.(O)},className:"absolute left-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer","aria-label":"Close",children:l.jsx(Yn,{className:"w-5 h-5"})}),Pt&&!Wt&&l.jsxs("div",{className:"flex items-center justify-between px-4 h-14 border-b border-border/40 bg-background/95 backdrop-blur z-40 shrink-0",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("button",{onClick:()=>vn("back"),disabled:!fe,className:`p-2 rounded-lg transition-colors ${fe?"hover:bg-muted text-muted-foreground hover:text-foreground cursor-pointer":"text-muted-foreground/50 cursor-not-allowed"}`,"aria-label":"Go back",children:l.jsx(Dq,{className:"w-5 h-5"})}),l.jsx("button",{onClick:()=>vn("forward"),disabled:!Ce,className:`p-2 rounded-lg transition-colors ${Ce?"hover:bg-muted text-muted-foreground hover:text-foreground cursor-pointer":"text-muted-foreground/50 cursor-not-allowed"}`,"aria-label":"Go forward",children:l.jsx(wr,{className:"w-5 h-5"})})]}),l.jsx("div",{className:"font-medium text-sm text-muted-foreground",children:n||"ChatGPT App"}),l.jsx("button",{onClick:()=>{Y("inline"),d===O&&m?.(O)},className:"p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors","aria-label":"Exit fullscreen",children:l.jsx(Yn,{className:"w-5 h-5"})})]}),sn&&!vt&&l.jsx("button",{onClick:()=>{Y("inline"),m?.(O)},className:"absolute left-2 top-2 z-10 flex h-6 w-6 items-center justify-center rounded-md bg-background/80 hover:bg-background border border-border/50 text-muted-foreground hover:text-foreground transition-colors cursor-pointer","aria-label":"Close PiP mode",title:"Close PiP mode",children:l.jsx(Yn,{className:"w-4 h-4"})}),re&&l.jsxs("div",{className:"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",children:["Failed to load widget: ",re]}),l.jsx(Zoe,{ref:E,url:ln,allowAutoResize:Mn,onMessage:yr,onReady:()=>{oe(!0),ee(null)},title:`ChatGPT App Widget: ${n||"tool"}`,className:`w-full bg-background overflow-hidden ${Pt?"flex-1 border-0 rounded-none":`rounded-md ${Hu?"border border-border/40":""}`}`,style:{height:Wa,maxHeight:L==="pip"&&!vt?"90vh":void 0}}),R&&l.jsxs("div",{className:"text-[11px] text-muted-foreground/70",children:["Template: ",l.jsx("code",{children:R})]}),l.jsx(si,{open:le,onOpenChange:te,children:l.jsxs(oi,{className:"w-fit max-w-[90vw] h-fit max-h-[70vh] flex flex-col",children:[l.jsx(vi,{children:l.jsx(yi,{children:J})}),l.jsx("div",{className:"flex-1 w-full h-full min-h-0 overflow-y-auto",children:hs&&l.jsx(Zoe,{ref:A,url:hs,onMessage:Ka,onReady:ms,title:`ChatGPT App Modal: ${J}`,className:"w-full h-full border-0 rounded-md bg-background overflow-hidden"})})]})}),l.jsx(SRt,{open:ye,onOpenChange:Ne,checkoutSession:ce,checkoutCallId:we,onRespond:Cr,serverInfo:y??{name:e},onCallTool:u})]})}const jRt=b.forwardRef(function({html:t,sandbox:n="allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",csp:r,permissions:i,permissive:a,onProxyReady:s,onMessage:o,className:u,style:c,title:d="Sandboxed Content"},f){const p=b.useRef(null),[m,y]=b.useState(!1),[v]=b.useState(()=>{const w=window.location.hostname,T=window.location.port,N=window.location.protocol;let E;w==="localhost"?E="127.0.0.1":w==="127.0.0.1"?E="localhost":(console.warn("[SandboxedIframe] Cross-origin isolation not available for hostname:",w,"- falling back to same-origin sandbox"),E=w);const A=T?`:${T}`:"";return`${N}//${E}${A}/api/mcp/sandbox-proxy?v=${Date.now()}`}),x=b.useMemo(()=>{try{return new URL(v).origin}catch{return"*"}},[v]);b.useImperativeHandle(f,()=>({postMessage:w=>{p.current?.contentWindow?.postMessage(w,x)},getIframeElement:()=>p.current}),[x]);const _=b.useCallback(w=>{if(w.origin!==x&&x!=="*"||w.source!==p.current?.contentWindow)return;if(w.data?.type==="mcp-apps:csp-violation"){o(w);return}const{jsonrpc:T,method:N}=w.data||{};if(T==="2.0"){if(N==="ui/notifications/sandbox-proxy-ready"){y(!0),s?.();return}N?.startsWith("ui/notifications/sandbox-")||o(w)}},[o,s,x]);b.useEffect(()=>(window.addEventListener("message",_),()=>window.removeEventListener("message",_)),[_]);const S=b.useMemo(()=>{const w=["local-network-access *","midi *"];return i?.camera&&w.push("camera *"),i?.microphone&&w.push("microphone *"),i?.geolocation&&w.push("geolocation *"),i?.clipboardWrite&&w.push("clipboard-write *"),w.join("; ")},[i]);return b.useEffect(()=>{!m||!t||p.current?.contentWindow?.postMessage({jsonrpc:"2.0",method:"ui/notifications/sandbox-resource-ready",params:{html:t,sandbox:n,csp:r,permissions:i,permissive:a}},x)},[m,t,n,r,i,a,x]),l.jsx("iframe",{ref:p,src:v,sandbox:n,allow:S,title:d,className:u,style:c})}),ORt=e=>{const t=e==="dark";return{"--color-background-primary":t?"#171717":"#ffffff","--color-background-secondary":t?"#262626":"#f5f5f5","--color-background-tertiary":void 0,"--color-background-inverse":void 0,"--color-background-ghost":void 0,"--color-background-info":void 0,"--color-background-danger":void 0,"--color-background-success":void 0,"--color-background-warning":void 0,"--color-background-disabled":void 0,"--color-text-primary":t?"#fafafa":"#171717","--color-text-secondary":t?"#a3a3a3":"#737373","--color-text-tertiary":void 0,"--color-text-inverse":void 0,"--color-text-info":void 0,"--color-text-danger":void 0,"--color-text-success":void 0,"--color-text-warning":void 0,"--color-text-disabled":void 0,"--color-text-ghost":void 0,"--color-border-primary":t?"#404040":"#e5e5e5","--color-border-secondary":void 0,"--color-border-tertiary":void 0,"--color-border-inverse":void 0,"--color-border-ghost":void 0,"--color-border-info":void 0,"--color-border-danger":void 0,"--color-border-success":void 0,"--color-border-warning":void 0,"--color-border-disabled":void 0,"--color-ring-primary":void 0,"--color-ring-secondary":void 0,"--color-ring-inverse":void 0,"--color-ring-info":void 0,"--color-ring-danger":void 0,"--color-ring-success":void 0,"--color-ring-warning":void 0,"--font-sans":"system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif","--font-mono":"ui-monospace, SFMono-Regular, 'SF Mono', Menlo, Consolas, monospace","--font-weight-normal":void 0,"--font-weight-medium":void 0,"--font-weight-semibold":void 0,"--font-weight-bold":void 0,"--font-text-xs-size":void 0,"--font-text-sm-size":void 0,"--font-text-md-size":void 0,"--font-text-lg-size":void 0,"--font-heading-xs-size":void 0,"--font-heading-sm-size":void 0,"--font-heading-md-size":void 0,"--font-heading-lg-size":void 0,"--font-heading-xl-size":void 0,"--font-heading-2xl-size":void 0,"--font-heading-3xl-size":void 0,"--font-text-xs-line-height":void 0,"--font-text-sm-line-height":void 0,"--font-text-md-line-height":void 0,"--font-text-lg-line-height":void 0,"--font-heading-xs-line-height":void 0,"--font-heading-sm-line-height":void 0,"--font-heading-md-line-height":void 0,"--font-heading-lg-line-height":void 0,"--font-heading-xl-line-height":void 0,"--font-heading-2xl-line-height":void 0,"--font-heading-3xl-line-height":void 0,"--border-radius-xs":void 0,"--border-radius-sm":"4px","--border-radius-md":"8px","--border-radius-lg":"12px","--border-radius-xl":void 0,"--border-radius-full":void 0,"--border-width-regular":void 0,"--shadow-hairline":void 0,"--shadow-sm":void 0,"--shadow-md":void 0,"--shadow-lg":void 0}},RRt={type:"object"};class PRt{inner;onSend;onReceive;_sessionId;onclose;onerror;onmessage;setProtocolVersion;constructor(t,n){this.inner=t,this.onSend=n.onSend,this.onReceive=n.onReceive}get sessionId(){return this._sessionId??this.inner.sessionId}set sessionId(t){this._sessionId=t,this.inner.sessionId=t}async start(){this.inner.onmessage=(t,n)=>{this.onReceive?.(t),this.onmessage?.(t,n)},this.inner.onerror=t=>{this.onerror?.(t)},this.inner.onclose=()=>{this.onclose?.()},this.inner.setProtocolVersion=t=>{this.setProtocolVersion?.(t)},await this.inner.start()}async send(t,n){this.onSend?.(t),await this.inner.send(t,n)}async close(){await this.inner.close()}}function yK({serverId:e,toolCallId:t,toolName:n,toolState:r,toolInput:i,toolOutput:a,toolErrorText:s,resourceUri:o,toolMetadata:u,toolsMetadata:c,onSendFollowUp:d,onCallTool:f,pipWidgetId:p,fullscreenWidgetId:m,onRequestPip:y,onExitPip:v,displayMode:x,onDisplayModeChange:_,onRequestFullscreen:S,onExitFullscreen:w,onModelContextUpdate:T,onAppSupportedDisplayModesChange:N,isOffline:E,cachedWidgetHtmlUrl:A}){const I=b.useRef(null),M=eo(ht=>ht.themeMode),$=Zt(ht=>ht.isPlaygroundActive),O=Zt(ht=>ht.mcpAppsCspMode),R=$?O:"permissive",U=Zt(ht=>ht.globals.locale),z=Zt(ht=>ht.globals.timeZone),F=$?U:navigator.language||"en-US",D=$?z:Intl.DateTimeFormat().resolvedOptions().timeZone||"UTC",W=Zt(ht=>ht.displayMode),q=Zt(ht=>ht.capabilities),X=b.useMemo(()=>$?q:{hover:!0,touch:!1},[$,q]),L=Zt(ht=>ht.safeAreaInsets),Y=b.useMemo(()=>$?L:{top:0,right:0,bottom:0,left:0},[$,L]),G=Zt(ht=>ht.deviceType),P=b.useMemo(()=>{if(!$)return"web";switch(G){case"mobile":case"tablet":return"mobile";case"desktop":default:return"web"}},[$,G]),V=x!==void 0,[K,Q]=b.useState($?W:"inline"),oe=V?x:K,re=b.useMemo(()=>V?oe==="fullscreen"&&m===t?"fullscreen":oe==="pip"&&p===t?"pip":"inline":oe,[oe,m,V,p,t]),ee=b.useCallback(ht=>{V?_?.(ht):Q(ht),ht==="fullscreen"?S?.(t):oe==="fullscreen"&&w?.(t)},[V,_,t,S,w,oe]),[le,te]=b.useState(!1),[Z,ne]=b.useState(null),[J,se]=b.useState(null),[ie,he]=b.useState(void 0),[ye,Ne]=b.useState(void 0),[ce,Te]=b.useState(!1),[we,Oe]=b.useState(!0),[Ue,Me]=b.useState(null);b.useEffect(()=>{se(null),Me(null)},[A]);const be=b.useRef(null),je=b.useRef(null),Xe=b.useRef(null),ue=b.useRef(null),fe=b.useRef(null),xe=b.useRef(!1),Ce=b.useRef(d),He=b.useRef(f),Ze=b.useRef(y),st=b.useRef(v),ot=b.useRef(ee),mt=b.useRef($),Bt=b.useRef(G),Mt=b.useRef(re),It=b.useRef(e),gn=b.useRef(t),nt=b.useRef(p),yt=b.useRef(c),ut=b.useRef(T),vt=b.useRef(N),Wt=b.useRef(i);Wt.current=i;const Qn=b.useRef(a);Qn.current=a;const Gi=b.useRef(M);Gi.current=M,b.useEffect(()=>{if(r!=="output-available"||J&&Ue===R)return;(async()=>{try{if(A){const ol=await fetch(A);if(!ol.ok)throw new Error(`Failed to fetch cached widget HTML: ${ol.statusText}`);const Ve=await ol.text();se(Ve),Te(!0),Oe(!0),Me(R);return}if(E){ne("Server is offline and this view was saved without cached HTML. Connect the server and re-save the view to enable offline rendering.");return}const Nt=await Yt("/api/mcp/apps/widget/store",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:e,resourceUri:o,toolInput:Wt.current,toolOutput:Qn.current,toolId:t,toolName:n,theme:Gi.current,protocol:"mcp-apps",cspMode:R})});if(!Nt.ok)throw new Error(`Failed to store widget: ${Nt.statusText}`);const Tt=await fetch(`/api/mcp/apps/widget-content/${t}?csp_mode=${R}`);if(!Tt.ok){const ol=await Tt.json().catch(()=>({}));throw new Error(ol.error||`Failed to fetch widget: ${Tt.statusText}`)}const{html:Cr,csp:vn,permissions:yr,permissive:Ka,mimeTypeWarning:ms,mimeTypeValid:js,prefersBorder:Xc}=await Tt.json();if(!js){ne(ms||'Invalid mimetype - SEP-1865 requires "text/html;profile=mcp-app"');return}se(Cr),he(vn),Ne(yr),Te(Ka??!1),Oe(Xc??!0),Me(R),Zc(t,Cr),(vn||yr||!Ka)&&ln(t,{mode:Ka?"permissive":"widget-declared",connectDomains:vn?.connectDomains||[],resourceDomains:vn?.resourceDomains||[],frameDomains:vn?.frameDomains||[],baseUriDomains:vn?.baseUriDomains||[],permissions:yr,widgetDeclared:vn?{connectDomains:vn.connectDomains,resourceDomains:vn.resourceDomains,frameDomains:vn.frameDomains,baseUriDomains:vn.baseUriDomains}:null})}catch(Nt){ne(Nt instanceof Error?Nt.message:"Failed to prepare widget")}})()},[r,t,J,Ue,e,o,n,R,E,A]);const Pt=km(ht=>ht.addLog),sn=bs(ht=>ht.setWidgetDebugInfo),Mn=bs(ht=>ht.setWidgetGlobals),ln=bs(ht=>ht.setWidgetCsp),ir=bs(ht=>ht.addCspViolation),Ga=bs(ht=>ht.clearCspViolations),ja=bs(ht=>ht.setWidgetModelContext),Zc=bs(ht=>ht.setWidgetHtml);b.useEffect(()=>{Ue!==null&&Ue!==R&&Ga(t)},[R,Ue,t,Ga]),b.useEffect(()=>{Ue!==null&&Ue!==R&&(te(!1),xe.current=!1,Xe.current=null,ue.current=null,fe.current=null)},[R,Ue]),b.useEffect(()=>{$&&!V&&Q(W)},[$,W,V]),b.useEffect(()=>{sn(t,{toolName:n,protocol:"mcp-apps",widgetState:null,globals:{theme:M,displayMode:re,locale:F,timeZone:D,deviceCapabilities:X,safeAreaInsets:Y}})},[t,n,sn,M,re,F,D,X,Y]),b.useEffect(()=>{Mn(t,{theme:M,displayMode:re,locale:F,timeZone:D,deviceCapabilities:X,safeAreaInsets:Y})},[t,M,re,F,D,X,Y,Mn]);const qu=b.useMemo(()=>ORt(M),[M]),Is=b.useMemo(()=>({theme:M,displayMode:re,availableDisplayModes:["inline","pip","fullscreen"],locale:F,timeZone:D,platform:P,userAgent:navigator.userAgent,deviceCapabilities:X,safeAreaInsets:Y,styles:{variables:qu},toolInfo:{id:t,tool:{name:n,inputSchema:u?.inputSchema??RRt,description:u?.description}}}),[M,re,F,D,P,X,Y,qu,t,n,u]);b.useEffect(()=>{je.current=Is},[Is]),b.useEffect(()=>{Ce.current=d,He.current=f,Ze.current=y,st.current=v,ot.current=ee,mt.current=$,Bt.current=G,Mt.current=re,It.current=e,gn.current=t,nt.current=p,yt.current=c,ut.current=T,vt.current=N},[d,f,y,v,ee,$,G,re,e,t,p,c,T,N]);const Hu=b.useCallback(ht=>{ht.oninitialized=()=>{te(!0),xe.current=!0;const Nt=ht.getAppCapabilities();vt.current?.(Nt?.availableDisplayModes)},ht.onmessage=async({content:Nt})=>{const Tt=Nt.find(Cr=>Cr.type==="text")?.text;return Tt&&Ce.current?.(Tt),{}},ht.onopenlink=async({url:Nt})=>(Nt&&window.open(Nt,"_blank","noopener,noreferrer"),{}),ht.oncalltool=async({name:Nt,arguments:Tt},Cr)=>{const vn=yt.current?.[Nt];if(Smt(vn)){const yr=new Error(`Tool "${Nt}" is not callable by apps (visibility: model-only)`);throw ht.sendToolCancelled({reason:yr.message}),yr}if(!He.current){const yr=new Error("Tool calls not supported");throw ht.sendToolCancelled({reason:yr.message}),yr}try{return await He.current(Nt,Tt??{})}catch(yr){throw ht.sendToolCancelled({reason:yr instanceof Error?yr.message:String(yr)}),yr}},ht.onreadresource=async({uri:Nt})=>{const Tt=await Yt("/api/mcp/resources/read",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:It.current,uri:Nt})});if(!Tt.ok)throw new Error(`Resource read failed: ${Tt.statusText}`);return(await Tt.json()).content},ht.onlistresources=async Nt=>{const Tt=await Yt("/api/mcp/resources/list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:It.current,...Nt??{}})});if(!Tt.ok)throw new Error(`Resource list failed: ${Tt.statusText}`);return Tt.json()},ht.onlistresourcetemplates=async Nt=>{const Tt=await Yt("/api/mcp/resource-templates/list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:It.current,...Nt??{}})});if(!Tt.ok)throw new Error(`Resource template list failed: ${Tt.statusText}`);return Tt.json()},ht.onlistprompts=async Nt=>{const Tt=await Yt("/api/mcp/prompts/list",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverId:It.current,...Nt??{}})});if(!Tt.ok)throw new Error(`Prompt list failed: ${Tt.statusText}`);return Tt.json()},ht.onloggingmessage=({level:Nt,data:Tt,logger:Cr})=>{const yr=`${Cr?`[${Cr}]`:"[MCP Apps]"} ${Nt.toUpperCase()}:`;if(Nt==="error"||Nt==="critical"||Nt==="alert"){console.error(yr,Tt);return}if(Nt==="warning"){console.warn(yr,Tt);return}console.info(yr,Tt)},ht.onsizechange=({height:Nt})=>{if(Mt.current!=="inline")return;const Tt=I.current?.getIframeElement();if(!Tt||Nt===void 0)return;const Cr=getComputedStyle(Tt),vn=Cr.boxSizing==="border-box",yr={},Ka={};let ms=Nt;ms!==void 0&&(vn&&(ms+=parseFloat(Cr.borderTopWidth)+parseFloat(Cr.borderBottomWidth)),yr.height=`${Tt.offsetHeight}px`,Tt.style.height=Ka.height=`${ms}px`),Tt.animate([yr,Ka],{duration:300,easing:"ease-out"})},ht.onrequestdisplaymode=async({mode:Nt})=>{const Tt=Nt??"inline",vn=(mt.current?Bt.current==="mobile"||Bt.current==="tablet":!0)&&Tt==="pip"?"fullscreen":Tt;return ot.current(vn),vn==="pip"?Ze.current?.(gn.current):(vn==="inline"||vn==="fullscreen")&&nt.current===gn.current&&st.current?.(gn.current),{mode:vn}},ht.onupdatemodelcontext=async({content:Nt,structuredContent:Tt})=>(ja(t,{content:Nt,structuredContent:Tt}),ut.current?.(t,{content:Nt,structuredContent:Tt}),{})},[te,t,ja]);b.useEffect(()=>{if(!J)return;const ht=I.current?.getIframeElement();if(!ht?.contentWindow)return;te(!1),xe.current=!1;const Nt=new xmt(null,{name:"mcpjam-inspector",version:"1.5.14"},{openLinks:{},serverTools:{},serverResources:{},logging:{},sandbox:{csp:ce?void 0:ie,permissions:ye}},{hostContext:je.current??{}});Hu(Nt),be.current=Nt;const Tt=new PRt(new gmt(ht.contentWindow,ht.contentWindow),{onSend:vn=>{Pt({widgetId:t,serverId:e,direction:"host-to-ui",protocol:"mcp-apps",method:L1(vn,"mcp-apps"),message:vn})},onReceive:vn=>{Pt({widgetId:t,serverId:e,direction:"ui-to-host",protocol:"mcp-apps",method:L1(vn,"mcp-apps"),message:vn})}});let Cr=!0;return Nt.connect(Tt).catch(vn=>{Cr&&ne(vn instanceof Error?vn.message:"Failed to connect MCP App")}),()=>{Cr=!1,be.current=null,xe.current&&Nt.teardownResource({}).catch(()=>{}),Nt.close().catch(()=>{}),ja(t,null)}},[Pt,e,t,J,Hu,ja]),b.useEffect(()=>{const ht=be.current;!ht||!le||ht.setHostContext(Is)},[Is,le]),b.useEffect(()=>{if(!le||r!=="output-available")return;const ht=be.current;if(!ht)return;const Nt=i??{},Tt=JSON.stringify(Nt);Xe.current!==Tt&&(Xe.current=Tt,ht.sendToolInput({arguments:Nt}))},[le,i,r]),b.useEffect(()=>{if(!le||r!=="output-available")return;const ht=be.current;if(!ht||!a)return;const Nt=JSON.stringify(a);ue.current!==Nt&&(ue.current=Nt,ht.sendToolResult(a))},[le,a,r]),b.useEffect(()=>{if(!le||r!=="output-error")return;const ht=be.current;if(!ht)return;const Nt=s??(a instanceof Error?a.message:typeof a=="string"?a:"Tool execution failed");fe.current!==Nt&&(fe.current=Nt,ht.sendToolCancelled({reason:Nt}))},[le,s,a,r]),b.useEffect(()=>{Xe.current=null,ue.current=null,fe.current=null},[t]);const Ao=ht=>{if(ht.data?.type!=="mcp-apps:csp-violation")return;const{directive:Nt,blockedUri:Tt,sourceFile:Cr,lineNumber:vn,columnNumber:yr,effectiveDirective:Ka,timestamp:ms}=ht.data;Pt({widgetId:t,serverId:e,direction:"ui-to-host",protocol:"mcp-apps",method:"csp-violation",message:ht.data}),ir(t,{directive:Nt,effectiveDirective:Ka,blockedUri:Tt,sourceFile:Cr,lineNumber:vn,columnNumber:yr,timestamp:ms||Date.now()}),console.warn(`[MCP Apps CSP Violation] ${Nt}: Blocked ${Tt}`,Cr?`at ${Cr}:${vn}:${yr}`:"")};if(r==="output-denied")return l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Tool execution was denied."});if(r!=="output-available")return l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Waiting for tool to finish executing..."});if(Z)return l.jsxs("div",{className:"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",children:["Failed to load MCP App: ",Z]});if(!J)return l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Preparing MCP App widget..."});const Ai=re==="pip",Wa=re==="fullscreen",hs=$&&G==="mobile",vr=$&&(G==="mobile"||G==="tablet"),Yc=Wa?vr?"absolute inset-0 z-10 w-full h-full bg-background flex flex-col":"fixed inset-0 z-40 w-full h-full bg-background flex flex-col":Ai?hs?"absolute inset-0 z-10 w-full h-full bg-background flex flex-col":["fixed top-4 left-1/2 -translate-x-1/2 z-40 w-full min-w-[300px] max-w-[min(90vw,1200px)] space-y-2","bg-background/95 backdrop-blur supports-[backdrop-filter]:bg-background/80","shadow-xl border border-border/60 rounded-xl p-3"].join(" "):"mt-3 space-y-2 relative group",Xl={height:Wa?"100%":"400px",width:"100%",maxWidth:"100%",transition:Wa?void 0:"height 300ms ease-out"};return l.jsxs("div",{className:Yc,children:[(Wa&&vr||Ai&&hs)&&l.jsx("button",{onClick:()=>{ee("inline"),Ai&&v?.(t)},className:"absolute left-3 top-3 z-20 flex h-8 w-8 items-center justify-center rounded-full bg-black/20 hover:bg-black/40 text-white transition-colors cursor-pointer","aria-label":"Close",children:l.jsx(Yn,{className:"w-5 h-5"})}),Wa&&!vr&&l.jsxs("div",{className:"flex items-center justify-between px-4 h-14 border-b border-border/40 bg-background/95 backdrop-blur z-40 shrink-0",children:[l.jsx("div",{}),l.jsx("div",{className:"font-medium text-sm text-muted-foreground",children:n}),l.jsx("button",{onClick:()=>{ee("inline"),p===t&&v?.(t)},className:"p-2 rounded-lg hover:bg-muted text-muted-foreground hover:text-foreground transition-colors","aria-label":"Exit fullscreen",children:l.jsx(Yn,{className:"w-5 h-5"})})]}),Ai&&!hs&&l.jsx("button",{onClick:()=>{ee("inline"),v?.(t)},className:"absolute left-2 top-2 z-10 flex h-6 w-6 items-center justify-center rounded-md bg-background/80 hover:bg-background border border-border/50 text-muted-foreground hover:text-foreground transition-colors cursor-pointer","aria-label":"Close PiP mode",title:"Close PiP mode",children:l.jsx(Yn,{className:"w-4 h-4"})}),l.jsx(jRt,{ref:I,html:J,sandbox:"allow-scripts allow-same-origin allow-forms allow-popups allow-popups-to-escape-sandbox",csp:ie,permissions:ye,permissive:ce,onMessage:Ao,title:`MCP App: ${n}`,className:`bg-background overflow-hidden ${Wa?"flex-1 border-0 rounded-none":`rounded-md ${we?"border border-border/40":""}`}`,style:Xl}),l.jsxs("div",{className:"text-[11px] text-muted-foreground/70",children:["MCP App: ",l.jsx("code",{children:o})]})]})}function $Rt(e){const t=[];let n=[];for(const r of e){if(r.type==="step-start"){n.length>0&&t.push(n),n=[];continue}n.push(r)}return n.length>0&&t.push(n),t.length>0?t:[e.filter(r=>r.type!=="step-start")]}function uD(e){const t=e.type;return typeof t=="string"&&t.startsWith("tool-")}function Q1(e){return!!e&&typeof e.type=="string"&&e.type==="dynamic-tool"}function Qoe(e){if(Q1(e))return{toolName:e.toolName,toolCallId:e.toolCallId,toolState:e.state,input:e.input,output:e.output,rawOutput:e.output,errorText:e.errorText};const t=e,n=t.output;return{toolName:TPe(t.type),toolCallId:t.toolCallId,toolState:t.state,input:t.input,output:t.output?.value??n,rawOutput:n,errorText:t.errorText??t.error}}function MRt(e){const t=e?.value?.content??e?.content;return Array.isArray(t)?t.find(r=>oke(r))??null:null}function DRt(e){const t=e.type;return typeof t=="string"&&t.startsWith("data-")}function LRt(e){return e==="data-"?"Data":`Data (${e.replace(/^data-/,"")})`}function TPe(e){return e&&e.startsWith("tool-")?e.replace(/^tool-/,""):"Tool"}function zRt(e){try{return JSON.stringify(e,null,2)}catch{return String(e)}}function URt(e){if(!e)return null;switch(e){case"input-streaming":return{Icon:Pn,label:"Input streaming",className:"h-4 w-4 animate-spin text-muted-foreground"};case"input-available":return{Icon:ko,label:"Input available",className:"h-4 w-4 text-muted-foreground"};case"output-available":return{Icon:ko,label:"Output available",className:"h-4 w-4 text-emerald-500"};case"approval-requested":return{Icon:DQe,label:"Approval requested",className:"h-4 w-4 text-amber-500"};case"output-denied":return{Icon:Lv,label:"Denied",className:"h-4 w-4 text-destructive"};case"output-error":return{Icon:wo,label:"Output error",className:"h-4 w-4 text-destructive"};default:return null}}function FRt(e){if(!e||e==="inline"||e==="eval"||e==="data"||e==="blob")return null;try{return new URL(e).origin}catch{const t=e.match(/^(https?:\/\/[^/]+)/);return t?t[1]:null}}function BRt(e){const t=e.replace(/-src$/,"");return t==="connect"?"connect_domains":["script","style","img","font","media","default"].includes(t)?"resource_domains":null}function qRt(e){const t=new Map,n=new Map;for(const i of e){const a=i.effectiveDirective||i.directive,s=BRt(a),o=FRt(i.blockedUri);if(!s||!o)continue;const u=s==="connect_domains"?t:n,c=u.get(o)||[];c.push(i),u.set(o,c)}const r=[];return t.size>0&&r.push({field:"connect_domains",domains:Array.from(t.keys()),violations:Array.from(t.values()).flat()}),n.size>0&&r.push({field:"resource_domains",domains:Array.from(n.keys()),violations:Array.from(n.values()).flat()}),r}function HRt(e,t,n){const r=new Set([...t?.connect_domains||[],...t?.connectDomains||[]]),i=new Set([...t?.resource_domains||[],...t?.resourceDomains||[]]);for(const o of e){const u=o.field==="connect_domains"?r:i;for(const c of o.domains)u.add(c)}const a=n!=="openai-apps",s={};if(r.size>0){const o=a?"connectDomains":"connect_domains";s[o]=Array.from(r)}if(i.size>0){const o=a?"resourceDomains":"resource_domains";s[o]=Array.from(i)}return JSON.stringify(s,null,2)}function VRt({cspInfo:e,protocol:t}){const n=e?.mode??"permissive",r=e?.violations??[],i=r.length>0,[a,s]=b.useState(!1),o=e?.widgetDeclared?.connect_domains??e?.widgetDeclared?.connectDomains??[],u=e?.widgetDeclared?.resource_domains??e?.widgetDeclared?.resourceDomains??[],c=e?.widgetDeclared?.frame_domains??e?.widgetDeclared?.frameDomains??[],d=e?.widgetDeclared?.baseUriDomains??[],f=b.useMemo(()=>qRt(r),[r]),p=b.useMemo(()=>i?HRt(f,e?.widgetDeclared,t):"",[f,e?.widgetDeclared,i,t]),m=async()=>{try{await navigator.clipboard.writeText(p),s(!0),setTimeout(()=>s(!1),2e3)}catch(y){console.error("Failed to copy:",y)}};return l.jsxs("div",{className:"space-y-4 text-xs",children:[i&&f.length>0&&l.jsxs("details",{className:"group",children:[l.jsxs("summary",{className:"flex items-center gap-1.5 text-amber-600 dark:text-amber-400 cursor-pointer list-none",children:[l.jsx(wr,{className:"h-3.5 w-3.5 transition-transform group-open:rotate-90"}),l.jsx(PJe,{className:"h-3.5 w-3.5"}),l.jsx("span",{className:"font-medium",children:"Suggested fix"})]}),l.jsxs("div",{className:"mt-2 pl-5 space-y-1",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx(Zn,{className:"text-[10px] text-muted-foreground",children:t==="mcp-apps"?"Add the following to your ui.csp field":"Add the following to your openai/widgetCSP field"}),l.jsx("button",{onClick:m,className:"p-1 hover:bg-muted rounded transition-colors",title:"Copy to clipboard",children:a?l.jsx(xi,{className:"h-3 w-3 text-green-500"}):l.jsx(Ca,{className:"h-3 w-3 text-muted-foreground"})})]}),l.jsx("pre",{className:"font-mono text-[10px] bg-muted/50 p-2 rounded overflow-auto max-h-32 text-foreground",children:p})]})]}),i&&l.jsxs("details",{className:"group",children:[l.jsxs("summary",{className:"flex items-center gap-1.5 text-destructive cursor-pointer list-none",children:[l.jsx(wr,{className:"h-3.5 w-3.5 transition-transform group-open:rotate-90"}),l.jsx(Gs,{className:"h-3.5 w-3.5"}),l.jsxs("span",{className:"font-medium",children:[r.length," blocked request",r.length!==1?"s":""]})]}),l.jsx("div",{className:"mt-2 space-y-1 max-h-32 overflow-auto pl-5",children:r.map((y,v)=>l.jsxs("div",{className:"flex items-center gap-1.5 text-[10px] text-muted-foreground",children:[l.jsx(Cn,{variant:"outline",className:"text-[9px] px-1 py-0 h-4 shrink-0",children:y.effectiveDirective||y.directive}),l.jsx("span",{className:"font-mono truncate",children:y.blockedUri||"(inline)"})]},v))})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{className:"text-[10px] text-muted-foreground",children:"connect_domains"}),l.jsx("div",{className:"text-[10px]",children:n==="permissive"?l.jsx("span",{className:"text-muted-foreground italic",children:"Not enforced in permissive mode"}):o.length>0?l.jsx("div",{className:"font-mono space-y-0.5",children:o.map((y,v)=>l.jsx("div",{className:"truncate",children:y},v))}):l.jsx("span",{className:"text-muted-foreground italic",children:"Not declared"})})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{className:"text-[10px] text-muted-foreground",children:"resource_domains"}),l.jsx("div",{className:"text-[10px]",children:n==="permissive"?l.jsx("span",{className:"text-muted-foreground italic",children:"Not enforced in permissive mode"}):u.length>0?l.jsx("div",{className:"font-mono space-y-0.5",children:u.map((y,v)=>l.jsx("div",{className:"truncate",children:y},v))}):l.jsx("span",{className:"text-muted-foreground italic",children:"Not declared"})})]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{className:"text-[10px] text-muted-foreground",children:t==="openai-apps"?"frame_domains":"frameDomains"}),l.jsx("div",{className:"text-[10px]",children:n==="permissive"?l.jsx("span",{className:"text-muted-foreground italic",children:"Not enforced in permissive mode"}):c.length>0?l.jsx("div",{className:"font-mono space-y-0.5",children:c.map((y,v)=>l.jsx("div",{className:"truncate",children:y},v))}):l.jsx("span",{className:"text-muted-foreground italic",children:"Not declared"})})]}),t==="mcp-apps"&&l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{className:"text-[10px] text-muted-foreground",children:"baseUriDomains"}),l.jsx("div",{className:"text-[10px]",children:n==="permissive"?l.jsx("span",{className:"text-muted-foreground italic",children:"Not enforced in permissive mode"}):d.length>0?l.jsx("div",{className:"font-mono space-y-0.5",children:d.map((y,v)=>l.jsx("div",{className:"truncate",children:y},v))}):l.jsx("span",{className:"text-muted-foreground italic",children:"Not declared"})})]})]}),e?.headerString&&l.jsxs("details",{children:[l.jsx("summary",{className:"text-[10px] text-muted-foreground cursor-pointer hover:text-foreground",children:"Full CSP header"}),l.jsx("div",{className:"mt-1 font-mono text-[9px] text-muted-foreground bg-muted/50 p-2 rounded max-h-24 overflow-auto break-all",children:e.headerString})]}),l.jsxs("a",{href:t==="mcp-apps"?"https://github.com/modelcontextprotocol/ext-apps/blob/main/specification/draft/apps.mdx#ui-resource-format":"https://developers.openai.com/apps-sdk/reference/#component-resource-configuration",target:"_blank",rel:"noopener noreferrer",className:"inline-flex items-center gap-1 text-[10px] text-muted-foreground hover:text-foreground",children:[l.jsx(Iu,{className:"h-3 w-3"}),t==="mcp-apps"?"MCP Apps UI format docs":"openai/widgetCSP docs"]})]})}function Yh({part:e,uiType:t,displayMode:n,pipWidgetId:r,fullscreenWidgetId:i,onDisplayModeChange:a,onRequestFullscreen:s,onExitFullscreen:o,onRequestPip:u,onExitPip:c,appSupportedDisplayModes:d,approvalId:f,onApprove:p,onDeny:m,onSaveView:y,canSaveView:v,saveDisabledReason:x,isSaving:_}){const S=Q1(e)?e.toolName:TPe(e.type),w=e.toolCallId,T=e.state,N=URt(T),E=N?.Icon,I=eo(Z=>Z.themeMode)==="dark"?"h-3 w-3 filter invert":"h-3 w-3",M=T==="approval-requested"&&!!f,[$,O]=b.useState("pending"),U=$==="denied"||T==="output-denied"||M,[z,F]=b.useState(!1),D=M||z,[W,q]=b.useState("data"),X=e.input,L=e.output,Y=e.errorText??e.error,G=X!=null,P=L!=null,V=T==="output-error"&&!!Y,K=bs(Z=>w?Z.widgets.get(w):void 0),Q=!!K,oe=n!==void 0&&a!==void 0&&Q&&!U,re=[{mode:"inline",icon:Bm,label:"Inline"},{mode:"pip",icon:xQe,label:"Picture in Picture"},{mode:"fullscreen",icon:R1e,label:"Fullscreen"}],ee=b.useMemo(()=>{const Z=[{tab:"data",icon:nJe,label:"Data"}];return t===bn.OPENAI_SDK&&Z.push({tab:"state",icon:AXe,label:"Widget State"}),t===bn.MCP_APPS&&K?.modelContext&&Z.push({tab:"context",icon:Bm,label:"Model Context"}),Z.push({tab:"csp",icon:lA,label:"CSP",badge:K?.csp?.violations?.length}),Z},[t,K?.csp?.violations?.length,K?.modelContext]),le=Z=>{W===Z?(q(null),F(!1)):(q(Z),F(!0))},te=Z=>{w&&(n==="fullscreen"&&Z!=="fullscreen"?o?.(i??w):n==="pip"&&Z!=="pip"&&c?.(r??w),Z==="fullscreen"?s?.(w):Z==="pip"&&u?.(w)),a?.(Z)};return l.jsxs("div",{className:hu("rounded-lg border text-xs",M&&$==="pending"?"border-pending/40 bg-pending/5":M&&$==="approved"?"border-success/40 bg-success/5":M&&$==="denied"?"border-destructive/40 bg-destructive/5":"border-border/50 bg-background/70"),children:[l.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-2 px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wide text-muted-foreground cursor-pointer",onClick:()=>F(Z=>!Z),"aria-expanded":D,children:[l.jsxs("span",{className:"inline-flex items-center gap-2 font-medium normal-case text-foreground min-w-0",children:[l.jsxs("span",{className:"inline-flex items-center gap-2 min-w-0",children:[l.jsx("img",{src:"/mcp.svg",alt:"",role:"presentation","aria-hidden":"true",className:`${I} shrink-0`}),l.jsx("span",{className:"font-mono text-xs tracking-tight text-muted-foreground/80 truncate",children:S})]}),M&&$==="pending"&&l.jsx("span",{className:"text-[11px] font-medium text-pending-foreground dark:text-pending",children:"Approve tool call?"}),M&&$==="approved"&&l.jsxs("span",{className:"flex items-center gap-1 text-[11px] font-medium text-success dark:text-success",children:[l.jsx(M1e,{className:"h-3.5 w-3.5"}),"Approved"]}),M&&$==="denied"&&l.jsxs("span",{className:"flex items-center gap-1 text-[11px] font-medium text-destructive",children:[l.jsx(Lv,{className:"h-3.5 w-3.5"}),"Denied"]})]}),l.jsxs("span",{className:"inline-flex items-center gap-1.5 text-muted-foreground shrink-0",children:[oe&&l.jsx("span",{className:"inline-flex items-center gap-0.5 border border-border/40 rounded-md p-0.5 bg-muted/30",onClick:Z=>Z.stopPropagation(),children:l.jsx("div",{className:"inline-flex items-center gap-0.5",children:re.map(({mode:Z,icon:ne,label:J})=>{const se=n===Z,ie=d!==void 0&&!d.includes(Z);return l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("button",{type:"button",disabled:ie,onClick:he=>{he.stopPropagation(),!ie&&te(Z)},className:`p-1 rounded transition-colors ${ie?"text-muted-foreground/30 cursor-not-allowed":se?"bg-background text-foreground shadow-sm cursor-pointer":"text-muted-foreground/60 hover:text-muted-foreground hover:bg-background/50 cursor-pointer"}`,children:l.jsx(ne,{className:"h-3.5 w-3.5"})})}),l.jsx(zt,{children:ie?`${J} (not supported by this app)`:J})]},Z)})})}),Q&&!U&&l.jsxs(l.Fragment,{children:[oe&&Q&&l.jsx("div",{className:"h-4 w-px bg-border/40"}),l.jsx("span",{className:"inline-flex items-center gap-0.5 border border-border/40 rounded-md p-0.5 bg-muted/30",onClick:Z=>Z.stopPropagation(),children:ee.map(({tab:Z,icon:ne,label:J,badge:se})=>l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsxs("button",{type:"button",onClick:ie=>{ie.stopPropagation(),le(Z)},className:`p-1 rounded transition-colors cursor-pointer relative ${W===Z?"bg-background text-foreground shadow-sm":se&&se>0?"text-destructive hover:text-destructive hover:bg-destructive/10":"text-muted-foreground/60 hover:text-muted-foreground hover:bg-background/50"}`,children:[l.jsx(ne,{className:"h-3.5 w-3.5"}),se!==void 0&&se>0&&l.jsx(Cn,{variant:"destructive",className:"absolute -top-1.5 -right-1.5 h-3.5 min-w-[14px] px-1 text-[8px] leading-none",children:se})]})}),l.jsx(zt,{children:J})]},Z))})]}),y&&t&&t!==bn.MCP_UI&&l.jsxs(l.Fragment,{children:[Q&&l.jsx("div",{className:"h-4 w-px bg-border/40"}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("button",{type:"button",disabled:!v||_,onClick:Z=>{Z.stopPropagation(),y()},className:`p-1 rounded transition-colors ${v&&!_?"text-muted-foreground/60 hover:text-muted-foreground hover:bg-background/50 cursor-pointer":"text-muted-foreground/30 cursor-not-allowed"}`,children:_?l.jsx(Pn,{className:"h-3.5 w-3.5 animate-spin"}):l.jsx(N1,{className:"h-3.5 w-3.5"})})}),l.jsx(zt,{children:_?"Saving...":v?"Save as View":x||"No output to save"})]})]}),N&&E&&l.jsxs("span",{className:"inline-flex h-5 w-5 items-center justify-center",title:N.label,children:[l.jsx(E,{className:N.className}),l.jsx("span",{className:"sr-only",children:N.label})]}),!M&&l.jsx(Wr,{className:`h-4 w-4 transition-transform duration-150 ${D?"rotate-180":""}`})]})]}),D&&l.jsxs("div",{className:"border-t border-border/40 px-3 py-3",children:[Q&&W==="data"&&l.jsxs("div",{className:"space-y-4",children:[G&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Input"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[300px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:X,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),P&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Result"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[300px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:L,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),V&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Error"}),l.jsx("div",{className:"rounded border border-destructive/40 bg-destructive/10 p-2 text-destructive",children:Y})]}),!G&&!P&&!V&&l.jsx("div",{className:"text-muted-foreground/70",children:"No tool details available."})]}),Q&&W==="state"&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Widget State"}),l.jsxs("div",{className:"text-[9px] text-muted-foreground/50",children:["Updated:"," ",new Date(K.updatedAt).toLocaleTimeString()]})]}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[300px] overflow-auto",children:K.widgetState?l.jsx(zn,{viewOnly:!0,value:K.widgetState,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2}):l.jsx("div",{className:"p-2 text-[11px] text-muted-foreground",children:"null (no state set)"})}),l.jsx("div",{className:"text-[9px] text-muted-foreground/50 mt-2",children:"Tip: Widget state persists across follow-up turns. Keep under 4k tokens."})]}),Q&&W==="csp"&&l.jsx(VRt,{cspInfo:K.csp,protocol:K.protocol}),Q&&W==="context"&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Model Context"}),K.modelContext&&l.jsxs("div",{className:"text-[9px] text-muted-foreground/50",children:["Updated:"," ",new Date(K.modelContext.updatedAt).toLocaleTimeString()]})]}),K.modelContext?l.jsxs("div",{className:"space-y-3",children:[K.modelContext.content&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-medium text-muted-foreground",children:"Content (for model)"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[200px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:K.modelContext.content,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),K.modelContext.structuredContent&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-medium text-muted-foreground",children:"Structured Content"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[200px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:K.modelContext.structuredContent,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),l.jsx("div",{className:"text-[9px] text-muted-foreground/50 mt-2",children:"This context will be included in future turns with the model. Each update overwrites the previous context from this widget."})]}):l.jsx("div",{className:"text-muted-foreground/70 text-[11px]",children:"No model context set by this widget."})]}),!Q&&l.jsxs("div",{className:"space-y-4",children:[G&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Input"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[300px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:X,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),P&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Result"}),l.jsx("div",{className:"rounded-md border border-border/30 bg-muted/20 max-h-[300px] overflow-auto",children:l.jsx(zn,{viewOnly:!0,value:L,className:"p-2 text-[11px]",collapsible:!0,defaultExpandDepth:2})})]}),V&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Error"}),l.jsx("div",{className:"rounded border border-destructive/40 bg-destructive/10 p-2 text-destructive",children:Y})]}),!G&&!P&&!V&&l.jsx("div",{className:"text-muted-foreground/70",children:"No tool details available."})]}),M&&$==="pending"&&l.jsxs("div",{className:"flex items-center gap-2 pt-2 border-t border-border/40 mt-3",children:[l.jsxs(Ee,{type:"button",size:"sm",variant:"outline",className:"h-7 px-3 text-xs border-success/40 text-success hover:bg-success/10",onClick:Z=>{Z.stopPropagation(),f&&(O("approved"),F(!1),p?.(f))},children:[l.jsx(xi,{className:"h-3 w-3 mr-1"}),"Approve"]}),l.jsxs(Ee,{type:"button",size:"sm",variant:"outline",className:"h-7 px-3 text-xs border-destructive/40 text-destructive hover:bg-destructive/10",onClick:Z=>{Z.stopPropagation(),f&&(O("denied"),F(!1),m?.(f))},children:[l.jsx(Yn,{className:"h-3 w-3 mr-1"}),"Deny"]})]})]})]})}function GRt({text:e}){return e?l.jsx("div",{className:"rounded-lg border border-border/30 bg-muted/10 p-3 text-xs text-muted-foreground",children:l.jsx("pre",{className:"whitespace-pre-wrap break-words",children:e})}):null}function WRt(e){return e?.startsWith("image/")??!1}function KRt(e){return e?e.startsWith("image/")?XO:e==="application/pdf"||e==="text/plain"?Um:e==="text/csv"||e==="application/vnd.ms-excel"||e.includes("spreadsheet")?I1e:Fm:Fm}function ele(e,t=24){if(e.length<=t)return e;const n=e.lastIndexOf(".");if(n===-1)return e.slice(0,t-3)+"...";const r=e.slice(n),i=e.slice(0,n),a=t-r.length-3;return a<=0?"..."+r:i.slice(0,a)+"..."+r}function ZRt({part:e}){const t=e.filename??"Attachment";if(WRt(e.mediaType)&&e.url)return l.jsxs("div",{className:"inline-block",children:[l.jsx("img",{src:e.url,alt:t,className:"max-w-xs max-h-48 rounded-md object-contain border border-border"}),e.filename&&l.jsx("div",{className:"text-xs text-muted-foreground mt-1 truncate max-w-xs text-right",title:e.filename,children:ele(e.filename)})]});const r=KRt(e.mediaType);return l.jsxs("div",{className:"inline-flex items-center gap-2 rounded-md border border-border bg-muted/50 px-3 py-2 text-sm",children:[l.jsx(r,{className:"h-5 w-5 text-muted-foreground flex-shrink-0"}),l.jsx("span",{className:"font-medium text-foreground truncate max-w-[200px]",title:t,children:ele(t)})]})}function YRt({part:e}){return l.jsxs("div",{className:"space-y-1 text-xs",children:[l.jsxs("div",{className:"font-medium",children:["🔗 ",e.title??e.url]}),l.jsx("pre",{className:"whitespace-pre-wrap break-words text-muted-foreground",children:zRt({sourceId:e.sourceId,url:e.url})})]})}function XRt({part:e}){return l.jsxs("div",{className:"space-y-1 text-xs",children:[l.jsxs("div",{className:"font-medium",children:["📄 ",e.title]}),l.jsx(zn,{viewOnly:!0,value:{sourceId:e.sourceId,mediaType:e.mediaType,filename:e.filename}})]})}function tle({label:e,value:t}){return l.jsxs("div",{className:"space-y-1 text-xs",children:[l.jsx("div",{className:"font-medium",children:e}),l.jsx(zn,{value:t,viewOnly:!0})]})}function JRt({text:e,role:t}){const n="text-foreground",r=t==="user"?"text-right":"";return l.jsx(NI,{content:e,className:`max-w-full break-words overflow-auto ${n} ${r}`})}function QRt({resource:e,onSendFollowUp:t}){const n=async r=>{switch(r.type){case"tool":console.info("MCP UI tool action received:",r.payload),t(`Call tool ${r.payload.toolName} with parameters ${JSON.stringify(r.payload.params)}`);break;case"link":if(r.payload?.url&&typeof window<"u")return window.open(r.payload.url,"_blank","noopener,noreferrer"),{status:"handled"};break;case"prompt":if(r.payload?.prompt)return t(`Prompt: ${r.payload.prompt}`),{status:"handled"};break;case"intent":if(r.payload?.intent)return t(`Intent: ${r.payload.intent}`),{status:"handled"};break;case"notify":if(r.payload?.message)return t(`Notification: ${r.payload.message}`),{status:"handled"};break}return{status:"unhandled"}};return l.jsx("div",{className:"w-full overflow-hidden rounded-2xl border border-border/40 bg-muted/20 shadow-sm",children:l.jsx(ske,{resource:e,htmlProps:{style:{border:"2px",borderRadius:"4px",minHeight:"400px"},iframeProps:{title:"Custom MCP Resource",className:"mcp-resource-frame"}},remoteDomProps:{library:YH,remoteElements:[hdt,mdt,gdt,pdt,vdt]},onUIAction:n})})}function xK({isAuthenticated:e,workspaceId:t}){const n=e&&!!t,r=Ua("views:listAllByWorkspace",n?{workspaceId:t}:"skip"),i=n&&r===void 0,a=b.useMemo(()=>r?[...r].sort((c,d)=>d.updatedAt-c.updatedAt):[],[r]),s=b.useMemo(()=>{if(!r)return new Map;const c=new Map;for(const d of r){const f=c.get(d.serverId)||[];c.set(d.serverId,[...f,d])}return c},[r]),o=b.useMemo(()=>{if(!r)return new Map;const c=new Map;for(const d of r){const f=d.category||"Uncategorized",p=c.get(f)||[];c.set(f,[...p,d])}return c},[r]),u=b.useMemo(()=>r?{mcp:r.filter(c=>c.protocol==="mcp-apps"),openai:r.filter(c=>c.protocol==="openai-apps")}:{mcp:[],openai:[]},[r]);return{views:r,sortedViews:a,viewsByServer:s,viewsByCategory:o,viewsByProtocol:u,isLoading:i,hasViews:(r?.length??0)>0}}function NPe(){const e=_n("mcpAppViews:create"),t=_n("mcpAppViews:update"),n=_n("mcpAppViews:remove"),r=_n("mcpAppViews:generateUploadUrl"),i=_n("openaiAppViews:create"),a=_n("openaiAppViews:update"),s=_n("openaiAppViews:remove"),o=_n("openaiAppViews:generateUploadUrl");return{createMcpView:e,updateMcpView:t,removeMcpView:n,generateMcpUploadUrl:r,createOpenaiView:i,updateOpenaiView:a,removeOpenaiView:s,generateOpenaiUploadUrl:o}}function bK({isAuthenticated:e,workspaceId:t}){const n=e&&!!t,r=Ua("servers:getWorkspaceServers",n?{workspaceId:t}:"skip"),i=n&&r===void 0,a=b.useMemo(()=>{if(!r)return new Map;const o=new Map;for(const u of r)o.set(u.name,u._id);return o},[r]),s=b.useMemo(()=>{if(!r)return new Map;const o=new Map;for(const u of r)o.set(u._id,u.name);return o},[r]);return{servers:r,serversByName:a,serversById:s,isLoading:i}}function ePt(){return{createServer:_n("servers:createServer")}}function CPe(){const e=Zt(a=>a.deviceType),t=Zt(a=>a.customViewport),n=Zt(a=>a.globals),r=Zt(a=>a.capabilities),i=Zt(a=>a.safeAreaInsets);return{theme:n.theme,displayMode:n.displayMode,deviceType:e==="custom"?void 0:e,viewport:e==="custom"?{width:t.width,height:t.height}:void 0,locale:n.locale,timeZone:n.timeZone,capabilities:r,safeAreaInsets:i}}function nle(e,t){return JSON.stringify(e)===JSON.stringify(t)}function tPt(e,t){if(!t.has(e))return e;let n=2;for(;t.has(`${e} (${n})`);)n++;return`${e} (${n})`}function nPt({isAuthenticated:e,workspaceId:t,serverName:n,existingViewNames:r=new Set}){const[i,a]=b.useState(!1),s=CPe(),{createMcpView:o,createOpenaiView:u,generateMcpUploadUrl:c,generateOpenaiUploadUrl:d}=NPe(),{serversByName:f}=bK({isAuthenticated:e,workspaceId:t}),{createServer:p}=ePt(),m=b.useCallback(async S=>{const w=f.get(S);if(w)return w;if(!t)throw new Error("No workspace selected");return await p({workspaceId:t,name:S,enabled:!0,transportType:"http"})},[f,t,p]),y=b.useCallback(async(S,w)=>{const T=w==="mcp-apps"?await c({}):await d({}),N=new Blob([JSON.stringify(S)],{type:"application/json"}),E=await fetch(T,{method:"POST",body:N});if(!E.ok)throw new Error("Failed to upload output blob");return(await E.json()).storageId},[c,d]),v=b.useCallback(async(S,w)=>{const T=w==="mcp-apps"?await c({}):await d({}),N=new Blob([S],{type:"text/html"}),E=await fetch(T,{method:"POST",body:N});if(!E.ok)throw new Error("Failed to upload widget HTML blob");return(await E.json()).storageId},[c,d]),x=b.useCallback(async(S,w)=>{if(!t)return Pe.error("No workspace selected"),null;if(!w.name.trim())return Pe.error("View name is required"),null;a(!0);try{const T=S.uiType===bn.OPENAI_SDK?"openai-apps":"mcp-apps",N=await m(n),E=await y(S.output,T);let A;S.widgetHtml&&(A=await v(S.widgetHtml,T));const I={workspaceId:t,serverId:N,name:w.name.trim(),description:w.description,toolName:S.toolName,toolState:S.state,toolInput:S.input,toolOutputBlobId:E,toolErrorText:S.errorText,prefersBorder:w.prefersBorder,tags:w.tags,category:w.category,defaultContext:w.defaultContext,toolMetadata:S.toolMetadata};let M;if(T==="mcp-apps"){const $=S.widgetDebugInfo?.csp,O=$?{connectDomains:$.connectDomains,resourceDomains:$.resourceDomains,frameDomains:$.frameDomains,baseUriDomains:$.baseUriDomains}:void 0;M=await o({...I,resourceUri:S.resourceUri||`mcp://${n}/${S.toolName}`,toolsMetadata:S.toolsMetadata,widgetCsp:O,widgetPermissions:S.widgetPermissions,widgetPermissive:S.widgetPermissive,widgetHtmlBlobId:A})}else M=await u({...I,outputTemplate:S.outputTemplate||"",serverInfo:S.serverInfo,widgetHtmlBlobId:A});return Pe.success(`View "${w.name}" saved successfully`),M}catch(T){console.error("Failed to save view:",T);const N=T instanceof Error?T.message:"Failed to save view";return Pe.error(N),null}finally{a(!1)}},[t,n,m,y,v,o,u]),_=b.useCallback(async S=>{const w=`${n}-${S.toolName}`,T=tPt(w,r);return x(S,{name:T,defaultContext:s})},[x,n,r,s]);return{saveView:x,saveViewInstant:_,isSaving:i}}function cD({part:e,role:t,onSendFollowUp:n,toolsMetadata:r,toolServerMap:i,onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y,selectedProtocolOverrideIfBothExists:v=bn.OPENAI_SDK,onToolApprovalResponse:x,messageParts:_}){const[S,w]=b.useState(),{isAuthenticated:T}=Ba(),N=ci(),E=Rx(),I=E.workspaces[E.activeWorkspaceId]?.sharedWorkspaceId??null,M=uD(e)||Q1(e)?Qoe(e):null,$=(M?JU(M.toolName,i):void 0)??E.selectedServer??"unknown",{sortedViews:O}=xK({isAuthenticated:T,workspaceId:I}),R=b.useMemo(()=>new Set(O.map(q=>q.name)),[O]),{saveViewInstant:U,isSaving:z}=nPt({isAuthenticated:T,workspaceId:I,serverName:$,existingViewNames:R}),F=uD(e)||Q1(e)?e.toolCallId:void 0,D=bs(q=>F?q.widgets.get(F):void 0),W=b.useCallback((q,X,L,Y,G,P,V,K,Q)=>async()=>{N.capture("save_as_view_clicked",{location:"chat_tool_result",platform:Et(),environment:void 0});const oe={uiType:P,toolName:q,toolCallId:F,input:X,output:L,errorText:Y,state:G,widgetDebugInfo:D?{csp:D.csp,protocol:D.protocol,modelContext:D.modelContext}:void 0,resourceUri:V,outputTemplate:K,toolMetadata:Q,widgetHtml:D?.widgetHtml};await U(oe)},[F,D,U,N]);if(uD(e)||Q1(e)){const q=e,X=M??Qoe(q),L=q.approval?.id,Y=L?{approvalId:L,onApprove:ne=>x?.({id:ne,approved:!0}),onDeny:ne=>x?.({id:ne,approved:!1})}:{},G=r[X.toolName],P=oh(G,X.rawOutput),V=_mt(P,G),K=P===bn.MCP_UI?MRt(X.rawOutput):null,Q=JU(X.toolName,i),oe=X.output!==void 0||X.rawOutput!==void 0||X.toolState==="output-available"||X.toolState==="output-error",re=T&&!!I&&oe;let ee;T?I?oe||(ee="No output to save"):ee="Select a shared workspace to save views":ee="Sign in to save views";const le=X.output??X.rawOutput,te=G?.["openai/outputTemplate"],Z=W(X.toolName,X.input,le,X.errorText,X.toolState==="output-error"?"output-error":"output-available",P||bn.MCP_APPS,V??void 0,te,G);return K?l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y}),l.jsx(QRt,{resource:K.resource,onSendFollowUp:n})]}):P===bn.OPENAI_SDK||P===bn.OPENAI_SDK_AND_MCP_APPS&&v===bn.OPENAI_SDK?X.toolState!=="output-available"&&X.toolState!=="approval-requested"&&X.toolState!=="output-denied"?l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,onSaveView:Z,canSaveView:!1,isSaving:z,...Y}),l.jsx("div",{className:"border border-border/40 rounded-md bg-muted/30 text-xs text-muted-foreground px-3 py-2",children:"Waiting for tool to finish executing..."})]}):Q?l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,displayMode:m,pipWidgetId:o,fullscreenWidgetId:u,onDisplayModeChange:y,onRequestFullscreen:f,onExitFullscreen:p,onRequestPip:c,onExitPip:d,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y}),l.jsx(vK,{serverId:Q,toolCallId:X.toolCallId,toolName:X.toolName,toolState:X.toolState,toolInput:X.input??null,toolOutput:X.output??null,toolMetadata:r[X.toolName]??void 0,onSendFollowUp:n,onCallTool:(ne,J)=>kne(Q,ne,J),onWidgetStateChange:a,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y})]}):l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y}),l.jsx("div",{className:"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",children:"Failed to load tool server id."})]}):P===bn.MCP_APPS||P===bn.OPENAI_SDK_AND_MCP_APPS&&v===bn.MCP_APPS?!Q||!V||!X.toolCallId?l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y}),l.jsx("div",{className:"border border-destructive/40 bg-destructive/10 text-destructive text-xs rounded-md px-3 py-2",children:"Failed to load server id or resource uri for MCP App."})]}):l.jsxs(l.Fragment,{children:[l.jsx(Yh,{part:q,uiType:P,displayMode:m,pipWidgetId:o,fullscreenWidgetId:u,onDisplayModeChange:y,onRequestFullscreen:f,onExitFullscreen:p,onRequestPip:c,onExitPip:d,appSupportedDisplayModes:S,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y}),l.jsx(yK,{serverId:Q,toolCallId:X.toolCallId,toolName:X.toolName,toolState:X.toolState,toolInput:X.input,toolOutput:X.output,toolErrorText:X.errorText,resourceUri:V,toolMetadata:G,toolsMetadata:r,onSendFollowUp:n,onCallTool:(ne,J)=>kne(Q,ne,J),onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,displayMode:m,onDisplayModeChange:y,onRequestFullscreen:f,onExitFullscreen:p,onAppSupportedDisplayModesChange:w})]}):l.jsx(Yh,{part:q,uiType:P,onSaveView:Z,canSaveView:re,saveDisabledReason:ee,isSaving:z,...Y})}if(DRt(e))return l.jsx(tle,{label:LRt(e.type),value:e.data});switch(e.type){case"text":return l.jsx(JRt,{text:e.text,role:t});case"reasoning":return l.jsx(GRt,{text:e.text,state:e.state});case"file":return l.jsx(ZRt,{part:e});case"source-url":return l.jsx(YRt,{part:e});case"source-document":return l.jsx(XRt,{part:e});case"step-start":return null;default:return l.jsx(tle,{label:"Unknown part",value:e})}}function rPt({message:e,model:t,onSendFollowUp:n,toolsMetadata:r,toolServerMap:i,onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y,selectedProtocolOverrideIfBothExists:v,onToolApprovalResponse:x}){const _=eo(N=>N.themeMode),S=gPe(t,_);if(e.id?.startsWith("widget-state-")||e.id?.startsWith("model-context-"))return null;const w=e.role;if(w!=="user"&&w!=="assistant")return null;if(w==="user"){const N=e.parts?.filter(A=>A.type==="file")??[],E=e.parts?.filter(A=>A.type!=="file")??[];return l.jsxs("div",{className:"flex flex-col items-end gap-2",children:[N.length>0&&l.jsx("div",{className:"flex flex-wrap justify-end gap-2 max-w-3xl",children:N.map((A,I)=>l.jsx(cD,{part:A,role:w,onSendFollowUp:n,toolsMetadata:r,toolServerMap:i,onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y,selectedProtocolOverrideIfBothExists:v},`file-${I}`))}),(E.length>0||N.length===0)&&l.jsx(pRt,{children:E.map((A,I)=>l.jsx(cD,{part:A,role:w,onSendFollowUp:n,toolsMetadata:r,toolServerMap:i,onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y,selectedProtocolOverrideIfBothExists:v},I))})]})}const T=$Rt(e.parts??[]);return l.jsxs("article",{className:"flex gap-4 w-full",children:[l.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border/40 bg-muted/40",children:S?l.jsx("img",{src:S,alt:`${t.id} logo`,className:"h-4 w-4 object-contain"}):l.jsx(Bm,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx("div",{className:"flex-1 min-w-0 space-y-6 text-sm leading-6",children:T.map((N,E)=>l.jsx("div",{className:"space-y-3",children:N.map((A,I)=>l.jsx(cD,{part:A,role:w,onSendFollowUp:n,toolsMetadata:r,toolServerMap:i,onWidgetStateChange:a,onModelContextUpdate:s,pipWidgetId:o,fullscreenWidgetId:u,onRequestPip:c,onExitPip:d,onRequestFullscreen:f,onExitFullscreen:p,displayMode:m,onDisplayModeChange:y,selectedProtocolOverrideIfBothExists:v,onToolApprovalResponse:x,messageParts:e.parts},`${E}-${I}`))},E))})]})}function iPt({model:e}){const t=eo(r=>r.themeMode),n=gPe(e,t);return l.jsxs("article",{className:"flex w-full gap-4 text-sm leading-6 text-muted-foreground","aria-live":"polite","aria-busy":"true",children:[l.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border/40 bg-muted/40",children:n?l.jsx("img",{src:n,alt:`${e.id} logo`,className:"h-4 w-4 object-contain"}):l.jsx(Bm,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx("div",{className:"flex-1 min-w-0",children:l.jsx("div",{className:"inline-flex items-center gap-2 text-muted-foreground/80",children:l.jsxs("span",{className:"text-sm italic",children:["Thinking",l.jsxs("span",{className:"inline-flex",children:[l.jsx("span",{className:"animate-[blink_1.4s_ease-in-out_infinite]",children:"."}),l.jsx("span",{className:"animate-[blink_1.4s_ease-in-out_0.2s_infinite]",children:"."}),l.jsx("span",{className:"animate-[blink_1.4s_ease-in-out_0.4s_infinite]",children:"."})]})]})})})]})}function aPt(e){const n=(Array.isArray(e?.parts)?e.parts:[]).map(r=>!r||typeof r!="object"?"":r.type==="text"&&typeof r.text=="string"||"text"in r&&typeof r.text=="string"?r.text:"").filter(Boolean);return n.length>0?n.join(`
|
|
1770
1770
|
`).trim():typeof e?.content=="string"?e.content.trim():""}function sPt({text:e,isUser:t}){return l.jsx("div",{className:Ie("flex w-full",t?"justify-end":"justify-start"),children:l.jsx("div",{className:Ie("max-w-[85%] rounded-2xl px-3 py-2 text-sm leading-6 whitespace-pre-wrap",t?"bg-primary text-primary-foreground":"bg-muted text-foreground"),children:e})})}function oPt(){return l.jsx("div",{className:"flex w-full justify-start",children:l.jsx("div",{className:"inline-flex items-center gap-2 rounded-2xl bg-muted px-3 py-2 text-sm text-muted-foreground/80",children:l.jsxs("span",{className:"italic",children:["Thinking",l.jsxs("span",{className:"inline-flex",children:[l.jsx("span",{className:"animate-[blink_1.4s_ease-in-out_infinite]",children:"."}),l.jsx("span",{className:"animate-[blink_1.4s_ease-in-out_0.2s_infinite]",children:"."}),l.jsx("span",{className:"animate-[blink_1.4s_ease-in-out_0.4s_infinite]",children:"."})]})]})})})}function lPt({open:e,onToggle:t}){return l.jsx("button",{type:"button","aria-label":e?"Collapse chat":"Expand chat",className:Ie("absolute left-1/2 -translate-x-1/2 z-10 transition-all duration-200",e?"-top-11":"-top-9","inline-flex h-8 w-8 items-center justify-center rounded-full","border border-border/40 bg-background/95 shadow-sm backdrop-blur-md","text-muted-foreground hover:text-foreground hover:bg-background hover:border-border/60"),onClick:t,children:e?l.jsx(Wr,{className:"h-4 w-4"}):l.jsx(Ex,{className:"h-4 w-4"})})}function uPt({messages:e,isThinking:t,open:n}){const r=b.useRef(null),i=b.useMemo(()=>e.filter(a=>!a.id?.startsWith("widget-state-")).filter(a=>a.role==="user"||a.role==="assistant"),[e]);return b.useEffect(()=>{n&&r.current?.scrollIntoView({block:"end"})},[n,i.length,t]),n?l.jsx("div",{className:"mb-4 overflow-hidden rounded-3xl border border-border/40 bg-background/95 shadow-2xl backdrop-blur-xl",children:l.jsxs("div",{className:"max-h-[45vh] overflow-y-auto px-4 py-3 space-y-3",children:[i.map((a,s)=>{const o=aPt(a);return o?l.jsx(sPt,{text:o,isUser:a.role==="user"},a.id??`${a.role}-${s}`):null}),t&&l.jsx(oPt,{}),l.jsx("div",{ref:r})]})}):null}function cPt({value:e,onChange:t,placeholder:n,disabled:r,canSend:i,onSubmit:a}){const s=u=>{u.preventDefault(),i&&a()},o=u=>{if(u.key==="Enter"&&!u.shiftKey&&!u.nativeEvent.isComposing){if(u.preventDefault(),!i)return;a()}};return l.jsx("form",{onSubmit:s,className:"rounded-full border border-border/40 bg-background/95 backdrop-blur-xl",children:l.jsxs("div",{className:"flex items-center gap-2 px-6 py-3",children:[l.jsx(IRe,{value:e,onChange:u=>t(u.target.value),onKeyDown:o,placeholder:n,disabled:r,readOnly:r,minRows:1,maxRows:3,className:Ie("w-full resize-none border-none bg-transparent px-0 py-0 min-h-0 text-sm leading-tight","placeholder:text-muted-foreground/60 shadow-none","focus-visible:ring-0 focus-visible:outline-none focus-visible:border-none")}),l.jsx(Ee,{type:"submit",size:"icon",className:Ie("size-8 rounded-full shrink-0 transition-all",i?"bg-primary text-primary-foreground hover:bg-primary/90":"bg-muted text-muted-foreground cursor-not-allowed",i&&"hover:scale-105"),disabled:!i,children:l.jsx(k1e,{className:"h-4 w-4"})})]})})}function APe({messages:e,open:t,onOpenChange:n,input:r,onInputChange:i,placeholder:a,disabled:s,canSend:o,isThinking:u,onSend:c}){return l.jsx("div",{className:"pointer-events-none fixed inset-x-0 bottom-6 z-50",children:l.jsx("div",{className:"pointer-events-auto mx-auto w-full max-w-3xl px-4 pb-4",style:{paddingBottom:"env(safe-area-inset-bottom)"},children:l.jsxs("div",{className:"relative",children:[l.jsx(lPt,{open:t,onToggle:()=>n(!t)}),l.jsx(uPt,{messages:e,isThinking:u,open:t}),l.jsx(cPt,{value:r,onChange:i,placeholder:a,disabled:s,canSend:o,onSubmit:()=>{n(!0),c()}})]})})})}function IPe({messages:e,sendFollowUpMessage:t,model:n,isLoading:r,toolsMetadata:i,toolServerMap:a,onWidgetStateChange:s,onModelContextUpdate:o,displayMode:u,onDisplayModeChange:c,onFullscreenChange:d,enableFullscreenChatOverlay:f=!1,fullscreenChatPlaceholder:p="Message…",fullscreenChatDisabled:m=!1,selectedProtocolOverrideIfBothExists:y,onToolApprovalResponse:v}){const[x,_]=b.useState(null),[S,w]=b.useState(null),[T,N]=b.useState(!1),[E,A]=b.useState(""),I=z=>{_(z)},M=z=>{x===z&&_(null)},$=z=>{w(z),d?.(!0)},O=z=>{S===z&&(w(null),d?.(!1))},R=f&&S!==null;b.useEffect(()=>{R||(N(!1),A(""))},[R]);const U=!m&&E.trim().length>0;return l.jsxs("div",{className:"flex-1 min-h-0 pb-4",children:[x&&l.jsx("div",{className:"h-[480px] flex-shrink-0 pointer-events-none"}),l.jsxs("div",{className:"max-w-4xl mx-auto px-4 pt-8 pb-16 space-y-8",children:[e.map((z,F)=>l.jsx(rPt,{message:z,model:n,onSendFollowUp:t,toolsMetadata:i,toolServerMap:a,onWidgetStateChange:s,onModelContextUpdate:o,pipWidgetId:x,fullscreenWidgetId:S,onRequestPip:I,onExitPip:M,onRequestFullscreen:$,onExitFullscreen:O,displayMode:u,onDisplayModeChange:c,selectedProtocolOverrideIfBothExists:y,onToolApprovalResponse:v},F)),r&&l.jsx(iPt,{model:n})]}),R&&l.jsx(APe,{messages:e,open:T,onOpenChange:N,input:E,onInputChange:A,placeholder:p,disabled:m,canSend:U,isThinking:r,onSend:()=>{if(!U)return;const z=E;N(!0),A(""),t(z)}})]})}function jPe({onSignUp:e,className:t}){return l.jsxs("div",{className:Ie("max-w-2xl mx-auto space-y-4 text-center flex flex-col items-center justify-center",t),children:[l.jsx("div",{className:"space-y-1",children:l.jsx("h2",{className:"text-2xl font-semibold tracking-tight",children:"Test your MCP server with frontier models for free"})}),l.jsxs("div",{className:"flex justify-center items-center gap-4 py-3",children:[l.jsx("div",{className:"flex items-center justify-center",children:l.jsx("img",{src:"/claude_logo.png",alt:"Claude",className:"w-8 h-8 object-contain opacity-70 hover:opacity-100 transition-opacity"})}),l.jsx("div",{className:"flex items-center justify-center",children:l.jsx("img",{src:"/openai_logo.png",alt:"OpenAI",className:"w-8 h-8 object-contain opacity-70 hover:opacity-100 transition-opacity"})}),l.jsx("div",{className:"flex items-center justify-center",children:l.jsx("img",{src:"/google_logo.png",alt:"Google",className:"w-8 h-8 object-contain opacity-70 hover:opacity-100 transition-opacity"})}),l.jsx("div",{className:"flex items-center justify-center",children:l.jsx("img",{src:"/meta_logo.svg",alt:"Meta",className:"w-8 h-8 object-contain opacity-70 hover:opacity-100 transition-opacity"})}),l.jsx("div",{className:"flex items-center justify-center",children:l.jsx("img",{src:"/grok_light.svg",alt:"Grok",className:"w-8 h-8 object-contain opacity-70 hover:opacity-100 transition-opacity"})})]}),l.jsxs("div",{className:"space-y-2 text-center",children:[l.jsx(Ee,{onClick:e,size:"lg",className:"hover:opacity-90 cursor-pointer font-semibold px-8 py-6 text-base",children:"Get started"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:["or bring your own API key in"," ",l.jsx("a",{href:"#settings",className:"underline hover:text-foreground transition-colors",children:"settings"})]})]})]})}function qR({...e}){return l.jsx(Uve,{"data-slot":"collapsible",...e})}function HR({...e}){return l.jsx(F9,{"data-slot":"collapsible-trigger",...e})}function VR({...e}){return l.jsx(q9,{"data-slot":"collapsible-content",...e})}const dPt=e=>{if(!e)return null;try{return JSON.parse(e)}catch{return null}};function OPe({message:e,errorDetails:t,onResetChat:n,code:r,statusCode:i,isRetryable:a,isMCPJamPlatformError:s,onRetry:o}){const[u,c]=b.useState(!1),d=dPt(t),f=s===!0,p=f?"border-warning bg-warning/20 text-warning-foreground":"border-destructive bg-destructive/20 text-destructive-foreground",m=f?"text-warning":"text-destructive",y=f?"text-warning hover:text-warning/80":"text-destructive hover:text-destructive/80",v=f?"border-warning/30":"border-destructive/30",x=f?"text-warning-foreground":"text-destructive-foreground",_=f?"MCPJam platform issue":"An error occurred";return l.jsxs("div",{className:Ie("flex flex-col gap-3 border rounded p-4",p),children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(Gs,{className:Ie("h-6 w-6 flex-shrink-0",m)}),l.jsxs("div",{className:"flex-1",children:[l.jsxs("p",{className:"text-sm leading-6",children:[_,": ",e]}),f&&l.jsx("p",{className:"text-xs opacity-75 mt-0.5",children:"This is a temporary issue on our end."})]}),l.jsxs("div",{className:"flex items-center gap-2 ml-auto flex-shrink-0",children:[a&&o&&l.jsxs(Ee,{type:"button",variant:"outline",size:"sm",onClick:o,className:"gap-1.5",children:[l.jsx(wn,{className:"h-3.5 w-3.5"}),"Retry"]}),l.jsx(Ee,{type:"button",variant:"outline",onClick:n,children:"Reset chat"})]})]}),t&&l.jsxs(qR,{open:u,onOpenChange:c,children:[l.jsxs(HR,{className:Ie("flex items-center gap-1.5 text-xs transition-colors",y),children:[l.jsx("span",{children:"More details"}),u?l.jsx(Wr,{className:"h-3 w-3"}):l.jsx(wr,{className:"h-3 w-3"})]}),l.jsx(VR,{className:"mt-2",children:l.jsx("div",{className:Ie("rounded border bg-background/50 p-2",v),children:d?l.jsx(zn,{value:d,readOnly:!0,showToolbar:!1}):l.jsx("pre",{className:Ie("text-xs font-mono whitespace-pre-wrap overflow-x-auto",x),children:t})})})]})]})}const fPt={damping:.7,stiffness:.05,mass:1.25},pPt=70,hPt=1e3/60,mPt=350;let GR=!1;globalThis.document?.addEventListener("mousedown",()=>{GR=!0});globalThis.document?.addEventListener("mouseup",()=>{GR=!1});globalThis.document?.addEventListener("click",()=>{GR=!1});const gPt=(e={})=>{const[t,n]=b.useState(!1),[r,i]=b.useState(e.initial!==!1),[a,s]=b.useState(!1),o=b.useRef(null);o.current=e;const u=b.useCallback(()=>{if(!GR)return!1;const S=window.getSelection();if(!S||!S.rangeCount)return!1;const w=S.getRangeAt(0);return w.commonAncestorContainer.contains(x.current)||x.current?.contains(w.commonAncestorContainer)},[]),c=b.useCallback(S=>{f.isAtBottom=S,i(S)},[]),d=b.useCallback(S=>{f.escapedFromLock=S,n(S)},[]),f=b.useMemo(()=>{let S;return{escapedFromLock:t,isAtBottom:r,resizeDifference:0,accumulated:0,velocity:0,listeners:new Set,get scrollTop(){return x.current?.scrollTop??0},set scrollTop(w){x.current&&(x.current.scrollTop=w,f.ignoreScrollToTop=x.current.scrollTop)},get targetScrollTop(){return!x.current||!_.current?0:x.current.scrollHeight-1-x.current.clientHeight},get calculatedTargetScrollTop(){if(!x.current||!_.current)return 0;const{targetScrollTop:w}=this;if(!e.targetScrollTop)return w;if(S?.targetScrollTop===w)return S.calculatedScrollTop;const T=Math.max(Math.min(e.targetScrollTop(w,{scrollElement:x.current,contentElement:_.current}),w),0);return S={targetScrollTop:w,calculatedScrollTop:T},requestAnimationFrame(()=>{S=void 0}),T},get scrollDifference(){return this.calculatedTargetScrollTop-this.scrollTop},get isNearBottom(){return this.scrollDifference<=pPt}}},[]),p=b.useCallback((S={})=>{typeof S=="string"&&(S={animation:S}),S.preserveScrollPosition||c(!0);const w=Date.now()+(Number(S.wait)||0),T=fD(o.current,S.animation),{ignoreEscapes:N=!1}=S;let E,A=f.calculatedTargetScrollTop;S.duration instanceof Promise?S.duration.finally(()=>{E=Date.now()}):E=w+(S.duration??0);const I=async()=>{const M=new Promise(requestAnimationFrame).then(()=>{if(!f.isAtBottom)return f.animation=void 0,!1;const{scrollTop:$}=f,O=performance.now(),R=(O-(f.lastTick??O))/hPt;if(f.animation||(f.animation={behavior:T,promise:M,ignoreEscapes:N}),f.animation.behavior===T&&(f.lastTick=O),u()||w>Date.now())return I();if($<Math.min(A,f.calculatedTargetScrollTop)){if(f.animation?.behavior===T){if(T==="instant")return f.scrollTop=f.calculatedTargetScrollTop,I();f.velocity=(T.damping*f.velocity+T.stiffness*f.scrollDifference)/T.mass,f.accumulated+=f.velocity*R,f.scrollTop+=f.accumulated,f.scrollTop!==$&&(f.accumulated=0)}return I()}return E>Date.now()?(A=f.calculatedTargetScrollTop,I()):(f.animation=void 0,f.scrollTop<f.calculatedTargetScrollTop?p({animation:fD(o.current,o.current.resize),ignoreEscapes:N,duration:Math.max(0,E-Date.now())||void 0}):f.isAtBottom)});return M.then($=>(requestAnimationFrame(()=>{f.animation||(f.lastTick=void 0,f.velocity=0)}),$))};return S.wait!==!0&&(f.animation=void 0),f.animation?.behavior===T?f.animation.promise:I()},[c,u,f]),m=b.useCallback(()=>{d(!0),c(!1)},[d,c]),y=b.useCallback(({target:S})=>{if(S!==x.current)return;const{scrollTop:w,ignoreScrollToTop:T}=f;let{lastScrollTop:N=w}=f;f.lastScrollTop=w,f.ignoreScrollToTop=void 0,T&&T>w&&(N=T),s(f.isNearBottom),setTimeout(()=>{if(f.resizeDifference||w===T)return;if(u()){d(!0),c(!1);return}const E=w>N,A=w<N;if(f.animation?.ignoreEscapes){f.scrollTop=N;return}A&&(d(!0),c(!1)),E&&d(!1),!f.escapedFromLock&&f.isNearBottom&&c(!0)},1)},[d,c,u,f]),v=b.useCallback(({target:S,deltaY:w})=>{let T=S;for(;!["scroll","auto"].includes(getComputedStyle(T).overflow);){if(!T.parentElement)return;T=T.parentElement}T===x.current&&w<0&&x.current.scrollHeight>x.current.clientHeight&&!f.animation?.ignoreEscapes&&(d(!0),c(!1))},[d,c,f]),x=rle(S=>{x.current?.removeEventListener("scroll",y),x.current?.removeEventListener("wheel",v),S?.addEventListener("scroll",y,{passive:!0}),S?.addEventListener("wheel",v,{passive:!0})},[]),_=rle(S=>{if(f.resizeObserver?.disconnect(),!S)return;let w;f.resizeObserver=new ResizeObserver(([T])=>{const{height:N}=T.contentRect,E=N-(w??N);if(f.resizeDifference=E,f.scrollTop>f.targetScrollTop&&(f.scrollTop=f.targetScrollTop),s(f.isNearBottom),E>=0){const A=fD(o.current,w?o.current.resize:o.current.initial);p({animation:A,wait:!0,preserveScrollPosition:!0,duration:A==="instant"?void 0:mPt})}else f.isNearBottom&&(d(!1),c(!0));w=N,requestAnimationFrame(()=>{setTimeout(()=>{f.resizeDifference===E&&(f.resizeDifference=0)},1)})}),f.resizeObserver?.observe(S)},[]);return{contentRef:_,scrollRef:x,scrollToBottom:p,stopScroll:m,isAtBottom:r||a,isNearBottom:a,escapedFromLock:t,state:f}};function rle(e,t){const n=b.useCallback(r=>(n.current=r,e(r)),t);return n}const dD=new Map;function fD(...e){const t={...fPt};let n=!1;for(const i of e){if(i==="instant"){n=!0;continue}typeof i=="object"&&(n=!1,t.damping=i.damping??t.damping,t.stiffness=i.stiffness??t.stiffness,t.mass=i.mass??t.mass)}const r=JSON.stringify(t);return dD.has(r)||dD.set(r,Object.freeze(t)),n?"instant":dD.get(r)}const RPe=b.createContext(null),vPt=typeof window<"u"?b.useLayoutEffect:b.useEffect;function gc({instance:e,children:t,resize:n,initial:r,mass:i,damping:a,stiffness:s,targetScrollTop:o,contextRef:u,...c}){const d=b.useRef(null),f=b.useCallback((N,E)=>(T?.targetScrollTop??o)?.(N,E)??N,[o]),p=gPt({mass:i,damping:a,stiffness:s,resize:n,initial:r,targetScrollTop:f}),{scrollRef:m,contentRef:y,scrollToBottom:v,stopScroll:x,isAtBottom:_,escapedFromLock:S,state:w}=e??p,T=b.useMemo(()=>({scrollToBottom:v,stopScroll:x,scrollRef:m,isAtBottom:_,escapedFromLock:S,contentRef:y,state:w,get targetScrollTop(){return d.current},set targetScrollTop(N){d.current=N}}),[v,_,y,m,x,S,w]);return b.useImperativeHandle(u,()=>T,[T]),vPt(()=>{m.current&&getComputedStyle(m.current).overflow==="visible"&&(m.current.style.overflow="auto")},[]),b.createElement(RPe.Provider,{value:T},b.createElement("div",{...c},typeof t=="function"?t(T):t))}(function(e){function t({children:n,scrollClassName:r,...i}){const a=_K();return b.createElement("div",{ref:a.scrollRef,style:{height:"100%",width:"100%",scrollbarGutter:"stable both-edges"},className:r},b.createElement("div",{...i,ref:a.contentRef},typeof n=="function"?n(a):n))}e.Content=t})(gc||(gc={}));function _K(){const e=b.useContext(RPe);if(!e)throw new Error("use-stick-to-bottom component context must be used within a StickToBottom component");return e}var pD,ile;function yPt(){if(ile)return pD;ile=1;function e(t,n){if(typeof t!="function")throw new TypeError(`Expected the first argument to be a \`function\`, got \`${typeof t}\`.`);let r,i=0;return function(...s){clearTimeout(r);const o=Date.now(),u=o-i,c=n-u;c<=0?(i=o,t.apply(this,s)):r=setTimeout(()=>{i=Date.now(),t.apply(this,s)},c)}}return pD=e,pD}var xPt=yPt();const bPt=Jn(xPt);var PPe=(e,t,n)=>{if(!t.has(e))throw TypeError("Cannot "+n)},hi=(e,t,n)=>(PPe(e,t,"read from private field"),n?n.call(e):t.get(e)),tc=(e,t,n)=>{if(t.has(e))throw TypeError("Cannot add the same private member more than once");t instanceof WeakSet?t.add(e):t.set(e,n)},op=(e,t,n,r)=>(PPe(e,t,"write to private field"),t.set(e,n),n);function _Pt(e,t){return t!=null?bPt(e,t):e}var bl,kC,EC,m1,g1,v1,ov,vF,yF,wPt=class{constructor(e=[]){tc(this,bl,void 0),tc(this,kC,"ready"),tc(this,EC,void 0),tc(this,m1,new Set),tc(this,g1,new Set),tc(this,v1,new Set),this.pushMessage=t=>{op(this,bl,hi(this,bl).concat(t)),hi(this,ov).call(this)},this.popMessage=()=>{op(this,bl,hi(this,bl).slice(0,-1)),hi(this,ov).call(this)},this.replaceMessage=(t,n)=>{op(this,bl,[...hi(this,bl).slice(0,t),this.snapshot(n),...hi(this,bl).slice(t+1)]),hi(this,ov).call(this)},this.snapshot=t=>structuredClone(t),this["~registerMessagesCallback"]=(t,n)=>{const r=n?_Pt(t,n):t;return hi(this,m1).add(r),()=>{hi(this,m1).delete(r)}},this["~registerStatusCallback"]=t=>(hi(this,g1).add(t),()=>{hi(this,g1).delete(t)}),this["~registerErrorCallback"]=t=>(hi(this,v1).add(t),()=>{hi(this,v1).delete(t)}),tc(this,ov,()=>{hi(this,m1).forEach(t=>t())}),tc(this,vF,()=>{hi(this,g1).forEach(t=>t())}),tc(this,yF,()=>{hi(this,v1).forEach(t=>t())}),op(this,bl,e)}get status(){return hi(this,kC)}set status(e){op(this,kC,e),hi(this,vF).call(this)}get error(){return hi(this,EC)}set error(e){op(this,EC,e),hi(this,yF).call(this)}get messages(){return hi(this,bl)}set messages(e){op(this,bl,[...e]),hi(this,ov).call(this)}};bl=new WeakMap;kC=new WeakMap;EC=new WeakMap;m1=new WeakMap;g1=new WeakMap;v1=new WeakMap;ov=new WeakMap;vF=new WeakMap;yF=new WeakMap;var lv,ale=class extends jOt{constructor({messages:e,...t}){const n=new wPt(e);super({...t,state:n}),tc(this,lv,void 0),this["~registerMessagesCallback"]=(r,i)=>hi(this,lv)["~registerMessagesCallback"](r,i),this["~registerStatusCallback"]=r=>hi(this,lv)["~registerStatusCallback"](r),this["~registerErrorCallback"]=r=>hi(this,lv)["~registerErrorCallback"](r),op(this,lv,n)}};lv=new WeakMap;function SPt({experimental_throttle:e,resume:t=!1,...n}={}){const r=b.useRef("chat"in n?{}:{onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});"chat"in n||(r.current={onToolCall:n.onToolCall,onData:n.onData,onFinish:n.onFinish,onError:n.onError,sendAutomaticallyWhen:n.sendAutomaticallyWhen});const i={...n,onToolCall:p=>{var m,y;return(y=(m=r.current).onToolCall)==null?void 0:y.call(m,p)},onData:p=>{var m,y;return(y=(m=r.current).onData)==null?void 0:y.call(m,p)},onFinish:p=>{var m,y;return(y=(m=r.current).onFinish)==null?void 0:y.call(m,p)},onError:p=>{var m,y;return(y=(m=r.current).onError)==null?void 0:y.call(m,p)},sendAutomaticallyWhen:p=>{var m,y,v;return(v=(y=(m=r.current).sendAutomaticallyWhen)==null?void 0:y.call(m,p))!=null?v:!1}},a=b.useRef("chat"in n?n.chat:new ale(i));("chat"in n&&n.chat!==a.current||"id"in n&&a.current.id!==n.id)&&(a.current="chat"in n?n.chat:new ale(i));const o=b.useCallback(p=>a.current["~registerMessagesCallback"](p,e),[e,a.current.id]),u=b.useSyncExternalStore(o,()=>a.current.messages,()=>a.current.messages),c=b.useSyncExternalStore(a.current["~registerStatusCallback"],()=>a.current.status,()=>a.current.status),d=b.useSyncExternalStore(a.current["~registerErrorCallback"],()=>a.current.error,()=>a.current.error),f=b.useCallback(p=>{typeof p=="function"&&(p=p(a.current.messages)),a.current.messages=p},[a]);return b.useEffect(()=>{t&&a.current.resumeStream()},[t,a]),{id:a.current.id,messages:u,setMessages:f,sendMessage:a.current.sendMessage,regenerate:a.current.regenerate,clearError:a.current.clearError,stop:a.current.stop,error:d,resumeStream:a.current.resumeStream,status:c,addToolResult:a.current.addToolOutput,addToolOutput:a.current.addToolOutput,addToolApprovalResponse:a.current.addToolApprovalResponse}}const sle="mcp-inspector-provider-tokens",Xh={anthropic:"",anthropicBaseUrl:"",azure:"",azureBaseUrl:"",openai:"",openaiBaseUrl:"",deepseek:"",google:"",mistral:"",xai:"",ollama:"local",ollamaBaseUrl:"http://127.0.0.1:11434/api",litellm:"",litellmBaseUrl:"http://localhost:4000",litellmModelAlias:"",openrouter:"",openRouterSelectedModels:[]};function zx(){const[e,t]=b.useState(Xh),[n,r]=b.useState(!1);b.useEffect(()=>{if(typeof window<"u"){try{const A=localStorage.getItem(sle);if(A){const I=JSON.parse(A);t(I)}}catch(A){console.warn("Failed to load provider tokens from localStorage:",A)}r(!0)}},[]),b.useEffect(()=>{if(n&&typeof window<"u")try{localStorage.setItem(sle,JSON.stringify(e))}catch(A){console.warn("Failed to save provider tokens to localStorage:",A)}},[e,n]);const i=b.useCallback((A,I)=>{t(M=>({...M,[A]:I}))},[]),a=b.useCallback(A=>{t(I=>({...I,[A]:""}))},[]),s=b.useCallback(()=>{t(Xh)},[]),o=b.useCallback(A=>{const I=e[A];return A==="openrouter"?!!e.openrouter?.trim()&&e.openRouterSelectedModels.length>0:Array.isArray(I)?I.length>0:!!I?.trim()},[e]),u=b.useCallback(A=>{const I=e[A];return Array.isArray(I)?I.join(", "):I||""},[e]),c=b.useCallback(()=>e.ollamaBaseUrl||Xh.ollamaBaseUrl,[e.ollamaBaseUrl]),d=b.useCallback(A=>{t(I=>({...I,ollamaBaseUrl:A}))},[]),f=b.useCallback(()=>e.litellmBaseUrl||Xh.litellmBaseUrl,[e.litellmBaseUrl]),p=b.useCallback(A=>{t(I=>({...I,litellmBaseUrl:A}))},[]),m=b.useCallback(()=>e.litellmModelAlias||Xh.litellmModelAlias,[e.litellmModelAlias]),y=b.useCallback(A=>{t(I=>({...I,litellmModelAlias:A}))},[]),v=b.useCallback(()=>e.azureBaseUrl||Xh.azureBaseUrl,[e.azureBaseUrl]),x=b.useCallback(A=>{t(I=>({...I,azureBaseUrl:A}))},[]),_=b.useCallback(()=>e.openRouterSelectedModels||Xh.openRouterSelectedModels,[e.openRouterSelectedModels]),S=b.useCallback(A=>{t(I=>({...I,openRouterSelectedModels:A}))},[]),w=b.useCallback(()=>e.anthropicBaseUrl||"",[e.anthropicBaseUrl]),T=b.useCallback(A=>{t(I=>({...I,anthropicBaseUrl:A}))},[]),N=b.useCallback(()=>e.openaiBaseUrl||"",[e.openaiBaseUrl]),E=b.useCallback(A=>{t(I=>({...I,openaiBaseUrl:A}))},[]);return{tokens:e,setToken:i,clearToken:a,clearAllTokens:s,hasToken:o,getToken:u,getOllamaBaseUrl:c,setOllamaBaseUrl:d,getLiteLLMBaseUrl:f,setLiteLLMBaseUrl:p,getLiteLLMModelAlias:m,setLiteLLMModelAlias:y,getOpenRouterSelectedModels:_,setOpenRouterSelectedModels:S,getAzureBaseUrl:v,setAzureBaseUrl:x,getAnthropicBaseUrl:w,setAnthropicBaseUrl:T,getOpenAIBaseUrl:N,setOpenAIBaseUrl:E}}const hD="mcp-inspector-selected-model";function kPt(){const[e,t]=b.useState(null),[n,r]=b.useState(!1);b.useEffect(()=>{if(typeof window<"u"){try{const a=localStorage.getItem(hD);a&&t(a)}catch(a){console.warn("Failed to load selected model from localStorage:",a)}r(!0)}},[]),b.useEffect(()=>{if(n&&typeof window<"u")try{e?localStorage.setItem(hD,e):localStorage.removeItem(hD)}catch(a){console.warn("Failed to save selected model to localStorage:",a)}},[e,n]);const i=b.useCallback(a=>{t(a)},[]);return{selectedModelId:e,setSelectedModelId:i}}function EPt(e,t){return e.split(",").map(n=>n.trim()).filter(n=>n.length>0).map(n=>({id:n,name:n,provider:t}))}function TPt(e){const{hasToken:t,getAzureBaseUrl:n,getLiteLLMBaseUrl:r,getLiteLLMModelAlias:i,getOpenRouterSelectedModels:a,isOllamaRunning:s,ollamaModels:o}=e,u={anthropic:t("anthropic"),openai:t("openai"),deepseek:t("deepseek"),google:t("google"),mistral:t("mistral"),xai:t("xai"),azure:!!n(),ollama:s,litellm:!!(r()&&i()),openrouter:!!(t("openrouter")&&a().length>0),meta:!1},c=dK.filter(m=>_r(m.id)?!0:u[m.provider]),d=u.litellm?EPt(i(),"litellm"):[],f=u.openrouter?a().map(m=>({id:m,name:m,provider:"openrouter"})):[];let p=c;return s&&o.length>0&&(p=p.concat(o)),d.length>0&&(p=p.concat(d)),f.length>0&&(p=p.concat(f)),p}const NPt=e=>{const t=["anthropic/claude-haiku-4.5","openai/gpt-5","meta-llama/llama-3.3-70b-instruct",cc.CLAUDE_3_7_SONNET_LATEST,cc.GPT_4_1,cc.GEMINI_2_5_PRO,cc.DEEPSEEK_CHAT,cc.MISTRAL_LARGE_LATEST];for(const n of t){const r=e.find(i=>i.id===n);if(r)return r}return e[0]};class rg{baseUrl;static normalizeBaseUrl(t){const n=(t||"").replace(/\/+$/,"");return/\/api$/.test(n)?n:`${n}/api`}constructor(t="http://127.0.0.1:11434/api"){this.baseUrl=rg.normalizeBaseUrl(t)}setBaseUrl(t){this.baseUrl=rg.normalizeBaseUrl(t)}async isOllamaRunning(){try{return(await fetch(`${this.baseUrl}/version`,{method:"GET",signal:AbortSignal.timeout(3e3)})).ok}catch{return!1}}async getAvailableModels(){try{const t=await fetch(`${this.baseUrl}/tags`,{method:"GET",signal:AbortSignal.timeout(5e3)});return t.ok?(await t.json()).models.map(r=>r.name):[]}catch(t){return console.warn("Failed to fetch Ollama models:",t),[]}}async checkModelExists(t){return(await this.getAvailableModels()).some(r=>r===t||r.startsWith(`${t}:`))}async getFilteredAvailableModels(t){const n=await this.getAvailableModels();return t.filter(r=>n.some(i=>i===r||i.startsWith(`${r}:`)))}async getToolCapableModels(){const t=await this.getAvailableModels();return t.length===0?[]:(await Promise.all(t.map(async r=>{try{const i=await fetch(`${this.baseUrl}/show`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({model:r}),signal:AbortSignal.timeout(5e3)});return i.ok&&(await i.json()).capabilities.includes("tools")?r:null}catch{return null}}))).flatMap(r=>r?[r]:[])}}const $Pe=async e=>{const t=e?new rg(e):new rg;return await t.isOllamaRunning()?{isRunning:!0,availableModels:await t.getAvailableModels()}:{isRunning:!1,availableModels:[]}},MPe=async e=>(e?new rg(e):new rg).getToolCapableModels();async function CPt(e,t){const n=await Yt("/api/mcp/tokenizer/count-text",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({text:e,modelId:t})});let r=null;try{r=await n.json()}catch{}if(!n.ok){const i=r?.error||`Count tokens failed (${n.status})`;throw new Error(i)}if(!r.ok)throw new Error(r.error||"Failed to count tokens");return r.tokenCount??0}function DPe({selectedServers:e,initialSystemPrompt:t=POt,initialTemperature:n=.7,onReset:r}){const{getAccessToken:i}=Aa(),a=b.useRef(r);b.useLayoutEffect(()=>{a.current=r},[r]);const{isAuthenticated:s,isLoading:o}=Ba(),{hasToken:u,getToken:c,getLiteLLMBaseUrl:d,getLiteLLMModelAlias:f,getOpenRouterSelectedModels:p,getOllamaBaseUrl:m,getAzureBaseUrl:y}=zx(),[v,x]=b.useState([]),[_,S]=b.useState(!1),[w,T]=b.useState(void 0),[N,E]=b.useState(t),[A,I]=b.useState(n),[M,$]=b.useState(Vd()),[O,R]=b.useState({}),[U,z]=b.useState({}),[F,D]=b.useState(null),[W,q]=b.useState(!1),[X,L]=b.useState(null),[Y,G]=b.useState(!1),[P,V]=b.useState(!1),K=b.useRef(P);K.current=P;const Q=b.useMemo(()=>TPt({hasToken:u,getLiteLLMBaseUrl:d,getLiteLLMModelAlias:f,getOpenRouterSelectedModels:p,isOllamaRunning:_,ollamaModels:v,getAzureBaseUrl:y}),[u,d,f,p,_,v,y]),{selectedModelId:oe,setSelectedModelId:re}=kPt(),ee=b.useMemo(()=>{const fe=NPt(Q);return oe?Q.find(Ce=>String(Ce.id)===oe)??fe:fe},[Q,oe]),le=b.useCallback(fe=>{re(String(fe.id))},[re]),te=b.useMemo(()=>ee?.id?_r(String(ee.id)):!1,[ee]),Z=b.useMemo(()=>{const fe=c(ee.provider),xe=RRe(ee.id),He={...F1e(),...w};return new aPe({api:"/api/mcp/chat-v2",body:()=>({model:ee,apiKey:fe,...xe?{}:{temperature:A},systemPrompt:N,selectedServers:e,requireToolApproval:K.current}),headers:Object.keys(He).length>0?He:void 0})},[ee,c,w,A,N,e]),{messages:ne,sendMessage:J,stop:se,status:ie,error:he,setMessages:ye,addToolApprovalResponse:Ne}=SPt({id:M,transport:Z,sendAutomaticallyWhen:P?OOt:void 0}),ce=b.useCallback(fe=>{const{text:xe,files:Ce}=fe;Ce&&Ce.length>0?J({text:xe,files:Ce}):J({text:xe})},[J]),Te=b.useCallback(()=>{$(Vd()),ye([]),a.current?.()},[ye]);b.useEffect(()=>{let fe=!0;return(async()=>{try{const xe=await i?.();if(!fe)return;T(xe?{Authorization:`Bearer ${xe}`}:void 0)}catch(xe){if(console.error("[useChatSession] Failed to get access token:",xe),!fe)return;T(void 0)}fe&&($(Vd()),ye([]),a.current?.())})(),()=>{fe=!1}},[i,ye]),b.useEffect(()=>{const fe=async()=>{const{isRunning:Ce,availableModels:He}=await $Pe(m());S(Ce);const Ze=Ce?await MPe(m()):[],st=new Set(Ze),ot=He.map(mt=>({id:mt,name:mt,provider:"ollama",disabled:!st.has(mt),disabledReason:st.has(mt)?void 0:"Model does not support tool calling"}));x(ot)};fe();const xe=setInterval(fe,3e4);return()=>clearInterval(xe)},[m]),b.useEffect(()=>{(async()=>{if(e.length===0){R({}),z({}),D(null),q(!1);return}const Ce=ee?.id&&ee?.provider?_r(String(ee.id))?String(ee.id):`${ee.provider}/${ee.id}`:void 0;q(!!Ce);try{const{metadata:He,toolServerMap:Ze,tokenCounts:st}=await Irt(e,Ce);R(He),z(Ze),D(st&&Object.keys(st).length>0?st:null)}catch(He){console.warn("[useChatSession] Failed to fetch tools metadata:",He),R({}),z({}),D(null)}finally{q(!1)}})()},[e,ee]),b.useEffect(()=>{(async()=>{if(!N||!ee?.id||!ee?.provider){L(null),G(!1);return}G(!0);try{const xe=_r(String(ee.id))?String(ee.id):`${ee.provider}/${ee.id}`,Ce=await CPt(N,xe);L(Ce>0?Ce:null)}catch(xe){console.warn("[useChatSession] Failed to count system prompt tokens:",xe),L(null)}finally{G(!1)}})()},[N,ee]);const we=b.useRef(e);b.useEffect(()=>{const fe=we.current,xe=e;(fe.length!==xe.length||fe.some((He,Ze)=>He!==xe[Ze]))&&Te(),we.current=xe},[e,Te]);const Oe=b.useMemo(()=>{let fe=0,xe=0;for(const Ce of ne)if(Ce.role==="assistant"&&Ce.metadata){const He=Ce.metadata;He&&(fe=He.inputTokens??0,xe+=He.outputTokens??0)}return{inputTokens:fe,outputTokens:xe,totalTokens:fe+xe}},[ne]),Ue=!te||s&&!!w,Me=!s&&te,be=te&&s&&!w,je=ie==="streaming"||ie==="submitted",Xe=Me||o||be;return{messages:ne,setMessages:ye,sendMessage:ce,stop:se,status:ie,error:he,chatSessionId:M,selectedModel:ee,setSelectedModel:le,availableModels:Q,isMcpJamModel:te,isAuthenticated:s,isAuthLoading:o,authHeaders:w,isAuthReady:Ue,systemPrompt:N,setSystemPrompt:E,temperature:A,setTemperature:I,toolsMetadata:O,toolServerMap:U,tokenUsage:Oe,mcpToolsTokenCount:F,mcpToolsTokenCountLoading:W,systemPromptTokenCount:X,systemPromptTokenCountLoading:Y,requireToolApproval:P,setRequireToolApproval:V,addToolApprovalResponse:Ne,resetChat:Te,isStreaming:je,disableForAuthentication:Me,submitBlocked:Xe,inputDisabled:ie!=="ready"||Xe}}async function APt(e){const t=await Yt("/api/mcp/xray-payload",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(e)});let n=null;try{n=await t.json()}catch{}if(!t.ok){const r=n?.error||`Failed to get X-Ray payload (${t.status})`;throw new Error(r)}if(n===null||typeof n!="object"||typeof n.system!="string"||typeof n.tools!="object"||!Array.isArray(n.messages))throw new Error("Failed to parse X-Ray payload");return n}function IPt(e,t){navigator.clipboard.writeText(typeof e=="string"?e:JSON.stringify(e,null,2)).then(()=>Pe.success(`${t} copied to clipboard`)).catch(()=>Pe.error(`Failed to copy ${t}`))}function LPe({systemPrompt:e,messages:t,selectedServers:n,onClose:r}){const i=ci(),[a,s]=b.useState(null),[o,u]=b.useState(!0),[c,d]=b.useState(null),f=async()=>{u(!0),d(null);try{const v=await APt({messages:t,systemPrompt:e,selectedServers:n});s(v),d(null)}catch(v){a||d(v instanceof Error?v.message:"Failed to fetch payload")}finally{u(!1)}},p=t.length>0,m=b.useRef(null);b.useEffect(()=>{if(!p){u(!1),s(null);return}return m.current&&clearTimeout(m.current),m.current=setTimeout(()=>{f()},1e3),()=>{m.current&&clearTimeout(m.current)}},[t,e,n,p]);const y=({showCopy:v=!1,showLoading:x=!1})=>l.jsxs("div",{className:"flex items-center justify-between px-4 py-3 border-b border-border flex-shrink-0 bg-muted/30",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(MM,{className:"h-4 w-4 text-primary"}),l.jsx("h2",{className:"text-sm font-medium text-foreground",children:"X-Ray View"}),x&&l.jsx(wn,{className:"h-3.5 w-3.5 animate-spin text-muted-foreground"})]}),l.jsxs("div",{className:"flex items-center gap-1",children:[v&&a&&l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:"ghost",size:"icon",onClick:()=>{i.capture("xray_payload_copied",{tool_count:Object.keys(a.tools).length,message_count:a.messages.length}),IPt(a,"Model payload")},className:"h-7 w-7",children:l.jsx(Ca,{className:"h-3.5 w-3.5"})})}),l.jsx(zt,{children:"Copy payload"})]}),r&&l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:"ghost",size:"icon",onClick:r,className:"h-7 w-7",children:l.jsx(Yn,{className:"h-3.5 w-3.5"})})}),l.jsx(zt,{children:"Close"})]})]})]});return p?o&&!a?l.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[l.jsx(y,{showLoading:!0}),l.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-muted/50 flex items-center justify-center mb-4",children:l.jsx(wn,{className:"h-6 w-6 animate-spin text-muted-foreground"})}),l.jsx("div",{className:"text-sm text-muted-foreground",children:"Loading payload..."})]})})]}):c?l.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[l.jsx(y,{}),l.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-destructive/10 flex items-center justify-center mb-4",children:l.jsx(Gs,{className:"h-6 w-6 text-destructive"})}),l.jsx("div",{className:"text-sm font-medium text-foreground mb-1",children:"Failed to load"}),l.jsx("div",{className:"text-xs text-muted-foreground mb-3",children:c}),l.jsx(Ee,{variant:"outline",size:"sm",onClick:f,children:"Try again"})]})})]}):a?l.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[l.jsx(y,{showCopy:!0,showLoading:o}),l.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:l.jsx("div",{className:"p-4",children:l.jsx("div",{className:"rounded-lg border border-border bg-muted/20",children:l.jsx(zn,{value:a,viewOnly:!0,collapsible:!0,collapseStringsAfterLength:100})})})})]}):l.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[l.jsx(y,{}),l.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:l.jsx(MM,{className:"h-7 w-7 text-primary/70"})}),l.jsx("div",{className:"text-sm font-medium text-foreground mb-1",children:"No payload data"}),l.jsx("div",{className:"text-xs text-muted-foreground",children:"Send a message to see the AI request payload"})]})})]}):l.jsxs("div",{className:"flex h-full min-h-0 flex-col overflow-hidden",children:[l.jsx(y,{}),l.jsx("div",{className:"flex-1 flex items-center justify-center p-6",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto w-14 h-14 rounded-full bg-primary/10 flex items-center justify-center mb-4",children:l.jsx(MM,{className:"h-7 w-7 text-primary/70"})}),l.jsx("div",{className:"text-sm font-medium text-foreground mb-1",children:"No messages yet"}),l.jsx("div",{className:"text-xs text-muted-foreground max-w-[220px]",children:"Send a message to inspect the raw payload sent to the model"})]})})]})}function ole(){const{isAtBottom:e,scrollToBottom:t}=_K();return e?null:l.jsx("div",{className:"pointer-events-none absolute inset-x-0 flex bottom-12 justify-center animate-in slide-in-from-bottom fade-in duration-200",children:l.jsx("button",{type:"button",className:"pointer-events-auto inline-flex items-center gap-2 rounded-full border border-border bg-background/90 px-2 py-2 text-xs font-medium shadow-sm transition hover:bg-accent",onClick:()=>t({animation:"smooth"}),children:l.jsx(S1e,{className:"h-4 w-4"})})})}function jPt({connectedOrConnectingServerConfigs:e,selectedServerNames:t,onHasMessagesChange:n}){const{signUp:r}=Aa(),{isVisible:i,toggle:a}=lW(),s=ci(),[o,u]=b.useState(""),[c,d]=b.useState([]),[f,p]=b.useState([]),[m,y]=b.useState([]),[v,x]=b.useState([]),[_,S]=b.useState([]),[w,T]=b.useState(null),[N,E]=b.useState(!1),[A,I]=b.useState(!1),[M,$]=b.useState(!1),O=b.useMemo(()=>t.filter(mt=>e[mt]?.connectionStatus==="connected"),[t,e]),{messages:R,setMessages:U,sendMessage:z,stop:F,status:D,error:W,selectedModel:q,setSelectedModel:X,availableModels:L,isAuthLoading:Y,systemPrompt:G,setSystemPrompt:P,temperature:V,setTemperature:K,toolsMetadata:Q,toolServerMap:oe,tokenUsage:re,mcpToolsTokenCount:ee,mcpToolsTokenCountLoading:le,systemPromptTokenCount:te,systemPromptTokenCountLoading:Z,resetChat:ne,isStreaming:J,disableForAuthentication:se,submitBlocked:ie,requireToolApproval:he,setRequireToolApproval:ye,addToolApprovalResponse:Ne}=DPe({selectedServers:O,onReset:()=>{u(""),x([])}}),ce=!R.some(mt=>mt.role==="user"||mt.role==="assistant"),Te=b.useMemo(()=>{const mt={};for(const Bt of t){const It=e[Bt]?.initializationInfo?.instructions;It&&(mt[Bt]=It)}return mt},[e,t]);b.useEffect(()=>{U(mt=>{const Bt=mt.filter(It=>!(It.role==="system"&&It?.metadata?.source==="server-instruction"));return[...Object.entries(Te).sort(([It],[gn])=>It.localeCompare(gn)).map(([It,gn])=>({id:`server-instruction-${It}`,role:"system",parts:[{type:"text",text:`Server ${It} instructions: ${gn}`}],metadata:{source:"server-instruction",serverName:It}})),...Bt]})},[Te,U]),b.useEffect(()=>{s.capture("chat_tab_viewed",{location:"chat_tab",platform:Et(),environment:void 0})},[s]),b.useEffect(()=>{n?.(!ce)},[ce,n]);const we=b.useCallback((mt,Bt)=>{let Mt=mt;for(const{toolCallId:It,state:gn}of Bt){const nt=`widget-state-${It}`;if(gn===null){Mt=Mt.filter(Wt=>Wt.id!==nt);continue}const yt=`The state of widget ${It} is: ${JSON.stringify(gn)}`,ut=Mt.findIndex(vt=>vt.id===nt);if(ut!==-1){const vt=Mt[ut];if((vt.parts?.[0]?.type==="text"?vt.parts[0].text:null)===yt)continue;const Qn=[...Mt];Qn[ut]={id:nt,role:"assistant",parts:[{type:"text",text:yt}]},Mt=Qn;continue}Mt=[...Mt,{id:nt,role:"assistant",parts:[{type:"text",text:yt}]}]}return Mt},[]),Oe=b.useCallback((mt,Bt)=>{D==="ready"?U(Mt=>we(Mt,[{toolCallId:mt,state:Bt}])):x(Mt=>[...Mt,{toolCallId:mt,state:Bt}])},[D,U,we]);b.useEffect(()=>{D!=="ready"||v.length===0||(U(mt=>we(mt,v)),x([]))},[D,v,U,we]);const Ue=b.useCallback((mt,Bt)=>{S(Mt=>[...Mt.filter(gn=>gn.toolCallId!==mt),{toolCallId:mt,context:Bt}])},[]);b.useEffect(()=>{const mt=new EventSource(qq("/api/mcp/elicitation/stream"));return mt.onmessage=Bt=>{try{const Mt=JSON.parse(Bt.data);Mt?.type==="elicitation_request"?T({requestId:Mt.requestId,message:Mt.message,schema:Mt.schema,timestamp:Mt.timestamp||new Date().toISOString()}):Mt?.type==="elicitation_complete"&&T(It=>It?.requestId===Mt.requestId?null:It)}catch(Mt){console.warn("[ChatTabV2] Failed to parse elicitation event:",Mt)}},mt.onerror=()=>{console.warn("[ChatTabV2] Elicitation SSE connection error, browser will retry")},()=>mt.close()},[]);const Me=async(mt,Bt)=>{if(w){E(!0);try{await Yt("/api/mcp/elicitation/respond",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({requestId:w.requestId,action:mt,content:Bt})}),T(null)}finally{E(!1)}}},be=ie,je=D!=="ready"||be;let Xe='Ask something… Use Slash "/" commands for Skills & MCP prompts';Y?Xe="Loading...":se&&(Xe="Sign in to use free chat");const fe=ce&&(se&&!Y),xe=vPe(W),Ce=()=>{s.capture("sign_up_button_clicked",{location:"chat_tab",platform:Et(),environment:void 0}),r()},He=async mt=>{if(mt.preventDefault(),(o.trim()||c.length>0||m.length>0||f.length>0)&&D==="ready"&&!be){s.capture("send_message",{location:"chat_tab",platform:Et(),environment:void 0,model_id:q?.id??null,model_name:q?.name??null,model_provider:q?.provider??null});const Mt=zOt(c);Mt.length>0&&U(yt=>[...yt,...Mt]);const It=UOt(m);It.length>0&&U(yt=>[...yt,...It]);const gn=_.map(({toolCallId:yt,context:ut})=>({id:`model-context-${yt}-${Date.now()}`,role:"user",parts:[{type:"text",text:`Widget ${yt} context: ${JSON.stringify(ut)}`}],metadata:{source:"widget-model-context",toolCallId:yt}}));gn.length>0&&U(yt=>[...yt,...gn]);const nt=f.length>0?await ORe(f):void 0;z({text:o,files:nt}),u(""),d([]),y([]),CI(f),p([]),S([])}},Ze=mt=>{if(be||je){u(mt);return}s.capture("send_message",{location:"chat_tab",platform:Et(),environment:void 0,model_id:q?.id??null,model_name:q?.name??null,model_provider:q?.provider??null}),z({text:mt}),u(""),CI(f),p([])},st={value:o,onChange:u,onSubmit:He,stop:F,disabled:je,isLoading:J,placeholder:Xe,currentModel:q,availableModels:L,onModelChange:mt=>{X(mt),ne()},systemPrompt:G,onSystemPromptChange:P,temperature:V,onTemperatureChange:K,onResetChat:ne,submitDisabled:be,tokenUsage:re,selectedServers:O,mcpToolsTokenCount:ee,mcpToolsTokenCountLoading:le,connectedOrConnectingServerConfigs:e,systemPromptTokenCount:te,systemPromptTokenCountLoading:Z,mcpPromptResults:c,onChangeMcpPromptResults:d,fileAttachments:f,onChangeFileAttachments:p,skillResults:m,onChangeSkillResults:y,xrayMode:M,onXrayModeChange:$,requireToolApproval:he,onRequireToolApprovalChange:ye},ot=!fe&&ce&&!Y;return l.jsx("div",{className:"flex flex-1 h-full min-h-0 flex-col overflow-hidden",children:l.jsxs(Bc,{direction:"horizontal",className:"flex-1 min-h-0 h-full",children:[l.jsx(ta,{defaultSize:i?70:100,minSize:40,className:"min-w-0",children:l.jsxs("div",{className:"flex flex-col bg-background h-full min-h-0 overflow-hidden",style:{transform:A?"none":"translateZ(0)"},children:[M&&l.jsxs(gc,{className:"relative flex flex-1 flex-col min-h-0",resize:"smooth",initial:"smooth",children:[l.jsxs("div",{className:"relative flex-1 min-h-0",children:[l.jsx(gc.Content,{className:"flex flex-col min-h-0",children:l.jsx(LPe,{systemPrompt:G,messages:R,selectedServers:O,onClose:()=>$(!1)})}),l.jsx(ole,{})]}),l.jsx("div",{className:"bg-background/80 backdrop-blur-sm border-t border-border flex-shrink-0",children:l.jsx("div",{className:"max-w-4xl mx-auto p-4",children:l.jsx(J1,{...st,hasMessages:!ce})})})]}),!ce&&l.jsxs(gc,{className:"relative flex flex-1 flex-col min-h-0 animate-in fade-in duration-300",style:M?{display:"none"}:void 0,resize:"smooth",initial:"smooth",children:[l.jsxs("div",{className:"relative flex-1 min-h-0",children:[l.jsx(gc.Content,{className:"flex flex-col min-h-0",children:l.jsx(IPe,{messages:R,sendFollowUpMessage:mt=>z({text:mt}),model:q,isLoading:D==="submitted",toolsMetadata:Q,toolServerMap:oe,onWidgetStateChange:Oe,onModelContextUpdate:Ue,onFullscreenChange:I,enableFullscreenChatOverlay:!0,fullscreenChatPlaceholder:Xe,fullscreenChatDisabled:je,onToolApprovalResponse:Ne})}),l.jsx(ole,{})]}),l.jsxs("div",{className:"bg-background/80 backdrop-blur-sm border-t border-border flex-shrink-0",children:[xe&&l.jsx("div",{className:"max-w-4xl mx-auto px-4 pt-4",children:l.jsx(OPe,{message:xe.message,errorDetails:xe.details,code:xe.code,statusCode:xe.statusCode,isRetryable:xe.isRetryable,isMCPJamPlatformError:xe.isMCPJamPlatformError,onResetChat:ne})}),l.jsx("div",{className:"max-w-4xl mx-auto p-4",children:l.jsx(J1,{...st,hasMessages:!0})})]})]}),!M&&ce&&l.jsx("div",{className:"flex-1 flex items-center justify-center overflow-y-auto px-4",children:l.jsxs("div",{className:"w-full max-w-3xl space-y-6 py-8",children:[Y?l.jsxs("div",{className:"text-center space-y-4",children:[l.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})]}):fe?l.jsx("div",{className:"space-y-4",children:l.jsx(jPe,{onSignUp:Ce})}):null,l.jsxs("div",{className:"space-y-4",children:[ot&&l.jsxs("div",{className:"text-center",children:[l.jsx("p",{className:"text-sm text-muted-foreground mb-3",children:"Try one of these to get started"}),l.jsx("div",{className:"flex flex-wrap justify-center gap-2",children:$Ot.map(mt=>l.jsx("button",{type:"button",onClick:()=>Ze(mt.text),className:"rounded-full border border-border bg-background px-4 py-2 text-sm text-foreground transition hover:border-foreground hover:bg-accent cursor-pointer font-light",children:mt.label},mt.text))})]}),!Y&&l.jsx(J1,{...st,hasMessages:!1})]})]})}),l.jsx(uW,{elicitationRequest:w,onResponse:Me,loading:N})]})}),i?l.jsxs(l.Fragment,{children:[l.jsx($u,{withHandle:!0}),l.jsx(ta,{defaultSize:30,minSize:20,maxSize:50,className:"min-w-[260px] min-h-0 overflow-hidden",children:l.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:l.jsx(QS,{onClose:a})})})]}):l.jsx(Zw,{onOpen:a})]})})}function lle(){const e=window.location.hash.replace("#","");if(!e.startsWith("/evals"))return null;const[t,n]=e.split("?");if(t==="/evals")return{type:"list"};if(t==="/evals/create")return{type:"create"};const r=t.match(/^\/evals\/suite\/([^/]+)(?:\/(.*))?$/);if(r){const[,i,a]=r;if(a==="edit")return{type:"suite-edit",suiteId:i};const s=a?.match(/^runs\/([^/?]+)$/);if(s){const[,c]=s,d=new URLSearchParams(n||"");return{type:"run-detail",suiteId:i,runId:c,iteration:d.get("iteration")||void 0}}const o=a?.match(/^test\/([^/?]+)\/edit$/);if(o){const[,c]=o;return{type:"test-edit",suiteId:i,testId:c}}const u=a?.match(/^test\/([^/?]+)$/);if(u){const[,c]=u,d=new URLSearchParams(n||"");return{type:"test-detail",suiteId:i,testId:c,iteration:d.get("iteration")||void 0}}if(!a){const d=new URLSearchParams(n||"").get("view");return{type:"suite-overview",suiteId:i,view:d==="test-cases"?"test-cases":"runs"}}}return{type:"list"}}function _s(e){let t="";switch(e.type){case"list":t="#/evals";break;case"create":t="#/evals/create";break;case"suite-overview":{const n=new URLSearchParams;e.view&&e.view!=="runs"&&n.set("view",e.view);const r=n.toString();t=`#/evals/suite/${e.suiteId}${r?`?${r}`:""}`;break}case"run-detail":{const n=new URLSearchParams;e.iteration&&n.set("iteration",e.iteration);const r=n.toString();t=`#/evals/suite/${e.suiteId}/runs/${e.runId}${r?`?${r}`:""}`;break}case"test-detail":{const n=new URLSearchParams;e.iteration&&n.set("iteration",e.iteration);const r=n.toString();t=`#/evals/suite/${e.suiteId}/test/${e.testId}${r?`?${r}`:""}`;break}case"test-edit":t=`#/evals/suite/${e.suiteId}/test/${e.testId}/edit`;break;case"suite-edit":t=`#/evals/suite/${e.suiteId}/edit`;break}window.location.hash=t}function OPt(){const[e,t]=de.useState(()=>lle()||{type:"list"});return de.useEffect(()=>{const n=()=>{const r=lle()||{type:"list"};t(r)};return window.addEventListener("hashchange",n),()=>window.removeEventListener("hashchange",n)},[]),e}async function*RPt(e){const t=new TextDecoder;let n="";try{for(;;){const{done:r,value:i}=await e.read();if(r)break;n+=t.decode(i,{stream:!0});const a=n.split(`
|
|
1771
1771
|
`);n=a.pop()||"";for(const s of a){if(!s.startsWith("data: "))continue;const o=s.slice(6).trim();if(o){if(o==="[DONE]"){yield"[DONE]";return}try{yield JSON.parse(o)}catch{continue}}}}}finally{try{e.releaseLock?.()}catch{}}}function PPt(e={}){const{getToken:t,hasToken:n,tokens:r,getOllamaBaseUrl:i,getLiteLLMBaseUrl:a,getLiteLLMModelAlias:s,getOpenRouterSelectedModels:o,getAzureBaseUrl:u,getAnthropicBaseUrl:c,getOpenAIBaseUrl:d}=zx(),f=ci(),{initialMessages:p=[],systemPrompt:m,temperature:y,onMessageSent:v,onMessageReceived:x,onError:_,onModelChange:S,sendMessagesToBackend:w=!1,selectedServers:T=[]}=e,[N,E]=b.useState({messages:p,isLoading:!1,connectionStatus:"disconnected"}),[A,I]=b.useState(""),[M,$]=b.useState("idle"),[O,R]=b.useState(null),[U,z]=b.useState([]),[F,D]=b.useState(!1),[W,q]=b.useState(null),[X,L]=b.useState(!1),Y=b.useRef(null),G=b.useRef(N.messages),{getAccessToken:P}=Aa();b.useEffect(()=>{G.current=N.messages},[N.messages]),b.useEffect(()=>{const ie=async()=>{const{isRunning:ye,availableModels:Ne}=await $Pe(i());D(ye),ye&&f.capture("ollama_running");const ce=ye?await MPe(i()):[],Te=new Set(ce),we=Ne.map(Oe=>{const Ue=Te.has(Oe);return{id:Oe,name:Oe,provider:"ollama",disabled:!Ue,disabledReason:Ue?void 0:"Model does not support tool calling"}});z(we)};ie();const he=setInterval(ie,3e4);return()=>clearInterval(he)},[i]),b.useEffect(()=>{if(!O||!oe.some(ie=>ie.id===O.id)){const ie=$Pt(oe,F);R(ie??null)}},[r,U,F,n,O]);const V=b.useCallback(ie=>ie?_r(ie.id)?"router":ie.provider==="ollama"?F&&U.some(ye=>ye.id===ie.id||ye.id.startsWith(`${ie.id}:`))?"local":"":t(ie.provider):"",[t,F,U]),K=b.useMemo(()=>V(O),[O,V]),Q=b.useCallback(ie=>{R(ie),S&&S(ie)},[S]),oe=b.useMemo(()=>{const ie={anthropic:n("anthropic"),openai:n("openai"),deepseek:n("deepseek"),google:n("google"),mistral:n("mistral"),xai:n("xai"),ollama:F,litellm:!!(a()&&s()),openrouter:!!(n("openrouter")&&o().length>0),azure:!!u(),meta:!1},he=dK.filter(we=>_r(we.id)?!0:ie[we.provider]),ye=(we,Oe)=>we.split(",").map(Ue=>Ue.trim()).filter(Ue=>Ue.length>0).map(Ue=>({id:Ue,name:Ue,provider:Oe})),Ne=[];if(ie.litellm){const we=s();Ne.push(...ye(we,"litellm"))}const ce=[];ie.openrouter&&o().forEach(Oe=>{ce.push({id:Oe,name:Oe,provider:"openrouter"})});let Te=he;return F&&U.length>0&&(Te=Te.concat(U)),Ne.length>0&&(Te=Te.concat(Ne)),ce.length>0&&(Te=Te.concat(ce)),Te},[F,U,n,a,s,o,u]),re=b.useCallback((ie,he,ye,Ne,ce,Te)=>{switch(ie.type){case"text":{ye.current+=ie.content;const we=Te.current[Te.current.length-1];we&&we.type==="text"?we.content=(we.content||"")+ie.content:Te.current=[...Te.current,{id:`text-${Date.now()}`,type:"text",content:ie.content,timestamp:new Date}],E(Oe=>({...Oe,messages:Oe.messages.map(Ue=>Ue.id===he.id?{...Ue,content:ye.current,contentBlocks:[...Te.current]}:Ue)}));break}case"tool_call":{const we={...ie.toolCall,timestamp:new Date(ie.toolCall.timestamp)};Ne.current=[...Ne.current,we],Te.current=[...Te.current,{id:`tool-call-${we.id}`,type:"tool_call",toolCall:we,timestamp:new Date}],E(Oe=>({...Oe,messages:Oe.messages.map(Ue=>Ue.id===he.id?{...Ue,toolCalls:[...Ne.current],contentBlocks:[...Te.current]}:Ue)}));break}case"tool_result":{const we={...ie.toolResult,timestamp:new Date(ie.toolResult.timestamp)};ce.current=[...ce.current,we],Ne.current=Ne.current.map(Oe=>Oe.id===we.toolCallId?{...Oe,status:we.error?"error":"completed"}:Oe),Te.current=Te.current.map(Oe=>Oe.type==="tool_call"&&Oe.toolCall?.id===we.toolCallId?{...Oe,toolCall:{...Oe.toolCall,status:we.error?"error":"completed"},toolResult:we}:Oe),E(Oe=>({...Oe,messages:Oe.messages.map(Ue=>Ue.id===he.id?{...Ue,toolCalls:[...Ne.current],toolResults:[...ce.current],contentBlocks:[...Te.current]}:Ue)}));break}case"elicitation_request":{q({requestId:ie.requestId,message:ie.message,schema:ie.schema,timestamp:ie.timestamp});break}case"elicitation_complete":{q(null);break}case"trace_step":break;case"error":{Te.current=[...Te.current,{id:`error-${Date.now()}`,type:"error",content:ie.error,timestamp:new Date}],E(we=>({...we,messages:we.messages.map(Oe=>Oe.id===he.id?{...Oe,contentBlocks:[...Te.current]}:Oe)}));break}}},[]),ee=b.useCallback(async ie=>{const he=w||O&&_r(O.id);if(!he&&(!O||!K))throw new Error("Missing required configuration: model and apiKey are required");const ye=voe("assistant","");E(Ne=>({...Ne,messages:[...Ne.messages,ye]}));try{let Ne=null;if(he&&P)try{const be=await P();be&&(Ne=`Bearer ${be}`)}catch(be){console.warn("[useChat] failed to retrieve access token",be)}const ce=await Yt("/api/mcp/chat",{method:"POST",headers:{"Content-Type":"application/json",Accept:"text/event-stream",...Ne?{Authorization:Ne}:{}},body:JSON.stringify({model:O,provider:O.provider,apiKey:K,systemPrompt:m,temperature:y,messages:G.current.concat(ie),ollamaBaseUrl:i(),litellmBaseUrl:a(),azureBaseUrl:u(),anthropicBaseUrl:c(),openaiBaseUrl:d(),sendMessagesToBackend:he,selectedServers:T}),signal:Y.current?.signal});if(!ce.ok){const be=await ce.text();let je;try{je=JSON.parse(be)}catch{throw new Error(`Chat request failed: ${ce.status}`)}throw new Error(je.error||"Chat request failed")}const Te=ce.body?.getReader(),we={current:""},Oe={current:[]},Ue={current:[]},Me={current:[]};if(Te){for await(const be of RPt(Te)){if(be==="[DONE]")break;try{re(be,ye,we,Oe,Ue,Me)}catch(je){console.warn("Failed applying SSE event",je)}}E(be=>({...be,isLoading:!1}))}else E(be=>({...be,isLoading:!1}));if(!we.current&&!Oe.current.length&&console.warn("No content received from stream"),x){const be={...ye,content:we.current};x(be)}}catch(Ne){throw E(ce=>({...ce,isLoading:!1})),Ne}finally{Y.current=null}},[O,K,m,x,re,i,a,u,c,d,w,P,T]),le=b.useCallback(async(ie,he)=>{if(!ie.trim()||N.isLoading)return;const ye=voe("user",ie,he);E(Ne=>({...Ne,messages:[...Ne.messages,ye],isLoading:!0,error:void 0})),v&&v(ye),Y.current=new AbortController;try{await ee(ye),$("idle")}catch(Ne){const ce=Ne instanceof Error?Ne.message:"An error occurred";E(Te=>({...Te,isLoading:!1,error:ce})),$("error"),_?.(ce)}},[N.isLoading,v,ee,_]),te=b.useCallback(()=>{Y.current&&Y.current.abort(),E(ie=>({...ie,isLoading:!1})),$("idle"),Y.current=null},[]),Z=b.useCallback(async ie=>{const he=G.current,ye=he.findIndex(ce=>ce.id===ie);if(ye===-1||ye===0)return;const Ne=he[ye-1];if(Ne.role==="user"){E(ce=>({...ce,messages:ce.messages.slice(0,ye),isLoading:!0})),Y.current=new AbortController;try{await ee(Ne),$("idle")}catch(ce){const Te=ce instanceof Error?ce.message:"An error occurred";E(we=>({...we,isLoading:!1,error:Te})),$("error"),_?.(Te)}}},[N.isLoading,v,ee,_]),ne=b.useCallback(ie=>{E(he=>({...he,messages:he.messages.filter(ye=>ye.id!==ie)}))},[]),J=b.useCallback(()=>{E(ie=>({...ie,messages:[],error:void 0})),I("")},[]),se=b.useCallback(async(ie,he)=>{if(!W){console.warn("Cannot handle elicitation response: no active request");return}L(!0);try{let ye=null;ie==="accept"?ye={action:"accept",content:he||{}}:ye={action:ie};const Ne=await Yt("/api/mcp/chat",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({action:"elicitation_response",requestId:W.requestId,response:ye})});if(!Ne.ok){const ce=`HTTP error! status: ${Ne.status}`;throw new Error(ce)}q(null)}catch(ye){const Ne=ye instanceof Error?ye.message:"Unknown error";console.error("Error responding to elicitation request:",Ne),_&&_("Error responding to elicitation request")}finally{L(!1)}},[W,_]);return b.useEffect(()=>()=>{Y.current&&Y.current.abort()},[]),{messages:N.messages,isLoading:N.isLoading,error:N.error,connectionStatus:N.connectionStatus,status:M,input:A,setInput:I,model:O,availableModels:oe,hasValidApiKey:!!K,elicitationRequest:W,elicitationLoading:X,sendMessage:le,stopGeneration:te,regenerateMessage:Z,deleteMessage:ne,clearChat:J,setModel:Q,handleElicitationResponse:se}}function $Pt(e,t){if(t){const r=e.find(i=>i.provider==="ollama");if(r)return r}const n=["google/gemini-3-flash-preview",cc.CLAUDE_3_5_SONNET_LATEST,cc.GPT_4O,cc.DEEPSEEK_CHAT,cc.GEMINI_2_5_FLASH];for(const r of n){const i=e.find(a=>a.id===r);if(i)return i}return e[0]}function MPt(e,t){for(const[n,r]of Object.entries(e))if(JSON.stringify(t[n])!==JSON.stringify(r))return!1;return!0}function DPt(e,t,n){const r=Array.isArray(e)?e:[],i=Array.isArray(t)?t:[];if(n){const f=i.length===0;return{missing:[],unexpected:i,argumentMismatches:[],passed:f}}if(i.length===0)return{missing:r,unexpected:[],argumentMismatches:[],passed:!1};const a=new Set,s=new Set,o=[];for(let f=0;f<r.length;f++){const p=r[f],m=p.arguments||{};for(let y=0;y<i.length;y++){if(a.has(y))continue;const v=i[y];if(v.toolName!==p.toolName)continue;const x=v.arguments||{};if(Object.keys(m).length===0||MPt(m,x)){a.add(y),s.add(f);break}}}for(let f=0;f<r.length;f++){if(s.has(f))continue;const p=r[f],m=p.arguments||{};for(let y=0;y<i.length;y++){if(a.has(y))continue;const v=i[y];if(v.toolName!==p.toolName)continue;const x=v.arguments||{};a.add(y),s.add(f),Object.keys(m).length>0&&o.push({toolName:p.toolName,expectedArgs:m,actualArgs:x});break}}const u=r.filter((f,p)=>!s.has(p)),c=i.filter((f,p)=>!a.has(p)),d=u.length===0&&o.length===0;return{missing:u,unexpected:c,argumentMismatches:o,passed:d}}function Fl(e,t){return e.status==="pending"||e.status==="running"?"pending":e.status==="cancelled"?"cancelled":MI(e)?"passed":"failed"}function MI(e,t){const n=e.actualToolCalls||[],r=e.testCaseSnapshot?.expectedToolCalls||[],i=e.testCaseSnapshot?.isNegativeTest,a=DPt(r,n,i);if(i)return a.passed;if(r.length===0&&n.length>0)return!0;const s=a.missing,o=a.argumentMismatches;return s.length===0&&o.length===0}const wK={MIN_PASS_RATE:100,RUNS_PER_TEST:1},ule={EVAL_RUNNER_PREFERENCES:"mcp-inspector-eval-runner-preferences",SUITE_PASS_CRITERIA:e=>`suite-${e}-criteria-rate`},vN={PASSED:"passed",FAILED:"failed",CANCELLED:"cancelled",PENDING:"pending"},cle={CHART_COLORS:{PASSED:"hsl(142.1 76.2% 36.3%)",FAILED:"hsl(0 84.2% 60.2%)"}},gl=[{key:"servers",title:"Select Servers",description:"Choose the MCP servers to evaluate."},{key:"model",title:"Choose Model",description:"Pick the model and ensure credentials are ready."},{key:"tests",title:"Define Tests",description:"Author the scenarios you want to run or generate them with AI."},{key:"review",title:"Review & Run",description:"Confirm the configuration before launching the run."}],y1={EVALS_RUN:"/api/mcp/evals/run",EVALS_GENERATE_TESTS:"/api/mcp/evals/generate-tests",EVALS_GENERATE_NEGATIVE_TESTS:"/api/mcp/evals/generate-negative-tests",EVALS_RUN_TEST_CASE:"/api/mcp/evals/run-test-case",LIST_TOOLS:"/api/mcp/list-tools"};function LPt(e){return e?new Date(e).toLocaleString():"—"}function zPt(e){if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;if(n<60)return r?`${n}m ${r}s`:`${n}m`;const i=Math.floor(n/60),a=n%60;return a?`${i}h ${a}m`:`${i}h`}function r2(e){return e.substring(0,8)}function mD(e){const t={runs:e.length,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null};let n=0,r=0;return e.forEach(i=>{i.result==="passed"?t.passed+=1:i.result==="failed"?t.failed+=1:i.result==="cancelled"?t.cancelled+=1:t.pending+=1,t.tokens+=i.tokensUsed||0;const a=i.startedAt??i.createdAt,s=i.updatedAt??i.createdAt;if(a&&s){const o=Math.max(s-a,0);n+=o,r+=1}}),r>0&&(t.avgDuration=n/r),t}function UPt(e){return e.testTemplateKey?e.testTemplateKey:e._id?`fallback:${e._id}`:`fallback:${e.title}-${e.query}`}function FPt(e,t,n){const r=n.reduce((a,s)=>{const o=Fl(s);return o==="pending"?a.pending+=1:o==="passed"?a.passed+=1:o==="failed"?a.failed+=1:o==="cancelled"&&(a.cancelled+=1),a.tokens+=s.tokensUsed||0,a},{passed:0,failed:0,cancelled:0,pending:0,tokens:0}),i=new Map;for(const a of n){const s=a.testCaseId;if(!s)continue;if(!i.has(s)){const c=t.find(f=>f._id===s),d=n.filter(f=>f.testCaseId===s).length;i.set(s,{testCaseId:s,title:c?.title||"Untitled",provider:c?.provider||"",model:c?.model||"",runs:d,passed:0,failed:0,cancelled:0,tokens:0})}const o=i.get(s),u=Fl(a);u==="pending"||(u==="passed"?o.passed+=1:u==="failed"?o.failed+=1:u==="cancelled"&&(o.cancelled+=1)),o.tokens+=a.tokensUsed||0}return{filteredIterations:n,totals:r,byCase:Array.from(i.values())}}function SK(e){switch(e){case vN.PASSED:return"bg-success/50";case vN.FAILED:return"bg-red-500/50";case vN.CANCELLED:return"bg-muted";case vN.PENDING:return"bg-warning/50";default:return"bg-muted-foreground/50"}}var gD,dle;function Co(){if(dle)return gD;dle=1;var e=Array.isArray;return gD=e,gD}var vD,fle;function zPe(){if(fle)return vD;fle=1;var e=typeof FE=="object"&&FE&&FE.Object===Object&&FE;return vD=e,vD}var yD,ple;function Vc(){if(ple)return yD;ple=1;var e=zPe(),t=typeof self=="object"&&self&&self.Object===Object&&self,n=e||t||Function("return this")();return yD=n,yD}var xD,hle;function dk(){if(hle)return xD;hle=1;var e=Vc(),t=e.Symbol;return xD=t,xD}var bD,mle;function BPt(){if(mle)return bD;mle=1;var e=dk(),t=Object.prototype,n=t.hasOwnProperty,r=t.toString,i=e?e.toStringTag:void 0;function a(s){var o=n.call(s,i),u=s[i];try{s[i]=void 0;var c=!0}catch{}var d=r.call(s);return c&&(o?s[i]=u:delete s[i]),d}return bD=a,bD}var _D,gle;function qPt(){if(gle)return _D;gle=1;var e=Object.prototype,t=e.toString;function n(r){return t.call(r)}return _D=n,_D}var wD,vle;function xf(){if(vle)return wD;vle=1;var e=dk(),t=BPt(),n=qPt(),r="[object Null]",i="[object Undefined]",a=e?e.toStringTag:void 0;function s(o){return o==null?o===void 0?i:r:a&&a in Object(o)?t(o):n(o)}return wD=s,wD}var SD,yle;function bf(){if(yle)return SD;yle=1;function e(t){return t!=null&&typeof t=="object"}return SD=e,SD}var kD,xle;function Ux(){if(xle)return kD;xle=1;var e=xf(),t=bf(),n="[object Symbol]";function r(i){return typeof i=="symbol"||t(i)&&e(i)==n}return kD=r,kD}var ED,ble;function kK(){if(ble)return ED;ble=1;var e=Co(),t=Ux(),n=/\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,r=/^\w*$/;function i(a,s){if(e(a))return!1;var o=typeof a;return o=="number"||o=="symbol"||o=="boolean"||a==null||t(a)?!0:r.test(a)||!n.test(a)||s!=null&&a in Object(s)}return ED=i,ED}var TD,_le;function dh(){if(_le)return TD;_le=1;function e(t){var n=typeof t;return t!=null&&(n=="object"||n=="function")}return TD=e,TD}var ND,wle;function EK(){if(wle)return ND;wle=1;var e=xf(),t=dh(),n="[object AsyncFunction]",r="[object Function]",i="[object GeneratorFunction]",a="[object Proxy]";function s(o){if(!t(o))return!1;var u=e(o);return u==r||u==i||u==n||u==a}return ND=s,ND}var CD,Sle;function HPt(){if(Sle)return CD;Sle=1;var e=Vc(),t=e["__core-js_shared__"];return CD=t,CD}var AD,kle;function VPt(){if(kle)return AD;kle=1;var e=HPt(),t=(function(){var r=/[^.]+$/.exec(e&&e.keys&&e.keys.IE_PROTO||"");return r?"Symbol(src)_1."+r:""})();function n(r){return!!t&&t in r}return AD=n,AD}var ID,Ele;function UPe(){if(Ele)return ID;Ele=1;var e=Function.prototype,t=e.toString;function n(r){if(r!=null){try{return t.call(r)}catch{}try{return r+""}catch{}}return""}return ID=n,ID}var jD,Tle;function GPt(){if(Tle)return jD;Tle=1;var e=EK(),t=VPt(),n=dh(),r=UPe(),i=/[\\^$.*+?()[\]{}|]/g,a=/^\[object .+?Constructor\]$/,s=Function.prototype,o=Object.prototype,u=s.toString,c=o.hasOwnProperty,d=RegExp("^"+u.call(c).replace(i,"\\$&").replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g,"$1.*?")+"$");function f(p){if(!n(p)||t(p))return!1;var m=e(p)?d:a;return m.test(r(p))}return jD=f,jD}var OD,Nle;function WPt(){if(Nle)return OD;Nle=1;function e(t,n){return t?.[n]}return OD=e,OD}var RD,Cle;function Og(){if(Cle)return RD;Cle=1;var e=GPt(),t=WPt();function n(r,i){var a=t(r,i);return e(a)?a:void 0}return RD=n,RD}var PD,Ale;function WR(){if(Ale)return PD;Ale=1;var e=Og(),t=e(Object,"create");return PD=t,PD}var $D,Ile;function KPt(){if(Ile)return $D;Ile=1;var e=WR();function t(){this.__data__=e?e(null):{},this.size=0}return $D=t,$D}var MD,jle;function ZPt(){if(jle)return MD;jle=1;function e(t){var n=this.has(t)&&delete this.__data__[t];return this.size-=n?1:0,n}return MD=e,MD}var DD,Ole;function YPt(){if(Ole)return DD;Ole=1;var e=WR(),t="__lodash_hash_undefined__",n=Object.prototype,r=n.hasOwnProperty;function i(a){var s=this.__data__;if(e){var o=s[a];return o===t?void 0:o}return r.call(s,a)?s[a]:void 0}return DD=i,DD}var LD,Rle;function XPt(){if(Rle)return LD;Rle=1;var e=WR(),t=Object.prototype,n=t.hasOwnProperty;function r(i){var a=this.__data__;return e?a[i]!==void 0:n.call(a,i)}return LD=r,LD}var zD,Ple;function JPt(){if(Ple)return zD;Ple=1;var e=WR(),t="__lodash_hash_undefined__";function n(r,i){var a=this.__data__;return this.size+=this.has(r)?0:1,a[r]=e&&i===void 0?t:i,this}return zD=n,zD}var UD,$le;function QPt(){if($le)return UD;$le=1;var e=KPt(),t=ZPt(),n=YPt(),r=XPt(),i=JPt();function a(s){var o=-1,u=s==null?0:s.length;for(this.clear();++o<u;){var c=s[o];this.set(c[0],c[1])}}return a.prototype.clear=e,a.prototype.delete=t,a.prototype.get=n,a.prototype.has=r,a.prototype.set=i,UD=a,UD}var FD,Mle;function e4t(){if(Mle)return FD;Mle=1;function e(){this.__data__=[],this.size=0}return FD=e,FD}var BD,Dle;function TK(){if(Dle)return BD;Dle=1;function e(t,n){return t===n||t!==t&&n!==n}return BD=e,BD}var qD,Lle;function KR(){if(Lle)return qD;Lle=1;var e=TK();function t(n,r){for(var i=n.length;i--;)if(e(n[i][0],r))return i;return-1}return qD=t,qD}var HD,zle;function t4t(){if(zle)return HD;zle=1;var e=KR(),t=Array.prototype,n=t.splice;function r(i){var a=this.__data__,s=e(a,i);if(s<0)return!1;var o=a.length-1;return s==o?a.pop():n.call(a,s,1),--this.size,!0}return HD=r,HD}var VD,Ule;function n4t(){if(Ule)return VD;Ule=1;var e=KR();function t(n){var r=this.__data__,i=e(r,n);return i<0?void 0:r[i][1]}return VD=t,VD}var GD,Fle;function r4t(){if(Fle)return GD;Fle=1;var e=KR();function t(n){return e(this.__data__,n)>-1}return GD=t,GD}var WD,Ble;function i4t(){if(Ble)return WD;Ble=1;var e=KR();function t(n,r){var i=this.__data__,a=e(i,n);return a<0?(++this.size,i.push([n,r])):i[a][1]=r,this}return WD=t,WD}var KD,qle;function ZR(){if(qle)return KD;qle=1;var e=e4t(),t=t4t(),n=n4t(),r=r4t(),i=i4t();function a(s){var o=-1,u=s==null?0:s.length;for(this.clear();++o<u;){var c=s[o];this.set(c[0],c[1])}}return a.prototype.clear=e,a.prototype.delete=t,a.prototype.get=n,a.prototype.has=r,a.prototype.set=i,KD=a,KD}var ZD,Hle;function NK(){if(Hle)return ZD;Hle=1;var e=Og(),t=Vc(),n=e(t,"Map");return ZD=n,ZD}var YD,Vle;function a4t(){if(Vle)return YD;Vle=1;var e=QPt(),t=ZR(),n=NK();function r(){this.size=0,this.__data__={hash:new e,map:new(n||t),string:new e}}return YD=r,YD}var XD,Gle;function s4t(){if(Gle)return XD;Gle=1;function e(t){var n=typeof t;return n=="string"||n=="number"||n=="symbol"||n=="boolean"?t!=="__proto__":t===null}return XD=e,XD}var JD,Wle;function YR(){if(Wle)return JD;Wle=1;var e=s4t();function t(n,r){var i=n.__data__;return e(r)?i[typeof r=="string"?"string":"hash"]:i.map}return JD=t,JD}var QD,Kle;function o4t(){if(Kle)return QD;Kle=1;var e=YR();function t(n){var r=e(this,n).delete(n);return this.size-=r?1:0,r}return QD=t,QD}var e6,Zle;function l4t(){if(Zle)return e6;Zle=1;var e=YR();function t(n){return e(this,n).get(n)}return e6=t,e6}var t6,Yle;function u4t(){if(Yle)return t6;Yle=1;var e=YR();function t(n){return e(this,n).has(n)}return t6=t,t6}var n6,Xle;function c4t(){if(Xle)return n6;Xle=1;var e=YR();function t(n,r){var i=e(this,n),a=i.size;return i.set(n,r),this.size+=i.size==a?0:1,this}return n6=t,n6}var r6,Jle;function CK(){if(Jle)return r6;Jle=1;var e=a4t(),t=o4t(),n=l4t(),r=u4t(),i=c4t();function a(s){var o=-1,u=s==null?0:s.length;for(this.clear();++o<u;){var c=s[o];this.set(c[0],c[1])}}return a.prototype.clear=e,a.prototype.delete=t,a.prototype.get=n,a.prototype.has=r,a.prototype.set=i,r6=a,r6}var i6,Qle;function FPe(){if(Qle)return i6;Qle=1;var e=CK(),t="Expected a function";function n(r,i){if(typeof r!="function"||i!=null&&typeof i!="function")throw new TypeError(t);var a=function(){var s=arguments,o=i?i.apply(this,s):s[0],u=a.cache;if(u.has(o))return u.get(o);var c=r.apply(this,s);return a.cache=u.set(o,c)||u,c};return a.cache=new(n.Cache||e),a}return n.Cache=e,i6=n,i6}var a6,eue;function d4t(){if(eue)return a6;eue=1;var e=FPe(),t=500;function n(r){var i=e(r,function(s){return a.size===t&&a.clear(),s}),a=i.cache;return i}return a6=n,a6}var s6,tue;function f4t(){if(tue)return s6;tue=1;var e=d4t(),t=/[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g,n=/\\(\\)?/g,r=e(function(i){var a=[];return i.charCodeAt(0)===46&&a.push(""),i.replace(t,function(s,o,u,c){a.push(u?c.replace(n,"$1"):o||s)}),a});return s6=r,s6}var o6,nue;function AK(){if(nue)return o6;nue=1;function e(t,n){for(var r=-1,i=t==null?0:t.length,a=Array(i);++r<i;)a[r]=n(t[r],r,t);return a}return o6=e,o6}var l6,rue;function p4t(){if(rue)return l6;rue=1;var e=dk(),t=AK(),n=Co(),r=Ux(),i=e?e.prototype:void 0,a=i?i.toString:void 0;function s(o){if(typeof o=="string")return o;if(n(o))return t(o,s)+"";if(r(o))return a?a.call(o):"";var u=o+"";return u=="0"&&1/o==-1/0?"-0":u}return l6=s,l6}var u6,iue;function BPe(){if(iue)return u6;iue=1;var e=p4t();function t(n){return n==null?"":e(n)}return u6=t,u6}var c6,aue;function qPe(){if(aue)return c6;aue=1;var e=Co(),t=kK(),n=f4t(),r=BPe();function i(a,s){return e(a)?a:t(a,s)?[a]:n(r(a))}return c6=i,c6}var d6,sue;function XR(){if(sue)return d6;sue=1;var e=Ux();function t(n){if(typeof n=="string"||e(n))return n;var r=n+"";return r=="0"&&1/n==-1/0?"-0":r}return d6=t,d6}var f6,oue;function IK(){if(oue)return f6;oue=1;var e=qPe(),t=XR();function n(r,i){i=e(i,r);for(var a=0,s=i.length;r!=null&&a<s;)r=r[t(i[a++])];return a&&a==s?r:void 0}return f6=n,f6}var p6,lue;function HPe(){if(lue)return p6;lue=1;var e=IK();function t(n,r,i){var a=n==null?void 0:e(n,r);return a===void 0?i:a}return p6=t,p6}var h4t=HPe();const Qo=Jn(h4t);var h6,uue;function m4t(){if(uue)return h6;uue=1;function e(t){return t==null}return h6=e,h6}var g4t=m4t();const mn=Jn(g4t);var m6,cue;function v4t(){if(cue)return m6;cue=1;var e=xf(),t=Co(),n=bf(),r="[object String]";function i(a){return typeof a=="string"||!t(a)&&n(a)&&e(a)==r}return m6=i,m6}var y4t=v4t();const ig=Jn(y4t);var x4t=EK();const nn=Jn(x4t);var b4t=dh();const Fx=Jn(b4t);var g6={exports:{}},kr={};var due;function _4t(){if(due)return kr;due=1;var e=Symbol.for("react.element"),t=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),a=Symbol.for("react.provider"),s=Symbol.for("react.context"),o=Symbol.for("react.server_context"),u=Symbol.for("react.forward_ref"),c=Symbol.for("react.suspense"),d=Symbol.for("react.suspense_list"),f=Symbol.for("react.memo"),p=Symbol.for("react.lazy"),m=Symbol.for("react.offscreen"),y;y=Symbol.for("react.module.reference");function v(x){if(typeof x=="object"&&x!==null){var _=x.$$typeof;switch(_){case e:switch(x=x.type,x){case n:case i:case r:case c:case d:return x;default:switch(x=x&&x.$$typeof,x){case o:case s:case u:case p:case f:case a:return x;default:return _}}case t:return _}}}return kr.ContextConsumer=s,kr.ContextProvider=a,kr.Element=e,kr.ForwardRef=u,kr.Fragment=n,kr.Lazy=p,kr.Memo=f,kr.Portal=t,kr.Profiler=i,kr.StrictMode=r,kr.Suspense=c,kr.SuspenseList=d,kr.isAsyncMode=function(){return!1},kr.isConcurrentMode=function(){return!1},kr.isContextConsumer=function(x){return v(x)===s},kr.isContextProvider=function(x){return v(x)===a},kr.isElement=function(x){return typeof x=="object"&&x!==null&&x.$$typeof===e},kr.isForwardRef=function(x){return v(x)===u},kr.isFragment=function(x){return v(x)===n},kr.isLazy=function(x){return v(x)===p},kr.isMemo=function(x){return v(x)===f},kr.isPortal=function(x){return v(x)===t},kr.isProfiler=function(x){return v(x)===i},kr.isStrictMode=function(x){return v(x)===r},kr.isSuspense=function(x){return v(x)===c},kr.isSuspenseList=function(x){return v(x)===d},kr.isValidElementType=function(x){return typeof x=="string"||typeof x=="function"||x===n||x===i||x===r||x===c||x===d||x===m||typeof x=="object"&&x!==null&&(x.$$typeof===p||x.$$typeof===f||x.$$typeof===a||x.$$typeof===s||x.$$typeof===u||x.$$typeof===y||x.getModuleId!==void 0)},kr.typeOf=v,kr}var fue;function w4t(){return fue||(fue=1,g6.exports=_4t()),g6.exports}var S4t=w4t(),v6,pue;function VPe(){if(pue)return v6;pue=1;var e=xf(),t=bf(),n="[object Number]";function r(i){return typeof i=="number"||t(i)&&e(i)==n}return v6=r,v6}var y6,hue;function k4t(){if(hue)return y6;hue=1;var e=VPe();function t(n){return e(n)&&n!=+n}return y6=t,y6}var E4t=k4t();const Bx=Jn(E4t);var T4t=VPe();const N4t=Jn(T4t);var Zs=function(t){return t===0?0:t>0?1:-1},pm=function(t){return ig(t)&&t.indexOf("%")===t.length-1},dt=function(t){return N4t(t)&&!Bx(t)},C4t=function(t){return mn(t)},Ta=function(t){return dt(t)||ig(t)},A4t=0,qx=function(t){var n=++A4t;return"".concat(t||"").concat(n)},Ys=function(t,n){var r=arguments.length>2&&arguments[2]!==void 0?arguments[2]:0,i=arguments.length>3&&arguments[3]!==void 0?arguments[3]:!1;if(!dt(t)&&!ig(t))return r;var a;if(pm(t)){var s=t.indexOf("%");a=n*parseFloat(t.slice(0,s))/100}else a=+t;return Bx(a)&&(a=r),i&&a>n&&(a=n),a},xp=function(t){if(!t)return null;var n=Object.keys(t);return n&&n.length?t[n[0]]:null},I4t=function(t){if(!Array.isArray(t))return!1;for(var n=t.length,r={},i=0;i<n;i++)if(!r[t[i]])r[t[i]]=!0;else return!0;return!1},mo=function(t,n){return dt(t)&&dt(n)?function(r){return t+r*(n-t)}:function(){return n}};function DI(e,t,n){return!e||!e.length?null:e.find(function(r){return r&&(typeof t=="function"?t(r):Qo(r,t))===n})}var j4t=function(t,n){return dt(t)&&dt(n)?t-n:ig(t)&&ig(n)?t.localeCompare(n):t instanceof Date&&n instanceof Date?t.getTime()-n.getTime():String(t).localeCompare(String(n))};function Gv(e,t){for(var n in e)if({}.hasOwnProperty.call(e,n)&&(!{}.hasOwnProperty.call(t,n)||e[n]!==t[n]))return!1;for(var r in t)if({}.hasOwnProperty.call(t,r)&&!{}.hasOwnProperty.call(e,r))return!1;return!0}function xF(e){"@babel/helpers - typeof";return xF=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},xF(e)}var O4t=["viewBox","children"],R4t=["aria-activedescendant","aria-atomic","aria-autocomplete","aria-busy","aria-checked","aria-colcount","aria-colindex","aria-colspan","aria-controls","aria-current","aria-describedby","aria-details","aria-disabled","aria-errormessage","aria-expanded","aria-flowto","aria-haspopup","aria-hidden","aria-invalid","aria-keyshortcuts","aria-label","aria-labelledby","aria-level","aria-live","aria-modal","aria-multiline","aria-multiselectable","aria-orientation","aria-owns","aria-placeholder","aria-posinset","aria-pressed","aria-readonly","aria-relevant","aria-required","aria-roledescription","aria-rowcount","aria-rowindex","aria-rowspan","aria-selected","aria-setsize","aria-sort","aria-valuemax","aria-valuemin","aria-valuenow","aria-valuetext","className","color","height","id","lang","max","media","method","min","name","style","target","width","role","tabIndex","accentHeight","accumulate","additive","alignmentBaseline","allowReorder","alphabetic","amplitude","arabicForm","ascent","attributeName","attributeType","autoReverse","azimuth","baseFrequency","baselineShift","baseProfile","bbox","begin","bias","by","calcMode","capHeight","clip","clipPath","clipPathUnits","clipRule","colorInterpolation","colorInterpolationFilters","colorProfile","colorRendering","contentScriptType","contentStyleType","cursor","cx","cy","d","decelerate","descent","diffuseConstant","direction","display","divisor","dominantBaseline","dur","dx","dy","edgeMode","elevation","enableBackground","end","exponent","externalResourcesRequired","fill","fillOpacity","fillRule","filter","filterRes","filterUnits","floodColor","floodOpacity","focusable","fontFamily","fontSize","fontSizeAdjust","fontStretch","fontStyle","fontVariant","fontWeight","format","from","fx","fy","g1","g2","glyphName","glyphOrientationHorizontal","glyphOrientationVertical","glyphRef","gradientTransform","gradientUnits","hanging","horizAdvX","horizOriginX","href","ideographic","imageRendering","in2","in","intercept","k1","k2","k3","k4","k","kernelMatrix","kernelUnitLength","kerning","keyPoints","keySplines","keyTimes","lengthAdjust","letterSpacing","lightingColor","limitingConeAngle","local","markerEnd","markerHeight","markerMid","markerStart","markerUnits","markerWidth","mask","maskContentUnits","maskUnits","mathematical","mode","numOctaves","offset","opacity","operator","order","orient","orientation","origin","overflow","overlinePosition","overlineThickness","paintOrder","panose1","pathLength","patternContentUnits","patternTransform","patternUnits","pointerEvents","pointsAtX","pointsAtY","pointsAtZ","preserveAlpha","preserveAspectRatio","primitiveUnits","r","radius","refX","refY","renderingIntent","repeatCount","repeatDur","requiredExtensions","requiredFeatures","restart","result","rotate","rx","ry","seed","shapeRendering","slope","spacing","specularConstant","specularExponent","speed","spreadMethod","startOffset","stdDeviation","stemh","stemv","stitchTiles","stopColor","stopOpacity","strikethroughPosition","strikethroughThickness","string","stroke","strokeDasharray","strokeDashoffset","strokeLinecap","strokeLinejoin","strokeMiterlimit","strokeOpacity","strokeWidth","surfaceScale","systemLanguage","tableValues","targetX","targetY","textAnchor","textDecoration","textLength","textRendering","to","transform","u1","u2","underlinePosition","underlineThickness","unicode","unicodeBidi","unicodeRange","unitsPerEm","vAlphabetic","values","vectorEffect","version","vertAdvY","vertOriginX","vertOriginY","vHanging","vIdeographic","viewTarget","visibility","vMathematical","widths","wordSpacing","writingMode","x1","x2","x","xChannelSelector","xHeight","xlinkActuate","xlinkArcrole","xlinkHref","xlinkRole","xlinkShow","xlinkTitle","xlinkType","xmlBase","xmlLang","xmlns","xmlnsXlink","xmlSpace","y1","y2","y","yChannelSelector","z","zoomAndPan","ref","key","angle"],mue=["points","pathLength"],x6={svg:O4t,polygon:mue,polyline:mue},jK=["dangerouslySetInnerHTML","onCopy","onCopyCapture","onCut","onCutCapture","onPaste","onPasteCapture","onCompositionEnd","onCompositionEndCapture","onCompositionStart","onCompositionStartCapture","onCompositionUpdate","onCompositionUpdateCapture","onFocus","onFocusCapture","onBlur","onBlurCapture","onChange","onChangeCapture","onBeforeInput","onBeforeInputCapture","onInput","onInputCapture","onReset","onResetCapture","onSubmit","onSubmitCapture","onInvalid","onInvalidCapture","onLoad","onLoadCapture","onError","onErrorCapture","onKeyDown","onKeyDownCapture","onKeyPress","onKeyPressCapture","onKeyUp","onKeyUpCapture","onAbort","onAbortCapture","onCanPlay","onCanPlayCapture","onCanPlayThrough","onCanPlayThroughCapture","onDurationChange","onDurationChangeCapture","onEmptied","onEmptiedCapture","onEncrypted","onEncryptedCapture","onEnded","onEndedCapture","onLoadedData","onLoadedDataCapture","onLoadedMetadata","onLoadedMetadataCapture","onLoadStart","onLoadStartCapture","onPause","onPauseCapture","onPlay","onPlayCapture","onPlaying","onPlayingCapture","onProgress","onProgressCapture","onRateChange","onRateChangeCapture","onSeeked","onSeekedCapture","onSeeking","onSeekingCapture","onStalled","onStalledCapture","onSuspend","onSuspendCapture","onTimeUpdate","onTimeUpdateCapture","onVolumeChange","onVolumeChangeCapture","onWaiting","onWaitingCapture","onAuxClick","onAuxClickCapture","onClick","onClickCapture","onContextMenu","onContextMenuCapture","onDoubleClick","onDoubleClickCapture","onDrag","onDragCapture","onDragEnd","onDragEndCapture","onDragEnter","onDragEnterCapture","onDragExit","onDragExitCapture","onDragLeave","onDragLeaveCapture","onDragOver","onDragOverCapture","onDragStart","onDragStartCapture","onDrop","onDropCapture","onMouseDown","onMouseDownCapture","onMouseEnter","onMouseLeave","onMouseMove","onMouseMoveCapture","onMouseOut","onMouseOutCapture","onMouseOver","onMouseOverCapture","onMouseUp","onMouseUpCapture","onSelect","onSelectCapture","onTouchCancel","onTouchCancelCapture","onTouchEnd","onTouchEndCapture","onTouchMove","onTouchMoveCapture","onTouchStart","onTouchStartCapture","onPointerDown","onPointerDownCapture","onPointerMove","onPointerMoveCapture","onPointerUp","onPointerUpCapture","onPointerCancel","onPointerCancelCapture","onPointerEnter","onPointerEnterCapture","onPointerLeave","onPointerLeaveCapture","onPointerOver","onPointerOverCapture","onPointerOut","onPointerOutCapture","onGotPointerCapture","onGotPointerCaptureCapture","onLostPointerCapture","onLostPointerCaptureCapture","onScroll","onScrollCapture","onWheel","onWheelCapture","onAnimationStart","onAnimationStartCapture","onAnimationEnd","onAnimationEndCapture","onAnimationIteration","onAnimationIterationCapture","onTransitionEnd","onTransitionEndCapture"],LI=function(t,n){if(!t||typeof t=="function"||typeof t=="boolean")return null;var r=t;if(b.isValidElement(t)&&(r=t.props),!Fx(r))return null;var i={};return Object.keys(r).forEach(function(a){jK.includes(a)&&(i[a]=n||function(s){return r[a](r,s)})}),i},P4t=function(t,n,r){return function(i){return t(n,r,i),null}},ag=function(t,n,r){if(!Fx(t)||xF(t)!=="object")return null;var i=null;return Object.keys(t).forEach(function(a){var s=t[a];jK.includes(a)&&typeof s=="function"&&(i||(i={}),i[a]=P4t(s,n,r))}),i},$4t=["children"],M4t=["children"];function gue(e,t){if(e==null)return{};var n=D4t(e,t),r,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function D4t(e,t){if(e==null)return{};var n={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;n[r]=e[r]}return n}function bF(e){"@babel/helpers - typeof";return bF=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},bF(e)}var vue={click:"onClick",mousedown:"onMouseDown",mouseup:"onMouseUp",mouseover:"onMouseOver",mousemove:"onMouseMove",mouseout:"onMouseOut",mouseenter:"onMouseEnter",mouseleave:"onMouseLeave",touchcancel:"onTouchCancel",touchend:"onTouchEnd",touchmove:"onTouchMove",touchstart:"onTouchStart",contextmenu:"onContextMenu",dblclick:"onDoubleClick"},Wd=function(t){return typeof t=="string"?t:t?t.displayName||t.name||"Component":""},yue=null,b6=null,OK=function e(t){if(t===yue&&Array.isArray(b6))return b6;var n=[];return b.Children.forEach(t,function(r){mn(r)||(S4t.isFragment(r)?n=n.concat(e(r.props.children)):n.push(r))}),b6=n,yue=t,n};function $l(e,t){var n=[],r=[];return Array.isArray(t)?r=t.map(function(i){return Wd(i)}):r=[Wd(t)],OK(e).forEach(function(i){var a=Qo(i,"type.displayName")||Qo(i,"type.name");r.indexOf(a)!==-1&&n.push(i)}),n}function Bo(e,t){var n=$l(e,t);return n&&n[0]}var xue=function(t){if(!t||!t.props)return!1;var n=t.props,r=n.width,i=n.height;return!(!dt(r)||r<=0||!dt(i)||i<=0)},L4t=["a","altGlyph","altGlyphDef","altGlyphItem","animate","animateColor","animateMotion","animateTransform","circle","clipPath","color-profile","cursor","defs","desc","ellipse","feBlend","feColormatrix","feComponentTransfer","feComposite","feConvolveMatrix","feDiffuseLighting","feDisplacementMap","feDistantLight","feFlood","feFuncA","feFuncB","feFuncG","feFuncR","feGaussianBlur","feImage","feMerge","feMergeNode","feMorphology","feOffset","fePointLight","feSpecularLighting","feSpotLight","feTile","feTurbulence","filter","font","font-face","font-face-format","font-face-name","font-face-url","foreignObject","g","glyph","glyphRef","hkern","image","line","lineGradient","marker","mask","metadata","missing-glyph","mpath","path","pattern","polygon","polyline","radialGradient","rect","script","set","stop","style","svg","switch","symbol","text","textPath","title","tref","tspan","use","view","vkern"],z4t=function(t){return t&&t.type&&ig(t.type)&&L4t.indexOf(t.type)>=0},U4t=function(t){return t&&bF(t)==="object"&&"clipDot"in t},F4t=function(t,n,r,i){var a,s=(a=x6?.[i])!==null&&a!==void 0?a:[];return n.startsWith("data-")||!nn(t)&&(i&&s.includes(n)||R4t.includes(n))||r&&jK.includes(n)},Vt=function(t,n,r){if(!t||typeof t=="function"||typeof t=="boolean")return null;var i=t;if(b.isValidElement(t)&&(i=t.props),!Fx(i))return null;var a={};return Object.keys(i).forEach(function(s){var o;F4t((o=i)===null||o===void 0?void 0:o[s],s,n,r)&&(a[s]=i[s])}),a},_F=function e(t,n){if(t===n)return!0;var r=b.Children.count(t);if(r!==b.Children.count(n))return!1;if(r===0)return!0;if(r===1)return bue(Array.isArray(t)?t[0]:t,Array.isArray(n)?n[0]:n);for(var i=0;i<r;i++){var a=t[i],s=n[i];if(Array.isArray(a)||Array.isArray(s)){if(!e(a,s))return!1}else if(!bue(a,s))return!1}return!0},bue=function(t,n){if(mn(t)&&mn(n))return!0;if(!mn(t)&&!mn(n)){var r=t.props||{},i=r.children,a=gue(r,$4t),s=n.props||{},o=s.children,u=gue(s,M4t);return i&&o?Gv(a,u)&&_F(i,o):!i&&!o?Gv(a,u):!1}return!1},_ue=function(t,n){var r=[],i={};return OK(t).forEach(function(a,s){if(z4t(a))r.push(a);else if(a){var o=Wd(a.type),u=n[o]||{},c=u.handler,d=u.once;if(c&&(!d||!i[o])){var f=c(a,o,s);r.push(f),i[o]=!0}}}),r},B4t=function(t){var n=t&&t.type;return n&&vue[n]?vue[n]:null},q4t=function(t,n){return OK(n).indexOf(t)},H4t=["children","width","height","viewBox","className","style","title","desc"];function wF(){return wF=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},wF.apply(this,arguments)}function V4t(e,t){if(e==null)return{};var n=G4t(e,t),r,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function G4t(e,t){if(e==null)return{};var n={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;n[r]=e[r]}return n}function SF(e){var t=e.children,n=e.width,r=e.height,i=e.viewBox,a=e.className,s=e.style,o=e.title,u=e.desc,c=V4t(e,H4t),d=i||{width:n,height:r,x:0,y:0},f=dn("recharts-surface",a);return de.createElement("svg",wF({},Vt(c,!0,"svg"),{className:f,width:n,height:r,style:s,viewBox:"".concat(d.x," ").concat(d.y," ").concat(d.width," ").concat(d.height)}),de.createElement("title",null,o),de.createElement("desc",null,u),t)}var W4t=["children","className"];function kF(){return kF=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},kF.apply(this,arguments)}function K4t(e,t){if(e==null)return{};var n=Z4t(e,t),r,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function Z4t(e,t){if(e==null)return{};var n={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;n[r]=e[r]}return n}var lr=de.forwardRef(function(e,t){var n=e.children,r=e.className,i=K4t(e,W4t),a=dn("recharts-layer",r);return de.createElement("g",kF({className:a},Vt(i,!0),{ref:t}),n)}),Eu=function(t,n){for(var r=arguments.length,i=new Array(r>2?r-2:0),a=2;a<r;a++)i[a-2]=arguments[a]},_6,wue;function Y4t(){if(wue)return _6;wue=1;function e(t,n,r){var i=-1,a=t.length;n<0&&(n=-n>a?0:a+n),r=r>a?a:r,r<0&&(r+=a),a=n>r?0:r-n>>>0,n>>>=0;for(var s=Array(a);++i<a;)s[i]=t[i+n];return s}return _6=e,_6}var w6,Sue;function X4t(){if(Sue)return w6;Sue=1;var e=Y4t();function t(n,r,i){var a=n.length;return i=i===void 0?a:i,!r&&i>=a?n:e(n,r,i)}return w6=t,w6}var S6,kue;function GPe(){if(kue)return S6;kue=1;var e="\\ud800-\\udfff",t="\\u0300-\\u036f",n="\\ufe20-\\ufe2f",r="\\u20d0-\\u20ff",i=t+n+r,a="\\ufe0e\\ufe0f",s="\\u200d",o=RegExp("["+s+e+i+a+"]");function u(c){return o.test(c)}return S6=u,S6}var k6,Eue;function J4t(){if(Eue)return k6;Eue=1;function e(t){return t.split("")}return k6=e,k6}var E6,Tue;function Q4t(){if(Tue)return E6;Tue=1;var e="\\ud800-\\udfff",t="\\u0300-\\u036f",n="\\ufe20-\\ufe2f",r="\\u20d0-\\u20ff",i=t+n+r,a="\\ufe0e\\ufe0f",s="["+e+"]",o="["+i+"]",u="\\ud83c[\\udffb-\\udfff]",c="(?:"+o+"|"+u+")",d="[^"+e+"]",f="(?:\\ud83c[\\udde6-\\uddff]){2}",p="[\\ud800-\\udbff][\\udc00-\\udfff]",m="\\u200d",y=c+"?",v="["+a+"]?",x="(?:"+m+"(?:"+[d,f,p].join("|")+")"+v+y+")*",_=v+y+x,S="(?:"+[d+o+"?",o,f,p,s].join("|")+")",w=RegExp(u+"(?="+u+")|"+S+_,"g");function T(N){return N.match(w)||[]}return E6=T,E6}var T6,Nue;function e$t(){if(Nue)return T6;Nue=1;var e=J4t(),t=GPe(),n=Q4t();function r(i){return t(i)?n(i):e(i)}return T6=r,T6}var N6,Cue;function t$t(){if(Cue)return N6;Cue=1;var e=X4t(),t=GPe(),n=e$t(),r=BPe();function i(a){return function(s){s=r(s);var o=t(s)?n(s):void 0,u=o?o[0]:s.charAt(0),c=o?e(o,1).join(""):s.slice(1);return u[a]()+c}}return N6=i,N6}var C6,Aue;function n$t(){if(Aue)return C6;Aue=1;var e=t$t(),t=e("toUpperCase");return C6=t,C6}var r$t=n$t();const JR=Jn(r$t);function ri(e){return function(){return e}}const WPe=Math.cos,zI=Math.sin,Fu=Math.sqrt,UI=Math.PI,QR=2*UI,EF=Math.PI,TF=2*EF,sm=1e-6,i$t=TF-sm;function KPe(e){this._+=e[0];for(let t=1,n=e.length;t<n;++t)this._+=arguments[t]+e[t]}function a$t(e){let t=Math.floor(e);if(!(t>=0))throw new Error(`invalid digits: ${e}`);if(t>15)return KPe;const n=10**t;return function(r){this._+=r[0];for(let i=1,a=r.length;i<a;++i)this._+=Math.round(arguments[i]*n)/n+r[i]}}class s$t{constructor(t){this._x0=this._y0=this._x1=this._y1=null,this._="",this._append=t==null?KPe:a$t(t)}moveTo(t,n){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}`}closePath(){this._x1!==null&&(this._x1=this._x0,this._y1=this._y0,this._append`Z`)}lineTo(t,n){this._append`L${this._x1=+t},${this._y1=+n}`}quadraticCurveTo(t,n,r,i){this._append`Q${+t},${+n},${this._x1=+r},${this._y1=+i}`}bezierCurveTo(t,n,r,i,a,s){this._append`C${+t},${+n},${+r},${+i},${this._x1=+a},${this._y1=+s}`}arcTo(t,n,r,i,a){if(t=+t,n=+n,r=+r,i=+i,a=+a,a<0)throw new Error(`negative radius: ${a}`);let s=this._x1,o=this._y1,u=r-t,c=i-n,d=s-t,f=o-n,p=d*d+f*f;if(this._x1===null)this._append`M${this._x1=t},${this._y1=n}`;else if(p>sm)if(!(Math.abs(f*u-c*d)>sm)||!a)this._append`L${this._x1=t},${this._y1=n}`;else{let m=r-s,y=i-o,v=u*u+c*c,x=m*m+y*y,_=Math.sqrt(v),S=Math.sqrt(p),w=a*Math.tan((EF-Math.acos((v+p-x)/(2*_*S)))/2),T=w/S,N=w/_;Math.abs(T-1)>sm&&this._append`L${t+T*d},${n+T*f}`,this._append`A${a},${a},0,0,${+(f*m>d*y)},${this._x1=t+N*u},${this._y1=n+N*c}`}}arc(t,n,r,i,a,s){if(t=+t,n=+n,r=+r,s=!!s,r<0)throw new Error(`negative radius: ${r}`);let o=r*Math.cos(i),u=r*Math.sin(i),c=t+o,d=n+u,f=1^s,p=s?i-a:a-i;this._x1===null?this._append`M${c},${d}`:(Math.abs(this._x1-c)>sm||Math.abs(this._y1-d)>sm)&&this._append`L${c},${d}`,r&&(p<0&&(p=p%TF+TF),p>i$t?this._append`A${r},${r},0,1,${f},${t-o},${n-u}A${r},${r},0,1,${f},${this._x1=c},${this._y1=d}`:p>sm&&this._append`A${r},${r},0,${+(p>=EF)},${f},${this._x1=t+r*Math.cos(a)},${this._y1=n+r*Math.sin(a)}`)}rect(t,n,r,i){this._append`M${this._x0=this._x1=+t},${this._y0=this._y1=+n}h${r=+r}v${+i}h${-r}Z`}toString(){return this._}}function RK(e){let t=3;return e.digits=function(n){if(!arguments.length)return t;if(n==null)t=null;else{const r=Math.floor(n);if(!(r>=0))throw new RangeError(`invalid digits: ${n}`);t=r}return e},()=>new s$t(t)}function PK(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function ZPe(e){this._context=e}ZPe.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:this._context.lineTo(e,t);break}}};function eP(e){return new ZPe(e)}function YPe(e){return e[0]}function XPe(e){return e[1]}function JPe(e,t){var n=ri(!0),r=null,i=eP,a=null,s=RK(o);e=typeof e=="function"?e:e===void 0?YPe:ri(e),t=typeof t=="function"?t:t===void 0?XPe:ri(t);function o(u){var c,d=(u=PK(u)).length,f,p=!1,m;for(r==null&&(a=i(m=s())),c=0;c<=d;++c)!(c<d&&n(f=u[c],c,u))===p&&((p=!p)?a.lineStart():a.lineEnd()),p&&a.point(+e(f,c,u),+t(f,c,u));if(m)return a=null,m+""||null}return o.x=function(u){return arguments.length?(e=typeof u=="function"?u:ri(+u),o):e},o.y=function(u){return arguments.length?(t=typeof u=="function"?u:ri(+u),o):t},o.defined=function(u){return arguments.length?(n=typeof u=="function"?u:ri(!!u),o):n},o.curve=function(u){return arguments.length?(i=u,r!=null&&(a=i(r)),o):i},o.context=function(u){return arguments.length?(u==null?r=a=null:a=i(r=u),o):r},o}function yN(e,t,n){var r=null,i=ri(!0),a=null,s=eP,o=null,u=RK(c);e=typeof e=="function"?e:e===void 0?YPe:ri(+e),t=typeof t=="function"?t:ri(t===void 0?0:+t),n=typeof n=="function"?n:n===void 0?XPe:ri(+n);function c(f){var p,m,y,v=(f=PK(f)).length,x,_=!1,S,w=new Array(v),T=new Array(v);for(a==null&&(o=s(S=u())),p=0;p<=v;++p){if(!(p<v&&i(x=f[p],p,f))===_)if(_=!_)m=p,o.areaStart(),o.lineStart();else{for(o.lineEnd(),o.lineStart(),y=p-1;y>=m;--y)o.point(w[y],T[y]);o.lineEnd(),o.areaEnd()}_&&(w[p]=+e(x,p,f),T[p]=+t(x,p,f),o.point(r?+r(x,p,f):w[p],n?+n(x,p,f):T[p]))}if(S)return o=null,S+""||null}function d(){return JPe().defined(i).curve(s).context(a)}return c.x=function(f){return arguments.length?(e=typeof f=="function"?f:ri(+f),r=null,c):e},c.x0=function(f){return arguments.length?(e=typeof f=="function"?f:ri(+f),c):e},c.x1=function(f){return arguments.length?(r=f==null?null:typeof f=="function"?f:ri(+f),c):r},c.y=function(f){return arguments.length?(t=typeof f=="function"?f:ri(+f),n=null,c):t},c.y0=function(f){return arguments.length?(t=typeof f=="function"?f:ri(+f),c):t},c.y1=function(f){return arguments.length?(n=f==null?null:typeof f=="function"?f:ri(+f),c):n},c.lineX0=c.lineY0=function(){return d().x(e).y(t)},c.lineY1=function(){return d().x(e).y(n)},c.lineX1=function(){return d().x(r).y(t)},c.defined=function(f){return arguments.length?(i=typeof f=="function"?f:ri(!!f),c):i},c.curve=function(f){return arguments.length?(s=f,a!=null&&(o=s(a)),c):s},c.context=function(f){return arguments.length?(f==null?a=o=null:o=s(a=f),c):a},c}class QPe{constructor(t,n){this._context=t,this._x=n}areaStart(){this._line=0}areaEnd(){this._line=NaN}lineStart(){this._point=0}lineEnd(){(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line}point(t,n){switch(t=+t,n=+n,this._point){case 0:{this._point=1,this._line?this._context.lineTo(t,n):this._context.moveTo(t,n);break}case 1:this._point=2;default:{this._x?this._context.bezierCurveTo(this._x0=(this._x0+t)/2,this._y0,this._x0,n,t,n):this._context.bezierCurveTo(this._x0,this._y0=(this._y0+n)/2,t,this._y0,t,n);break}}this._x0=t,this._y0=n}}function o$t(e){return new QPe(e,!0)}function l$t(e){return new QPe(e,!1)}const $K={draw(e,t){const n=Fu(t/UI);e.moveTo(n,0),e.arc(0,0,n,0,QR)}},u$t={draw(e,t){const n=Fu(t/5)/2;e.moveTo(-3*n,-n),e.lineTo(-n,-n),e.lineTo(-n,-3*n),e.lineTo(n,-3*n),e.lineTo(n,-n),e.lineTo(3*n,-n),e.lineTo(3*n,n),e.lineTo(n,n),e.lineTo(n,3*n),e.lineTo(-n,3*n),e.lineTo(-n,n),e.lineTo(-3*n,n),e.closePath()}},e4e=Fu(1/3),c$t=e4e*2,d$t={draw(e,t){const n=Fu(t/c$t),r=n*e4e;e.moveTo(0,-n),e.lineTo(r,0),e.lineTo(0,n),e.lineTo(-r,0),e.closePath()}},f$t={draw(e,t){const n=Fu(t),r=-n/2;e.rect(r,r,n,n)}},p$t=.8908130915292852,t4e=zI(UI/10)/zI(7*UI/10),h$t=zI(QR/10)*t4e,m$t=-WPe(QR/10)*t4e,g$t={draw(e,t){const n=Fu(t*p$t),r=h$t*n,i=m$t*n;e.moveTo(0,-n),e.lineTo(r,i);for(let a=1;a<5;++a){const s=QR*a/5,o=WPe(s),u=zI(s);e.lineTo(u*n,-o*n),e.lineTo(o*r-u*i,u*r+o*i)}e.closePath()}},A6=Fu(3),v$t={draw(e,t){const n=-Fu(t/(A6*3));e.moveTo(0,n*2),e.lineTo(-A6*n,-n),e.lineTo(A6*n,-n),e.closePath()}},vl=-.5,yl=Fu(3)/2,NF=1/Fu(12),y$t=(NF/2+1)*3,x$t={draw(e,t){const n=Fu(t/y$t),r=n/2,i=n*NF,a=r,s=n*NF+n,o=-a,u=s;e.moveTo(r,i),e.lineTo(a,s),e.lineTo(o,u),e.lineTo(vl*r-yl*i,yl*r+vl*i),e.lineTo(vl*a-yl*s,yl*a+vl*s),e.lineTo(vl*o-yl*u,yl*o+vl*u),e.lineTo(vl*r+yl*i,vl*i-yl*r),e.lineTo(vl*a+yl*s,vl*s-yl*a),e.lineTo(vl*o+yl*u,vl*u-yl*o),e.closePath()}};function b$t(e,t){let n=null,r=RK(i);e=typeof e=="function"?e:ri(e||$K),t=typeof t=="function"?t:ri(t===void 0?64:+t);function i(){let a;if(n||(n=a=r()),e.apply(this,arguments).draw(n,+t.apply(this,arguments)),a)return n=null,a+""||null}return i.type=function(a){return arguments.length?(e=typeof a=="function"?a:ri(a),i):e},i.size=function(a){return arguments.length?(t=typeof a=="function"?a:ri(+a),i):t},i.context=function(a){return arguments.length?(n=a??null,i):n},i}function FI(){}function BI(e,t,n){e._context.bezierCurveTo((2*e._x0+e._x1)/3,(2*e._y0+e._y1)/3,(e._x0+2*e._x1)/3,(e._y0+2*e._y1)/3,(e._x0+4*e._x1+t)/6,(e._y0+4*e._y1+n)/6)}function n4e(e){this._context=e}n4e.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){switch(this._point){case 3:BI(this,this._x1,this._y1);case 2:this._context.lineTo(this._x1,this._y1);break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,this._context.lineTo((5*this._x0+this._x1)/6,(5*this._y0+this._y1)/6);default:BI(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function _$t(e){return new n4e(e)}function r4e(e){this._context=e}r4e.prototype={areaStart:FI,areaEnd:FI,lineStart:function(){this._x0=this._x1=this._x2=this._x3=this._x4=this._y0=this._y1=this._y2=this._y3=this._y4=NaN,this._point=0},lineEnd:function(){switch(this._point){case 1:{this._context.moveTo(this._x2,this._y2),this._context.closePath();break}case 2:{this._context.moveTo((this._x2+2*this._x3)/3,(this._y2+2*this._y3)/3),this._context.lineTo((this._x3+2*this._x2)/3,(this._y3+2*this._y2)/3),this._context.closePath();break}case 3:{this.point(this._x2,this._y2),this.point(this._x3,this._y3),this.point(this._x4,this._y4);break}}},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._x2=e,this._y2=t;break;case 1:this._point=2,this._x3=e,this._y3=t;break;case 2:this._point=3,this._x4=e,this._y4=t,this._context.moveTo((this._x0+4*this._x1+e)/6,(this._y0+4*this._y1+t)/6);break;default:BI(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function w$t(e){return new r4e(e)}function i4e(e){this._context=e}i4e.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=NaN,this._point=0},lineEnd:function(){(this._line||this._line!==0&&this._point===3)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1;break;case 1:this._point=2;break;case 2:this._point=3;var n=(this._x0+4*this._x1+e)/6,r=(this._y0+4*this._y1+t)/6;this._line?this._context.lineTo(n,r):this._context.moveTo(n,r);break;case 3:this._point=4;default:BI(this,e,t);break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t}};function S$t(e){return new i4e(e)}function a4e(e){this._context=e}a4e.prototype={areaStart:FI,areaEnd:FI,lineStart:function(){this._point=0},lineEnd:function(){this._point&&this._context.closePath()},point:function(e,t){e=+e,t=+t,this._point?this._context.lineTo(e,t):(this._point=1,this._context.moveTo(e,t))}};function k$t(e){return new a4e(e)}function Iue(e){return e<0?-1:1}function jue(e,t,n){var r=e._x1-e._x0,i=t-e._x1,a=(e._y1-e._y0)/(r||i<0&&-0),s=(n-e._y1)/(i||r<0&&-0),o=(a*i+s*r)/(r+i);return(Iue(a)+Iue(s))*Math.min(Math.abs(a),Math.abs(s),.5*Math.abs(o))||0}function Oue(e,t){var n=e._x1-e._x0;return n?(3*(e._y1-e._y0)/n-t)/2:t}function I6(e,t,n){var r=e._x0,i=e._y0,a=e._x1,s=e._y1,o=(a-r)/3;e._context.bezierCurveTo(r+o,i+o*t,a-o,s-o*n,a,s)}function qI(e){this._context=e}qI.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x0=this._x1=this._y0=this._y1=this._t0=NaN,this._point=0},lineEnd:function(){switch(this._point){case 2:this._context.lineTo(this._x1,this._y1);break;case 3:I6(this,this._t0,Oue(this,this._t0));break}(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line=1-this._line},point:function(e,t){var n=NaN;if(e=+e,t=+t,!(e===this._x1&&t===this._y1)){switch(this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;break;case 2:this._point=3,I6(this,Oue(this,n=jue(this,e,t)),n);break;default:I6(this,this._t0,n=jue(this,e,t));break}this._x0=this._x1,this._x1=e,this._y0=this._y1,this._y1=t,this._t0=n}}};function s4e(e){this._context=new o4e(e)}(s4e.prototype=Object.create(qI.prototype)).point=function(e,t){qI.prototype.point.call(this,t,e)};function o4e(e){this._context=e}o4e.prototype={moveTo:function(e,t){this._context.moveTo(t,e)},closePath:function(){this._context.closePath()},lineTo:function(e,t){this._context.lineTo(t,e)},bezierCurveTo:function(e,t,n,r,i,a){this._context.bezierCurveTo(t,e,r,n,a,i)}};function E$t(e){return new qI(e)}function T$t(e){return new s4e(e)}function l4e(e){this._context=e}l4e.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=[],this._y=[]},lineEnd:function(){var e=this._x,t=this._y,n=e.length;if(n)if(this._line?this._context.lineTo(e[0],t[0]):this._context.moveTo(e[0],t[0]),n===2)this._context.lineTo(e[1],t[1]);else for(var r=Rue(e),i=Rue(t),a=0,s=1;s<n;++a,++s)this._context.bezierCurveTo(r[0][a],i[0][a],r[1][a],i[1][a],e[s],t[s]);(this._line||this._line!==0&&n===1)&&this._context.closePath(),this._line=1-this._line,this._x=this._y=null},point:function(e,t){this._x.push(+e),this._y.push(+t)}};function Rue(e){var t,n=e.length-1,r,i=new Array(n),a=new Array(n),s=new Array(n);for(i[0]=0,a[0]=2,s[0]=e[0]+2*e[1],t=1;t<n-1;++t)i[t]=1,a[t]=4,s[t]=4*e[t]+2*e[t+1];for(i[n-1]=2,a[n-1]=7,s[n-1]=8*e[n-1]+e[n],t=1;t<n;++t)r=i[t]/a[t-1],a[t]-=r,s[t]-=r*s[t-1];for(i[n-1]=s[n-1]/a[n-1],t=n-2;t>=0;--t)i[t]=(s[t]-i[t+1])/a[t];for(a[n-1]=(e[n]+i[n-1])/2,t=0;t<n-1;++t)a[t]=2*e[t+1]-i[t+1];return[i,a]}function N$t(e){return new l4e(e)}function tP(e,t){this._context=e,this._t=t}tP.prototype={areaStart:function(){this._line=0},areaEnd:function(){this._line=NaN},lineStart:function(){this._x=this._y=NaN,this._point=0},lineEnd:function(){0<this._t&&this._t<1&&this._point===2&&this._context.lineTo(this._x,this._y),(this._line||this._line!==0&&this._point===1)&&this._context.closePath(),this._line>=0&&(this._t=1-this._t,this._line=1-this._line)},point:function(e,t){switch(e=+e,t=+t,this._point){case 0:this._point=1,this._line?this._context.lineTo(e,t):this._context.moveTo(e,t);break;case 1:this._point=2;default:{if(this._t<=0)this._context.lineTo(this._x,t),this._context.lineTo(e,t);else{var n=this._x*(1-this._t)+e*this._t;this._context.lineTo(n,this._y),this._context.lineTo(n,t)}break}}this._x=e,this._y=t}};function C$t(e){return new tP(e,.5)}function A$t(e){return new tP(e,0)}function I$t(e){return new tP(e,1)}function Ty(e,t){if((s=e.length)>1)for(var n=1,r,i,a=e[t[0]],s,o=a.length;n<s;++n)for(i=a,a=e[t[n]],r=0;r<o;++r)a[r][1]+=a[r][0]=isNaN(i[r][1])?i[r][0]:i[r][1]}function CF(e){for(var t=e.length,n=new Array(t);--t>=0;)n[t]=t;return n}function j$t(e,t){return e[t]}function O$t(e){const t=[];return t.key=e,t}function R$t(){var e=ri([]),t=CF,n=Ty,r=j$t;function i(a){var s=Array.from(e.apply(this,arguments),O$t),o,u=s.length,c=-1,d;for(const f of a)for(o=0,++c;o<u;++o)(s[o][c]=[0,+r(f,s[o].key,c,a)]).data=f;for(o=0,d=PK(t(s));o<u;++o)s[d[o]].index=o;return n(s,d),s}return i.keys=function(a){return arguments.length?(e=typeof a=="function"?a:ri(Array.from(a)),i):e},i.value=function(a){return arguments.length?(r=typeof a=="function"?a:ri(+a),i):r},i.order=function(a){return arguments.length?(t=a==null?CF:typeof a=="function"?a:ri(Array.from(a)),i):t},i.offset=function(a){return arguments.length?(n=a??Ty,i):n},i}function P$t(e,t){if((r=e.length)>0){for(var n,r,i=0,a=e[0].length,s;i<a;++i){for(s=n=0;n<r;++n)s+=e[n][i][1]||0;if(s)for(n=0;n<r;++n)e[n][i][1]/=s}Ty(e,t)}}function $$t(e,t){if((i=e.length)>0){for(var n=0,r=e[t[0]],i,a=r.length;n<a;++n){for(var s=0,o=0;s<i;++s)o+=e[s][n][1]||0;r[n][1]+=r[n][0]=-o/2}Ty(e,t)}}function M$t(e,t){if(!(!((s=e.length)>0)||!((a=(i=e[t[0]]).length)>0))){for(var n=0,r=1,i,a,s;r<a;++r){for(var o=0,u=0,c=0;o<s;++o){for(var d=e[t[o]],f=d[r][1]||0,p=d[r-1][1]||0,m=(f-p)/2,y=0;y<o;++y){var v=e[t[y]],x=v[r][1]||0,_=v[r-1][1]||0;m+=x-_}u+=f,c+=m*f}i[r-1][1]+=i[r-1][0]=n,u&&(n-=c/u)}i[r-1][1]+=i[r-1][0]=n,Ty(e,t)}}function i2(e){"@babel/helpers - typeof";return i2=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},i2(e)}var D$t=["type","size","sizeType"];function AF(){return AF=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},AF.apply(this,arguments)}function Pue(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function $ue(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Pue(Object(n),!0).forEach(function(r){L$t(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Pue(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function L$t(e,t,n){return t=z$t(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function z$t(e){var t=U$t(e,"string");return i2(t)=="symbol"?t:t+""}function U$t(e,t){if(i2(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(i2(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function F$t(e,t){if(e==null)return{};var n=B$t(e,t),r,i;if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(i=0;i<a.length;i++)r=a[i],!(t.indexOf(r)>=0)&&Object.prototype.propertyIsEnumerable.call(e,r)&&(n[r]=e[r])}return n}function B$t(e,t){if(e==null)return{};var n={};for(var r in e)if(Object.prototype.hasOwnProperty.call(e,r)){if(t.indexOf(r)>=0)continue;n[r]=e[r]}return n}var u4e={symbolCircle:$K,symbolCross:u$t,symbolDiamond:d$t,symbolSquare:f$t,symbolStar:g$t,symbolTriangle:v$t,symbolWye:x$t},q$t=Math.PI/180,H$t=function(t){var n="symbol".concat(JR(t));return u4e[n]||$K},V$t=function(t,n,r){if(n==="area")return t;switch(r){case"cross":return 5*t*t/9;case"diamond":return .5*t*t/Math.sqrt(3);case"square":return t*t;case"star":{var i=18*q$t;return 1.25*t*t*(Math.tan(i)-Math.tan(i*2)*Math.pow(Math.tan(i),2))}case"triangle":return Math.sqrt(3)*t*t/4;case"wye":return(21-10*Math.sqrt(3))*t*t/8;default:return Math.PI*t*t/4}},G$t=function(t,n){u4e["symbol".concat(JR(t))]=n},MK=function(t){var n=t.type,r=n===void 0?"circle":n,i=t.size,a=i===void 0?64:i,s=t.sizeType,o=s===void 0?"area":s,u=F$t(t,D$t),c=$ue($ue({},u),{},{type:r,size:a,sizeType:o}),d=function(){var x=H$t(r),_=b$t().type(x).size(V$t(a,o,r));return _()},f=c.className,p=c.cx,m=c.cy,y=Vt(c,!0);return p===+p&&m===+m&&a===+a?de.createElement("path",AF({},y,{className:dn("recharts-symbols",f),transform:"translate(".concat(p,", ").concat(m,")"),d:d()})):null};MK.registerSymbol=G$t;function Ny(e){"@babel/helpers - typeof";return Ny=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(t){return typeof t}:function(t){return t&&typeof Symbol=="function"&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Ny(e)}function IF(){return IF=Object.assign?Object.assign.bind():function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},IF.apply(this,arguments)}function Mue(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(i){return Object.getOwnPropertyDescriptor(e,i).enumerable})),n.push.apply(n,r)}return n}function W$t(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Mue(Object(n),!0).forEach(function(r){a2(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Mue(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function K$t(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function Z$t(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,d4e(r.key),r)}}function Y$t(e,t,n){return t&&Z$t(e.prototype,t),Object.defineProperty(e,"prototype",{writable:!1}),e}function X$t(e,t,n){return t=HI(t),J$t(e,c4e()?Reflect.construct(t,n||[],HI(e).constructor):t.apply(e,n))}function J$t(e,t){if(t&&(Ny(t)==="object"||typeof t=="function"))return t;if(t!==void 0)throw new TypeError("Derived constructors may only return object or undefined");return Q$t(e)}function Q$t(e){if(e===void 0)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function c4e(){try{var e=!Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],function(){}))}catch{}return(c4e=function(){return!!e})()}function HI(e){return HI=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(n){return n.__proto__||Object.getPrototypeOf(n)},HI(e)}function eMt(e,t){if(typeof t!="function"&&t!==null)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&jF(e,t)}function jF(e,t){return jF=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(r,i){return r.__proto__=i,r},jF(e,t)}function a2(e,t,n){return t=d4e(t),t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function d4e(e){var t=tMt(e,"string");return Ny(t)=="symbol"?t:t+""}function tMt(e,t){if(Ny(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(Ny(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}var xl=32,DK=(function(e){function t(){return K$t(this,t),X$t(this,t,arguments)}return eMt(t,e),Y$t(t,[{key:"renderIcon",value:function(r){var i=this.props.inactiveColor,a=xl/2,s=xl/6,o=xl/3,u=r.inactive?i:r.color;if(r.type==="plainline")return de.createElement("line",{strokeWidth:4,fill:"none",stroke:u,strokeDasharray:r.payload.strokeDasharray,x1:0,y1:a,x2:xl,y2:a,className:"recharts-legend-icon"});if(r.type==="line")return de.createElement("path",{strokeWidth:4,fill:"none",stroke:u,d:"M0,".concat(a,"h").concat(o,`
|
|
1772
1772
|
A`).concat(s,",").concat(s,",0,1,1,").concat(2*o,",").concat(a,`
|
|
@@ -1837,7 +1837,7 @@ ${n.map(([a,s])=>{const o=s.theme?.[r]||s.color;return o?` --color-${a}: ${o};`
|
|
|
1837
1837
|
`)}
|
|
1838
1838
|
}
|
|
1839
1839
|
`).join(`
|
|
1840
|
-
`)}}):null},Fd=rc;function AZ({active:e,payload:t,className:n,indicator:r="dot",hideLabel:i=!1,hideIndicator:a=!1,label:s,labelFormatter:o,labelClassName:u,formatter:c,color:d,nameKey:f,labelKey:p}){const{config:m}=CGt(),y=b.useMemo(()=>{if(i||!t?.length)return null;const[x]=t,_=`${p||x?.dataKey||x?.name||"value"}`,S=sme(m,x,_),w=!p&&typeof s=="string"?m[s]?.label||s:S?.label;return o?l.jsx("div",{className:Ie("font-medium",u),children:o(w,t)}):w?l.jsx("div",{className:Ie("font-medium",u),children:w}):null},[s,o,t,i,u,m,p]);if(!e||!t?.length)return null;const v=t.length===1&&r!=="dot";return l.jsxs("div",{className:Ie("border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",n),children:[v?null:y,l.jsx("div",{className:"grid gap-1.5",children:t.map((x,_)=>{const S=`${f||x.name||x.dataKey||"value"}`,w=sme(m,x,S),T=d||x.payload.fill||x.color;return l.jsx("div",{className:Ie("[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",r==="dot"&&"items-center"),children:c&&x?.value!==void 0&&x.name?c(x.value,x.name,x,_,x.payload):l.jsxs(l.Fragment,{children:[w?.icon?l.jsx(w.icon,{}):!a&&l.jsx("div",{className:Ie("shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",{"h-2.5 w-2.5":r==="dot","w-1":r==="line","w-0 border-[1.5px] border-dashed bg-transparent":r==="dashed","my-0.5":v&&r==="dashed"}),style:{"--color-bg":T,"--color-border":T}}),l.jsxs("div",{className:Ie("flex flex-1 justify-between leading-none",v?"items-end":"items-center"),children:[l.jsxs("div",{className:"grid gap-1.5",children:[v?y:null,l.jsx("span",{className:"text-muted-foreground",children:w?.label||x.name})]}),x.value&&l.jsx("span",{className:"text-foreground font-mono font-medium tabular-nums",children:x.value.toLocaleString()})]})]})},x.dataKey)})})]})}function sme(e,t,n){if(typeof t!="object"||t===null)return;const r="payload"in t&&typeof t.payload=="object"&&t.payload!==null?t.payload:void 0;let i=n;return n in t&&typeof t[n]=="string"?i=t[n]:r&&n in r&&typeof r[n]=="string"&&(i=r[n]),i in e?e[i]:e[n]}function IGt({suite:e,viewMode:t,selectedRunDetails:n,isEditMode:r,onRerun:i,onDelete:a,onCancelRun:s,onDeleteRun:o,onViewModeChange:u,connectedServerNames:c,rerunningSuiteId:d,cancellingRunId:f,deletingSuiteId:p,deletingRunId:m,showRunSummarySidebar:y,setShowRunSummarySidebar:v,runsViewMode:x="runs",runs:_=[],allIterations:S=[],aggregate:w=null,testCases:T=[],availableModels:N=[],onUpdateModels:E}){const[A,I]=b.useState(!1),[M,$]=b.useState(e.name),[O,R]=b.useState(!1),U=_n("testSuites:updateTestSuite"),z=b.useMemo(()=>{if(!T||T.length===0)return[];const ee=new Map;return T.forEach(le=>{le.models&&Array.isArray(le.models)&&le.models.forEach(te=>{const Z=`${te.provider}:${te.model}`;if(!ee.has(Z)){const ne=N.find(J=>J.id===te.model);ee.set(Z,{model:te.model,provider:te.provider,displayName:ne?.name||te.model})}})}),Array.from(ee.values())},[T,N]),F=b.useMemo(()=>{const ee=new Map;return N.forEach(le=>{const te=le.provider;ee.has(te)||ee.set(te,[]),ee.get(te).push(le)}),ee},[N]),D=b.useMemo(()=>Array.from(F.entries()).filter(([ee,le])=>le.some(te=>_r(te.id))).sort(([ee],[le])=>ee.localeCompare(le)),[F]),W=b.useMemo(()=>Array.from(F.entries()).filter(([ee,le])=>le.some(te=>!_r(te.id))).sort(([ee],[le])=>ee.localeCompare(le)),[F]),q=b.useCallback(async ee=>{if(!E)return;if(z.some(Z=>Z.model===ee.id)){R(!1);return}const le={model:ee.id,provider:ee.provider,displayName:ee.name},te=[...z,le];await E(te),R(!1)},[z,E]),X=b.useCallback(async ee=>{if(!E)return;const le=z.filter(te=>te.model!==ee);await E(le)},[z,E]),L=b.useMemo(()=>{if(!_||!S||_.length===0)return null;const ee=_.filter(he=>he.isActive!==!1);if(ee.length===0)return null;const le=new Set(ee.map(he=>he._id)),te=S.filter(he=>he.suiteRunId&&le.has(he.suiteRunId));if(te.length===0)return null;const Z=te.map(he=>Fl(he)),ne=Z.filter(he=>he==="passed").length,J=Z.filter(he=>he==="failed").length,se=ne+J;if(se===0)return null;const ie=[];return ne>0&&ie.push({name:"passed",value:ne,fill:"hsl(142.1 76.2% 36.3%)"}),J>0&&ie.push({name:"failed",value:J,fill:"hsl(0 84.2% 60.2%)"}),{donutData:ie,total:se,accuracy:Math.round(ne/se*100)}},[_,S]);b.useEffect(()=>{$(e.name)},[e.name]);const Y=b.useCallback(()=>{I(!0),$(e.name)},[e.name]),G=b.useCallback(async()=>{if(I(!1),M&&M.trim()&&M!==e.name)try{await U({suiteId:e._id,name:M.trim()}),Pe.success("Suite name updated")}catch(ee){Pe.error("Failed to update suite name"),console.error("Failed to update suite name:",ee),$(e.name)}else $(e.name)},[M,e.name,e._id,U]),P=b.useCallback(ee=>{ee.key==="Enter"?G():ee.key==="Escape"&&(I(!1),$(e.name))},[G,e.name]),K=(e.environment?.servers||[]).filter(ee=>!c.has(ee)),Q=K.length===0,oe=d===e._id,re=p===e._id;if(r)return l.jsx("div",{className:"flex items-center justify-between gap-4 mb-2 px-6 pt-6 max-w-5xl mx-auto w-full",children:A?l.jsx("input",{type:"text",value:M,onChange:ee=>$(ee.target.value),onBlur:G,onKeyDown:P,autoFocus:!0,className:"px-4 py-2 text-xl font-bold border border-input rounded-lg focus:outline-none focus:ring-2 focus:ring-ring bg-background"}):l.jsx(Ee,{variant:"ghost",onClick:Y,className:"px-4 py-2 h-auto text-xl font-bold hover:bg-accent/50 -ml-4 rounded-lg",children:e.name})});if(t==="run-detail"&&n){const ee=f===n._id,le=n.status==="running"||n.status==="pending",te=oe||le;return l.jsxs("div",{className:"flex items-center justify-between gap-4 mb-4",children:[l.jsxs("h2",{className:"text-lg font-semibold",children:["Run ",r2(n._id)]}),l.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[l.jsxs(Ee,{variant:"outline",size:"sm",onClick:()=>v(!y),className:"gap-2",children:[l.jsx(T1e,{className:"h-4 w-4"}),"View run summary"]}),le?l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:"outline",size:"sm",onClick:()=>s(n._id),disabled:ee,className:"gap-2",children:ee?l.jsxs(l.Fragment,{children:[l.jsx(Pn,{className:"h-4 w-4 animate-spin"}),"Cancelling..."]}):l.jsxs(l.Fragment,{children:[l.jsx(Yn,{className:"h-4 w-4"}),"Cancel run"]})})}),l.jsx(zt,{children:"Cancel the current evaluation run"})]}):l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsxs(Ee,{variant:"outline",size:"sm",onClick:()=>i(e),disabled:!Q||te,className:"gap-2",children:[l.jsx(bU,{className:`h-4 w-4 ${te?"animate-spin":""}`}),te?"Running...":"Rerun"]})})}),l.jsx(zt,{children:Q?"Run all tests":`Connect the following servers: ${K.join(", ")}`})]}),l.jsxs(Ee,{variant:"outline",size:"sm",onClick:()=>o(n._id),disabled:m===n._id,className:"gap-2",children:[l.jsx(Ll,{className:"h-4 w-4"}),m===n._id?"Deleting...":"Delete"]}),l.jsx(Ee,{variant:"outline",size:"icon",onClick:()=>u("overview"),children:l.jsx(Yn,{className:"h-4 w-4"})})]})]})}return t==="test-detail"||t==="test-edit"?null:l.jsxs("div",{className:"flex items-center justify-between gap-4 mb-4",children:[l.jsxs("div",{className:"flex items-center gap-4 flex-1",children:[A?l.jsx("input",{type:"text",value:M,onChange:ee=>$(ee.target.value),onBlur:G,onKeyDown:P,autoFocus:!0,className:"px-3 py-2 text-lg font-semibold border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-ring"}):l.jsx(Ee,{variant:"ghost",onClick:Y,className:"px-3 py-2 h-auto text-lg font-semibold hover:bg-accent",children:e.name}),L&&L.donutData.length>0&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-sm font-medium text-foreground",children:"Accuracy:"}),l.jsx(Ud,{config:{passed:{label:"Passed",color:"hsl(142.1 76.2% 36.3%)"},failed:{label:"Failed",color:"hsl(0 84.2% 60.2%)"},pending:{label:"Pending",color:"hsl(45.4 93.4% 47.5%)"},cancelled:{label:"Cancelled",color:"hsl(240 3.7% 15.9%)"}},className:"h-12 w-12",children:l.jsxs(u5e,{children:[l.jsx(Fd,{content:l.jsx(AZ,{hideLabel:!0})}),l.jsx(Wc,{data:L.donutData,dataKey:"value",nameKey:"name",innerRadius:15,outerRadius:22,strokeWidth:1,children:l.jsx(da,{content:({viewBox:ee})=>{if(ee&&"cx"in ee&&"cy"in ee)return l.jsx("text",{x:ee.cx,y:ee.cy,textAnchor:"middle",dominantBaseline:"middle",children:l.jsxs("tspan",{x:ee.cx,y:ee.cy,className:"fill-foreground text-[10px] font-bold",children:[L.accuracy,"%"]})})}})})]})})]})]}),l.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[E&&l.jsxs(Ic,{open:O,onOpenChange:R,children:[l.jsx(jc,{asChild:!0,children:l.jsxs(Ee,{size:"sm",variant:"outline",className:`gap-1.5 ${z.length===0?"text-destructive border-destructive/50":""}`,children:["Models",l.jsx(Cn,{variant:z.length===0?"destructive":"secondary",className:"px-1.5 py-0 text-[10px] min-w-[18px] justify-center",children:z.length})]})}),l.jsxs(Oc,{align:"end",side:"bottom",sideOffset:4,className:"w-[280px]",children:[z.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"px-2 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground",children:"Active Models"}),z.map(ee=>l.jsxs("div",{className:"flex items-center justify-between px-2 py-1.5 text-sm",children:[l.jsx("span",{className:"truncate",children:ee.displayName}),l.jsx("button",{onClick:()=>X(ee.model),className:"ml-2 p-0.5 text-muted-foreground hover:text-destructive rounded",title:"Remove model",children:l.jsx(Yn,{className:"h-3.5 w-3.5"})})]},ee.model)),l.jsx("div",{className:"my-1 h-px bg-border"})]}),D.length>0&&l.jsx("div",{className:"px-2 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground",children:"MCPJam Free Models"}),D.map(([ee,le])=>{const te=le.filter(ne=>_r(ne.id)),Z=te.length;return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:ee}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:ee}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[Z," model",Z!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[200px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:te.map(ne=>{const J=z.some(se=>se.model===ne.id);return l.jsxs(Oi,{onSelect:()=>q(ne),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:J,children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:ne.name})}),J&&l.jsx("div",{className:"ml-auto w-2 h-2 bg-primary rounded-full"})]},ne.id)})})]},`free-${ee}`)}),D.length>0&&W.length>0&&l.jsx("div",{className:"my-1 h-px bg-muted/50"}),W.length>0&&l.jsx("div",{className:"px-2 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground",children:"Your Providers"}),W.map(([ee,le])=>{const te=le.filter(ne=>!_r(ne.id)),Z=te.length;return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:ee}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:ee}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[Z," model",Z!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[200px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:te.map(ne=>{const J=z.some(se=>se.model===ne.id);return l.jsxs(Oi,{onSelect:()=>q(ne),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:J,children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:ne.name})}),J&&l.jsx("div",{className:"ml-auto w-2 h-2 bg-primary rounded-full"})]},ne.id)})})]},`user-${ee}`)})]})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsxs(Ee,{variant:"outline",size:"sm",onClick:()=>i(e),disabled:!Q||oe,className:"gap-2",children:[l.jsx(bU,{className:`h-4 w-4 ${oe?"animate-spin":""}`}),"Run"]})})}),l.jsx(zt,{children:Q?"Run all tests":`Connect the following servers: ${K.join(", ")}`})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsxs(Ee,{variant:"outline",size:"sm",onClick:()=>a(e),disabled:re,className:"gap-2",children:[l.jsx(Ll,{className:"h-4 w-4"}),re?"Deleting...":"Delete"]})}),l.jsx(zt,{children:"Delete this test suite"})]})]})]})}function IZ({data:e,isLoading:t=!1,title:n,height:r="h-32",onClick:i,showLabel:a=!1}){return t?l.jsx(nI,{className:`${r} w-full`}):e.length===0?l.jsx("p",{className:"text-xs text-muted-foreground",children:"No completed runs yet."}):l.jsx(Ud,{config:{passRate:{label:"Accuracy",color:"var(--chart-1)"}},className:`aspect-auto ${r} w-full`,children:l.jsxs(TGt,{data:e,width:void 0,height:void 0,onClick:i?s=>{s?.activePayload?.[0]?.payload?.runId&&i(s.activePayload[0].payload.runId)}:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"runIdDisplay",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:a?11:12},label:a?{value:"Run",position:"insideBottom",offset:-5,fontSize:11}:void 0}),l.jsx(Nu,{domain:[0,100],tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:a?11:12},tickFormatter:s=>`${s}%`}),l.jsx(Fd,{cursor:!1,content:l.jsx(AZ,{})}),l.jsx(mh,{type:"monotone",dataKey:"passRate",stroke:"var(--color-passRate)",fill:"var(--color-passRate)",fillOpacity:.15,strokeWidth:2,isAnimationActive:!1,dot:e.length>1?i?{cursor:"pointer"}:!0:!1,activeDot:i?{cursor:"pointer",r:6}:void 0})]})})}function jGt({suite:e,runs:t,runsLoading:n,allIterations:r,runTrendData:i,modelStats:a,onRunClick:s,onDirectDeleteRun:o,runsViewMode:u,onViewModeChange:c}){const[d,f]=b.useState(new Set),[p,m]=b.useState(!1),[y,v]=b.useState(null),x=b.useCallback(T=>{f(N=>{const E=new Set(N);return E.has(T)?E.delete(T):E.add(T),E})},[]),_=b.useCallback(()=>{f(T=>T.size===t.length?new Set:new Set(t.map(N=>N._id)))},[t]),S=b.useCallback(()=>{const T=Array.from(d);T.length!==0&&(v("batch"),Promise.all(T.map(N=>o(N))).then(()=>{f(new Set),m(!1),Pe.success(`Deleted ${T.length} run(s) successfully`)}).catch(N=>{console.error("Failed to delete runs:",N),Pe.error("Failed to delete some runs")}).finally(()=>{v(null),m(!1)}))},[d,o]),w={passRate:{label:"Pass Rate",color:"var(--chart-1)"}};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Accuracy"})}),l.jsx("div",{className:"px-4 pb-4",children:l.jsx(IZ,{data:i,isLoading:n,height:"h-32",onClick:s})})]}),l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Performance by model"})}),l.jsx("div",{className:"px-4 pb-4",children:a.length>0?l.jsx(Ud,{config:w,className:"aspect-auto h-32 w-full",children:l.jsxs(Xv,{data:a,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"model",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:11},interval:0,height:40,tickFormatter:T=>T.length>15?T.substring(0,12)+"...":T}),l.jsx(Nu,{domain:[0,100],tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:T=>`${T}%`}),l.jsx(Fd,{cursor:!1,content:({active:T,payload:N})=>{if(!T||!N||N.length===0)return null;const E=N[0].payload;return l.jsx("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:l.jsxs("div",{className:"grid gap-2",children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"text-xs font-semibold",children:E.model}),l.jsxs("span",{className:"text-xs text-muted-foreground mt-0.5",children:[E.passed," passed · ",E.failed," failed"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"h-2 w-2 rounded-full",style:{backgroundColor:"var(--color-passRate)"}}),l.jsxs("span",{className:"text-sm font-semibold",children:[E.passRate,"%"]})]})]})})}}),l.jsx(Ml,{dataKey:"passRate",fill:"var(--color-passRate)",radius:[4,4,0,0],isAnimationActive:!1,minPointSize:8})]})}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"No model data available."})})]})]}),l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground flex flex-col max-h-[600px]",children:[d.size>0?l.jsxs("div",{className:"border-b px-4 py-2 shrink-0 bg-muted/50 flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(Hw,{checked:d.size===t.length,onCheckedChange:_,"aria-label":"Select all runs"}),l.jsxs("span",{className:"text-xs font-medium",children:[d.size," ",d.size===1?"item":"items"," selected"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ee,{variant:"outline",size:"sm",onClick:()=>f(new Set),children:"Cancel"}),l.jsx(Ee,{variant:"destructive",size:"sm",onClick:()=>m(!0),disabled:y!==null,children:"Delete"})]})]}):l.jsxs("div",{className:"border-b px-4 py-2 shrink-0 flex items-center justify-between",children:[l.jsx("div",{children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Click on a run to view its test breakdown and results."})}),l.jsxs("select",{value:u,onChange:T=>c(T.target.value),className:"text-xs border rounded px-2 py-1 bg-background",children:[l.jsx("option",{value:"runs",children:"Runs"}),l.jsx("option",{value:"test-cases",children:"Test Cases"})]})]}),t.length>0&&l.jsxs("div",{className:"flex items-center gap-6 w-full px-4 py-1.5 bg-muted/30 border-b text-xs font-medium text-muted-foreground",children:[l.jsx("div",{className:"w-4"}),l.jsx("div",{className:"min-w-[120px]",children:"Run ID"}),l.jsx("div",{className:"min-w-[140px]",children:"Start time"}),l.jsx("div",{className:"min-w-[60px]",children:"Duration"}),l.jsx("div",{className:"min-w-[60px] text-right",children:"Passed"}),l.jsx("div",{className:"min-w-[60px] text-right",children:"Failed"}),l.jsx("div",{className:"min-w-[70px] text-right",children:"Accuracy"}),l.jsx("div",{className:"min-w-[70px] text-right",children:"Tokens"})]}),l.jsx("div",{className:"divide-y overflow-y-auto",children:t.length===0?l.jsx("div",{className:"px-4 py-12 text-center text-sm text-muted-foreground",children:"No runs found."}):t.map(T=>{const N=r.filter(G=>G.suiteRunId===T._id),E=N.map(G=>Fl(G)),A=E.filter(G=>G==="passed").length,I=E.filter(G=>G==="failed").length,M=A+I,$=N.reduce((G,P)=>G+(P.tokensUsed||0),0),O=A>0?A:T.summary?.passed??0,R=I>0?I:T.summary?.failed??0,U=M>0?M:T.summary?.total??0,z=U>0?Math.round(O/U*100):null,F=OGt(T.completedAt??T.createdAt),D=T.completedAt&&T.createdAt?ome(T.completedAt-T.createdAt):T.createdAt&&T.status==="running"?ome(Date.now()-T.createdAt):"—",W=T.isActive===!1,q=T.result||(T.status==="completed"&&z!==null?z>=(T.passCriteria?.minimumPassRate??100)?"passed":"failed":T.status==="cancelled"?"cancelled":"pending"),X=SK(q),L=d.has(T._id),Y=l.jsxs("div",{className:"flex items-center gap-6 w-full",children:[l.jsx("div",{className:"pl-3",children:l.jsx(Hw,{checked:L,onCheckedChange:()=>x(T._id),onClick:G=>G.stopPropagation(),"aria-label":`Select run ${r2(T._id)}`})}),l.jsxs("button",{onClick:()=>s(T._id),className:"flex flex-1 items-center gap-6 py-2.5 pr-3 text-left transition-colors hover:bg-muted/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:[l.jsxs("span",{className:"text-xs font-medium min-w-[120px]",children:["Run ",r2(T._id)]}),l.jsx("span",{className:"text-xs text-muted-foreground min-w-[140px]",children:F}),l.jsx("span",{className:"text-xs text-muted-foreground font-mono min-w-[60px]",children:D}),l.jsx("span",{className:"text-xs font-mono text-muted-foreground min-w-[60px] text-right",children:O}),l.jsx("span",{className:"text-xs font-mono text-muted-foreground min-w-[60px] text-right",children:R}),l.jsx("span",{className:"text-xs font-mono text-muted-foreground min-w-[70px] text-right",children:z!==null?`${z}%`:"—"}),l.jsx("span",{className:"text-xs font-mono text-muted-foreground min-w-[70px] text-right",children:$>0?$.toLocaleString():"—"})]})]});return l.jsxs("div",{className:Ie("relative overflow-hidden",W&&"opacity-50"),children:[l.jsx("div",{className:`absolute left-0 top-0 h-full w-1 ${X}`}),W?l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:Y}),l.jsx(zt,{children:l.jsx("p",{className:"text-xs",children:"Run is inactive since test cases were updated"})})]}):Y]},T._id)})})]}),l.jsx(si,{open:p,onOpenChange:m,children:l.jsxs(oi,{children:[l.jsxs(vi,{children:[l.jsxs(yi,{className:"flex items-center gap-2",children:[l.jsx(Ll,{className:"h-5 w-5 text-destructive"}),"Delete ",d.size," Run",d.size!==1?"s":""]}),l.jsxs(us,{children:["Are you sure you want to delete ",d.size," run",d.size!==1?"s":"","?",l.jsx("br",{}),l.jsx("br",{}),"This will permanently delete all iterations and results associated with ",d.size===1?"this run":"these runs",". This action cannot be undone."]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:()=>m(!1),disabled:y!==null,children:"Cancel"}),l.jsx(Ee,{variant:"destructive",onClick:S,disabled:y!==null,children:y?"Deleting...":"Delete"})]})]})})]})}function OGt(e){return e?new Date(e).toLocaleString():"—"}function ome(e){if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;if(n<60)return r?`${n}m ${r}s`:`${n}m`;const i=Math.floor(n/60),a=n%60;return a?`${i}h ${a}m`:`${i}h`}function RGt({run:e,variant:t="compact"}){const n=e.passCriteria?.minimumPassRate??100,r=e.result??"pending",i=e.status??"pending",s=(e.summary?.passRate??0)*100,o=r==="passed";return i==="running"||i==="pending"?null:t==="compact"?l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsxs(Cn,{variant:"outline",className:o?"gap-1 bg-success/50 text-success-foreground border-success/50 hover:bg-success/70":"gap-1 bg-destructive/50 text-destructive-foreground border-destructive/50 hover:bg-destructive/70",children:[o?l.jsx(ko,{className:"h-3 w-3"}):l.jsx(qd,{className:"h-3 w-3"}),o?"Passed":"Failed"]})}),l.jsx(zt,{className:"max-w-xs",children:l.jsxs("div",{className:"space-y-1 text-xs",children:[l.jsx("div",{className:"font-medium text-white",children:o?"✓ Suite Passed":"✗ Suite Failed"}),l.jsxs("div",{className:"text-white",children:["Required: ",n,"% Accuracy"]})]})})]}):l.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-4",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[o?l.jsx(ko,{className:"h-5 w-5 text-success"}):l.jsx(qd,{className:"h-5 w-5 text-destructive"}),l.jsx("h3",{className:"text-sm font-medium",children:o?"Suite Passed":"Suite Failed"})]}),l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-muted-foreground",children:"Criteria:"}),l.jsxs(Cn,{variant:"outline",className:"text-xs",children:["Min ",n,"% Accuracy"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-muted-foreground",children:"Accuracy:"}),l.jsxs("span",{className:"font-mono",children:[s.toFixed(1),"%"]}),l.jsxs("span",{className:"text-muted-foreground",children:["(threshold: ",n,"%)"]})]}),!o&&s<n&&l.jsxs("div",{className:"mt-2 rounded border-l-2 border-destructive bg-destructive/10 p-2 text-xs",children:["Accuracy ",s.toFixed(1),"% below threshold ",n,"%"]})]})]})}const d5e=(e,t)=>{switch(e){case"anthropic":return sPe;case"openai":return oPe;case"deepseek":return lPe;case"google":return uPe;case"mistral":return dPe;case"ollama":return t==="dark"||t==="system"&&typeof document<"u"&&document.documentElement.classList.contains("dark")?jI:II;case"meta":case"meta-llama":return cPe;case"x-ai":case"xai":return t==="dark"||t==="system"&&typeof document<"u"&&document.documentElement.classList.contains("dark")?RI:OI;case"litellm":return fPe;case"openrouter":return pPe;case"moonshotai":return t==="dark"||t==="system"&&typeof document<"u"&&document.documentElement.classList.contains("dark")?$I:PI;case"z-ai":return hPe;default:return null}};function PGt({trace:e,modelProvider:t="openai",toolsMetadata:n={},toolServerMap:r={}}){const[i,a]=b.useState("formatted");if(!e)return l.jsx("div",{className:"text-xs text-muted-foreground",children:"No trace data available"});let s=[];if(Array.isArray(e)?s=e:typeof e=="object"&&"messages"in e&&Array.isArray(e.messages)?s=e.messages:typeof e=="object"&&"role"in e&&(s=[e]),s.length===0)return l.jsx("div",{className:"text-xs text-muted-foreground",children:"No messages in trace"});const o=[];for(let u=0;u<s.length;u++){const c=s[u];if(c.role==="assistant"){const d=s[u+1];d&&d.role==="tool"?(o.push({type:"tool-group",messages:[c,d]}),u++):o.push({type:"assistant",messages:[c]})}else c.role==="user"?o.push({type:"user",messages:[c]}):o.push({type:"tool-group",messages:[c]})}return l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"flex items-center justify-between border-b border-border/40 pb-2",children:[l.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:[s.length," message",s.length!==1?"s":""]}),l.jsxs("div",{className:"flex items-center gap-1 rounded-md border border-border/40 bg-background p-0.5",children:[l.jsxs("button",{type:"button",onClick:()=>a("formatted"),className:`inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition-colors ${i==="formatted"?"bg-primary/10 text-foreground font-medium":"text-muted-foreground hover:text-foreground"}`,title:"Formatted view",children:[l.jsx(kw,{className:"h-3 w-3"}),"Formatted"]}),l.jsxs("button",{type:"button",onClick:()=>a("raw"),className:`inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition-colors ${i==="raw"?"bg-primary/10 text-foreground font-medium":"text-muted-foreground hover:text-foreground"}`,title:"Raw JSON view",children:[l.jsx(N1e,{className:"h-3 w-3"}),"Raw"]})]})]}),i==="raw"?l.jsx(zn,{viewOnly:!0,value:e}):l.jsx("div",{className:"space-y-6",children:o.map((u,c)=>u.type==="user"?l.jsx(lme,{message:u.messages[0],modelProvider:t},c):u.type==="tool-group"?l.jsx($Gt,{messages:u.messages,modelProvider:t,toolsMetadata:n,toolServerMap:r},c):l.jsx(lme,{message:u.messages[0],modelProvider:t},c))})]})}function lme({message:e,modelProvider:t}){const n=eo(s=>s.themeMode),r=d5e(t,n);if(e.role==="user"){const s=typeof e.content=="string"?e.content:e.content?.[0]?.text||"";return l.jsx("div",{className:"flex justify-end",children:l.jsx("div",{className:"max-w-3xl rounded-lg bg-primary px-4 py-3 text-sm text-primary-foreground shadow-sm",children:l.jsx("div",{className:"whitespace-pre-wrap break-words leading-6",children:s})})})}const a=Array.isArray(e.content)?e.content:[];return l.jsxs("article",{className:"flex gap-4 w-full",children:[l.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border/40 bg-muted/40",children:r?l.jsx("img",{src:r,alt:"Model logo",className:"h-4 w-4 object-contain"}):l.jsx(Bm,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx("div",{className:"flex-1 min-w-0 space-y-3 text-sm leading-6",children:a.map((s,o)=>l.jsx(f5e,{part:s},o))})]})}function $Gt({messages:e,modelProvider:t,toolsMetadata:n={},toolServerMap:r={}}){const i=eo(d=>d.themeMode),a=d5e(t,i),s=[],o=[],u=[];for(const d of e){const f=Array.isArray(d.content)?d.content:[];for(const p of f)p.type==="tool-call"?s.push(p):p.type==="tool-result"?o.push(p):u.push(p)}const c=s.map(d=>{const f=o.find(p=>p.toolCallId===d.toolCallId);return{toolCall:d,toolResult:f}});return l.jsxs("article",{className:"flex gap-4 w-full",children:[l.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border/40 bg-muted/40",children:a?l.jsx("img",{src:a,alt:"Model logo",className:"h-4 w-4 object-contain"}):l.jsx(Bm,{className:"h-4 w-4 text-muted-foreground"})}),l.jsxs("div",{className:"flex-1 min-w-0 space-y-3 text-sm leading-6",children:[u.map((d,f)=>l.jsx(f5e,{part:d},`other-${f}`)),c.map((d,f)=>l.jsx(MGt,{toolCall:d.toolCall,toolResult:d.toolResult,toolsMetadata:n,toolServerMap:r},`tool-${f}`))]})]})}function f5e({part:e}){return e.type==="text"&&e.text?l.jsx("div",{className:"text-sm whitespace-pre-wrap break-words text-foreground",children:e.text}):e.type==="reasoning"?e.text?l.jsxs("div",{className:"rounded-lg border border-purple-500/20 bg-purple-500/5 p-3 text-xs",children:[l.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[l.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-purple-500/60"}),l.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-purple-700 dark:text-purple-400",children:"Reasoning"})]}),l.jsx("pre",{className:"whitespace-pre-wrap break-words text-muted-foreground leading-relaxed",children:e.text})]}):l.jsxs("div",{className:"rounded-lg border border-border/30 bg-muted/10 px-3 py-2 text-xs text-muted-foreground italic flex items-center gap-2",children:[l.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-purple-500/60 animate-pulse"}),"Model used internal reasoning (content not visible)"]}):l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/20 p-2",children:[l.jsxs("div",{className:"text-xs font-semibold text-muted-foreground mb-1",children:["Unknown part type: ",e.type]}),l.jsx(zn,{viewOnly:!0,value:e})]})}function MGt({toolCall:e,toolResult:t,toolsMetadata:n={},toolServerMap:r={}}){const[i,a]=b.useState(!1),o=eo(w=>w.themeMode)==="dark"?"h-3 w-3 filter invert":"h-3 w-3",u=e?.toolName||t?.toolName||"Unknown tool",c=e?.input!==void 0&&e?.input!==null,d=t?.output!==void 0&&t?.output!==null,f=t?.isError===!0,p=n[u],m=!!p?.["openai/outputTemplate"],y=!!p?.ui?.resourceUri,v=p?.ui?.resourceUri,x=JU(u,r),_=t?.output&&typeof t.output=="object"&&"type"in t.output&&"value"in t.output?t.output.value:t?.output;let S=_;if(d&&typeof t?.output=="object"&&t?.output!==null&&"content"in t.output&&Array.isArray(t.output.content)){const w=t.output.content.find(T=>T.type==="text");w?.text&&(S=w.text)}return l.jsxs("div",{className:"rounded-lg border border-border/50 bg-background/70 text-xs",children:[l.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wide text-muted-foreground cursor-pointer",onClick:()=>a(w=>!w),"aria-expanded":i,children:[l.jsx("span",{className:"inline-flex items-center gap-2 font-medium normal-case text-foreground",children:l.jsxs("span",{className:"inline-flex items-center gap-2",children:[l.jsx("img",{src:"/mcp.svg",alt:"",role:"presentation","aria-hidden":"true",className:o}),l.jsx("span",{className:"font-mono text-xs tracking-tight text-muted-foreground/80",children:u})]})}),l.jsxs("span",{className:"inline-flex items-center gap-2 text-muted-foreground",children:[l.jsx("span",{className:"inline-flex h-5 w-5 items-center justify-center",children:f?l.jsx(wo,{className:"h-4 w-4 text-destructive"}):t?l.jsx(ko,{className:"h-4 w-4 text-success"}):l.jsx(ko,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx(Wr,{className:`h-4 w-4 transition-transform duration-150 ${i?"rotate-180":""}`})]})]}),i&&l.jsxs("div",{className:"space-y-4 border-t border-border/40 px-3 py-3",children:[c&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Input"}),l.jsx(zn,{viewOnly:!0,value:e.input})]}),d&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:f?"Error":"Result"}),typeof S=="string"?l.jsx("pre",{className:`whitespace-pre-wrap break-words rounded-md border p-2 text-[11px] leading-relaxed ${f?"border-destructive/40 bg-destructive/10 text-destructive":"border-border/30 bg-muted/20"}`,children:S}):l.jsx("div",{className:f?"[&_.rounded-lg]:border-destructive/40 [&_.rounded-lg]:bg-destructive/10 [&_.rounded-lg]:text-destructive":"",children:l.jsx(zn,{viewOnly:!0,value:S})})]}),!c&&!d&&l.jsx("div",{className:"text-muted-foreground/70",children:"No tool details available."})]}),y&&x&&v&&d&&!f&&l.jsx(yK,{serverId:x,toolCallId:e?.toolCallId??`evals-${u}-${Date.now()}`,toolName:u,toolState:"output-available",toolInput:e?.input,toolOutput:_,resourceUri:v,toolMetadata:p,onSendFollowUp:void 0,onCallTool:void 0}),m&&!y&&x&&d&&!f&&l.jsx(vK,{serverId:x,toolCallId:e?.toolCallId,toolName:u,toolState:"output-available",toolInput:e?.input??null,toolOutput:_??null,toolMetadata:p,onSendFollowUp:void 0,onCallTool:void 0})]})}function jZ({iteration:e,testCase:t,serverNames:n=[]}){const r=$9("testSuites:getTestIterationBlob"),[i,a]=b.useState(null),[s,o]=b.useState(!1),[u,c]=b.useState(null),[d,f]=b.useState("formatted"),[p,m]=b.useState({}),[y,v]=b.useState({}),[x,_]=b.useState({});b.useEffect(()=>{let O=!1;async function R(){if(!e.blob){a(null),o(!1),c(null);return}o(!0),c(null);try{const U=await r({blobId:e.blob});O||a(U)}catch(U){O||(c(U?.message||"Failed to load blob"),console.error("Blob load error:",U))}finally{O||o(!1)}}return R(),()=>{O=!0}},[e.blob,r]),b.useEffect(()=>{(async()=>{if(n.length===0){m({}),v({}),_({});return}try{const R={},U={},z={};await Promise.all(n.map(async F=>{try{const D=await _g({serverId:F});if(D.tools)for(const q of D.tools)R[q.name]={name:q.name,inputSchema:q.inputSchema},z[q.name]=F;const W=D.toolsMetadata??{};for(const[q,X]of Object.entries(W))U[q]=X}catch(D){console.warn(`Failed to fetch tools for server ${F}:`,D)}})),_(R),m(U),v(z)}catch{m({}),v({}),_({})}})()},[n]);const S=e.testCaseSnapshot?.expectedToolCalls||t?.expectedToolCalls||[],w=e.actualToolCalls||[],T=O=>Array.isArray(O)?O.join(" | "):typeof O=="string"?O:String(O),N=(O,R)=>{const U=x[O];return U?.inputSchema?.properties?U.inputSchema.properties[R]:null},E=(O,R)=>{const U=Object.entries(O);return U.length===0?l.jsx("span",{className:"text-muted-foreground italic",children:"No arguments"}):l.jsx("div",{className:"space-y-1",children:U.map(([z,F])=>{const D=R?N(R,z):null;return l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsxs("span",{className:"font-medium text-foreground",children:[z,":"]}),D?.type&&l.jsx("span",{className:"text-[10px] font-normal text-muted-foreground bg-background/50 px-1.5 py-0.5 rounded border border-border/40",children:T(D.type)})]}),l.jsx("span",{className:"font-mono text-muted-foreground",children:typeof F=="object"?JSON.stringify(F):String(F)})]},z)})})},I=(O=>{if(!O)return null;try{return JSON.parse(O)}catch{return null}})(e.errorDetails),[M,$]=b.useState(!1);return l.jsxs("div",{className:"space-y-4 py-2",children:[e.error&&l.jsxs("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 p-3 space-y-2",children:[l.jsx("div",{className:"text-xs font-semibold text-destructive uppercase tracking-wide",children:"Error"}),l.jsx("div",{className:"text-xs text-destructive whitespace-pre-wrap font-mono",children:e.error}),e.errorDetails&&l.jsxs(qR,{open:M,onOpenChange:$,children:[l.jsxs(HR,{className:"flex items-center gap-1.5 text-xs text-destructive hover:text-destructive/80 transition-colors",children:[l.jsx("span",{children:"More details"}),M?l.jsx(Wr,{className:"h-3 w-3"}):l.jsx(wr,{className:"h-3 w-3"})]}),l.jsx(VR,{className:"mt-2",children:l.jsx("div",{className:"rounded border border-destructive/30 bg-background/50 p-2",children:I?l.jsx(zn,{value:I,readOnly:!0,showToolbar:!1}):l.jsx("pre",{className:"text-xs font-mono text-destructive whitespace-pre-wrap overflow-x-auto",children:e.errorDetails})})})]})]}),(S.length>0||w.length>0)&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between border-b border-border/40 pb-2",children:[l.jsx("div",{className:"text-xs font-semibold",children:"Tool Calls"}),l.jsxs("div",{className:"flex items-center gap-1 rounded-md border border-border/40 bg-background p-0.5",children:[l.jsxs("button",{type:"button",onClick:()=>f("formatted"),className:`inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition-colors ${d==="formatted"?"bg-primary/10 text-foreground font-medium":"text-muted-foreground hover:text-foreground"}`,title:"Formatted view",children:[l.jsx(kw,{className:"h-3 w-3"}),"Formatted"]}),l.jsxs("button",{type:"button",onClick:()=>f("raw"),className:`inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition-colors ${d==="raw"?"bg-primary/10 text-foreground font-medium":"text-muted-foreground hover:text-foreground"}`,title:"Raw JSON view",children:[l.jsx(N1e,{className:"h-3 w-3"}),"Raw"]})]})]}),d==="raw"?l.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/10 p-3 space-y-2",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Expected"}),S.length===0?l.jsx("div",{className:"text-xs text-muted-foreground italic",children:"No expected tool calls"}):l.jsx("pre",{className:"text-xs font-mono bg-background/50 rounded p-2 overflow-x-auto",children:JSON.stringify(S,null,2)})]}),l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/10 p-3 space-y-2",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Actual"}),w.length===0?l.jsx("div",{className:"text-xs text-muted-foreground italic",children:"No tool calls made"}):l.jsx("pre",{className:"text-xs font-mono bg-background/50 rounded p-2 overflow-x-auto",children:JSON.stringify(w,null,2)})]})]}):l.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/10 p-2 space-y-2",children:[l.jsx("div",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wide",children:"Expected"}),S.length===0?l.jsx("div",{className:"text-xs text-muted-foreground italic",children:"No expected tool calls"}):l.jsx("div",{className:"space-y-1.5",children:S.map((O,R)=>l.jsxs("div",{className:"rounded border border-border/30 bg-background/50 p-1.5 space-y-1",children:[l.jsx("div",{className:"font-mono text-xs font-medium",children:O.toolName}),Object.keys(O.arguments||{}).length>0&&l.jsx("div",{className:"text-xs bg-muted/30 rounded p-1.5",children:E(O.arguments||{},O.toolName)})]},`expected-${R}`))})]}),l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/10 p-2 space-y-2",children:[l.jsx("div",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wide",children:"Actual"}),w.length===0?l.jsx("div",{className:"text-xs text-muted-foreground italic",children:"No tool calls made"}):l.jsx("div",{className:"space-y-1.5",children:w.map((O,R)=>l.jsxs("div",{className:"rounded border border-border/30 bg-background/50 p-1.5 space-y-1",children:[l.jsx("div",{className:"font-mono text-xs font-medium",children:O.toolName}),Object.keys(O.arguments||{}).length>0&&l.jsx("div",{className:"text-xs bg-muted/30 rounded p-1.5",children:E(O.arguments||{},O.toolName)})]},`actual-${R}`))})]})]})]}),e.blob&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:"text-xs font-semibold",children:"Trace"}),l.jsx("div",{className:"rounded-md bg-muted/20 p-3 max-h-[480px] overflow-y-auto",children:s?l.jsx("div",{className:"text-xs text-muted-foreground",children:"Loading trace"}):u?l.jsx("div",{className:"text-xs text-destructive",children:u}):l.jsx(PGt,{trace:i,modelProvider:t?.models[0]?.provider||e.testCaseSnapshot?.provider||"openai",toolsMetadata:p,toolServerMap:y})})]})]})}function DGt({selectedRunDetails:e,caseGroupsForSelectedRun:t,selectedRunChartData:n,runDetailSortBy:r,onSortChange:i,showRunSummarySidebar:a,setShowRunSummarySidebar:s,serverNames:o=[]}){const[u,c]=b.useState(null),d=b.useMemo(()=>{if(t.length===0)return e.summary??{passed:0,failed:0,total:0,passRate:0};const f=t.filter(v=>MI(v)).length,p=t.filter(v=>!MI(v)).length,m=t.length,y=m>0?f/m:0;return{passed:f,failed:p,total:m,passRate:y}},[t,e.summary]);return l.jsxs("div",{className:"relative",children:[l.jsx("div",{className:"rounded-lg border bg-background/80 px-3 py-2",children:l.jsxs("div",{className:"flex items-center gap-6",children:[l.jsxs("div",{className:"flex gap-6 flex-1",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"text-xs text-muted-foreground",children:"Accuracy"}),l.jsx("div",{className:"text-sm font-semibold",children:d.total>0?`${Math.round(d.passRate*100)}%`:"—"})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"text-xs text-muted-foreground",children:"Passed"}),l.jsx("div",{className:"text-sm font-semibold",children:d.passed.toLocaleString()})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"text-xs text-muted-foreground",children:"Failed"}),l.jsx("div",{className:"text-sm font-semibold",children:d.failed.toLocaleString()})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"text-xs text-muted-foreground",children:"Total"}),l.jsx("div",{className:"text-sm font-semibold",children:d.total.toLocaleString()})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"text-xs text-muted-foreground",children:"Duration"}),l.jsx("div",{className:"text-sm font-semibold",children:e.completedAt&&e.createdAt?p5e(e.completedAt-e.createdAt):"—"})]})]}),n.donutData.length>0&&l.jsx("div",{className:"flex items-center gap-2",children:l.jsx(Ud,{config:{passed:{label:"Passed",color:"hsl(142.1 76.2% 36.3%)"},failed:{label:"Failed",color:"hsl(0 84.2% 60.2%)"},pending:{label:"Pending",color:"hsl(45.4 93.4% 47.5%)"},cancelled:{label:"Cancelled",color:"hsl(240 3.7% 15.9%)"}},className:"h-12 w-12",children:l.jsxs(u5e,{children:[l.jsx(Fd,{content:l.jsx(AZ,{hideLabel:!0})}),l.jsx(Wc,{data:n.donutData,dataKey:"value",nameKey:"name",innerRadius:15,outerRadius:22,strokeWidth:1,children:l.jsx(da,{content:({viewBox:f})=>{if(f&&"cx"in f&&"cy"in f){const p=n.donutData.reduce((m,y)=>m+y.value,0);return l.jsxs("text",{x:f.cx,y:f.cy,textAnchor:"middle",dominantBaseline:"middle",children:[l.jsx("tspan",{x:f.cx,y:f.cy,className:"fill-foreground text-xs font-bold",children:p}),l.jsx("tspan",{x:f.cx,y:(f.cy||0)+8,className:"fill-muted-foreground text-[8px]",children:"Total"})]})}}})})]})})}),l.jsx("span",{className:"text-xs font-medium text-foreground capitalize",children:e.status}),l.jsx(RGt,{run:e,variant:"compact"})]})}),l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground mt-4",children:[l.jsxs("div",{className:"border-b px-4 py-2 shrink-0 flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("div",{className:"text-xs font-semibold",children:"All Iterations"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"All test iterations from this run"})]}),l.jsxs("select",{value:r,onChange:f=>i(f.target.value),className:"text-xs border rounded px-2 py-1 bg-background",children:[l.jsx("option",{value:"model",children:"Sort by Model"}),l.jsx("option",{value:"test",children:"Sort by Test"}),l.jsx("option",{value:"result",children:"Sort by Result"})]})]}),t.length>0&&l.jsxs("div",{className:"flex items-center gap-4 w-full px-4 py-1.5 bg-muted/30 border-b text-xs font-medium text-muted-foreground pl-7",children:[l.jsx("div",{className:"flex-1",children:"Test"}),l.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[l.jsx("div",{className:"min-w-[120px]",children:"Model"}),l.jsx("div",{className:"min-w-[50px]",children:"Tools"}),l.jsx("div",{className:"min-w-[60px]",children:"Tokens"}),l.jsx("div",{className:"min-w-[40px] text-right",children:"Duration"})]})]}),l.jsx("div",{className:"divide-y",children:t.length===0?l.jsx("div",{className:"px-4 py-12 text-center text-sm text-muted-foreground",children:"No test cases found for this run."}):t.map(f=>l.jsx(LGt,{iteration:f,isOpen:u===f._id,onToggle:()=>c(u===f._id?null:f._id),showModelInfo:!0,serverNames:o},f._id))})]}),a&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"fixed inset-0 bg-black/50 z-40 animate-in fade-in duration-200",onClick:()=>s(!1)}),l.jsxs("div",{className:"fixed right-0 top-0 bottom-0 w-[500px] bg-background border-l z-50 overflow-y-auto animate-in slide-in-from-right duration-300",children:[l.jsxs("div",{className:"sticky top-0 bg-background border-b px-4 py-3 flex items-center justify-between z-10",children:[l.jsx("div",{className:"text-sm font-semibold",children:"Run Summary"}),l.jsx(Ee,{variant:"ghost",size:"icon",onClick:()=>s(!1),children:l.jsx(Yn,{className:"h-4 w-4"})})]}),l.jsx("div",{className:"p-4 space-y-4",children:(n.durationData.length>0||n.tokensData.length>0||n.modelData.length>0)&&l.jsxs("div",{className:"space-y-4",children:[n.durationData.length>0&&l.jsxs("div",{className:"rounded-lg border bg-background/50 p-4",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-3",children:"Duration per Test"}),l.jsx(Ud,{config:{duration:{label:"Duration",color:"var(--chart-1)"}},className:"aspect-auto h-64 w-full",children:l.jsxs(Xv,{data:n.durationData,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"name",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:10,angle:-45,textAnchor:"end"},interval:0,height:80,tickFormatter:f=>f.length>20?f.substring(0,17)+"...":f}),l.jsx(Nu,{tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:f=>`${f.toFixed(1)}s`}),l.jsx(Fd,{cursor:!1,content:({active:f,payload:p})=>{if(!f||!p||p.length===0)return null;const m=p[0].payload;return l.jsxs("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:[l.jsx("div",{className:"text-xs font-semibold",children:m.name}),l.jsxs("div",{className:"text-sm font-medium mt-1",children:[m.durationSeconds.toFixed(2),"s"]})]})}}),l.jsx(Ml,{dataKey:"durationSeconds",fill:"var(--color-duration)",radius:[4,4,0,0],isAnimationActive:!1})]})})]}),n.tokensData.length>0&&l.jsxs("div",{className:"rounded-lg border bg-background/50 p-4",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-3",children:"Tokens per Test"}),l.jsx(Ud,{config:{tokens:{label:"Tokens",color:"var(--chart-2)"}},className:"aspect-auto h-64 w-full",children:l.jsxs(Xv,{data:n.tokensData,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"name",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:10,angle:-45,textAnchor:"end"},interval:0,height:80,tickFormatter:f=>f.length>20?f.substring(0,17)+"...":f}),l.jsx(Nu,{tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:f=>f.toLocaleString()}),l.jsx(Fd,{cursor:!1,content:({active:f,payload:p})=>{if(!f||!p||p.length===0)return null;const m=p[0].payload;return l.jsxs("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:[l.jsx("div",{className:"text-xs font-semibold",children:m.name}),l.jsxs("div",{className:"text-sm font-medium mt-1",children:[Math.round(m.tokens).toLocaleString()," ","tokens"]})]})}}),l.jsx(Ml,{dataKey:"tokens",fill:"var(--color-tokens)",radius:[4,4,0,0],isAnimationActive:!1})]})})]}),n.modelData.length>0&&l.jsxs("div",{className:"rounded-lg border bg-background/50 p-4",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-3",children:"Performance by model"}),l.jsx(Ud,{config:{passRate:{label:"Accuracy",color:"var(--chart-1)"}},className:"aspect-auto h-48 w-full",children:l.jsxs(Xv,{data:n.modelData,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"model",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:11},interval:0,height:40,tickFormatter:f=>f.length>15?f.substring(0,12)+"...":f}),l.jsx(Nu,{domain:[0,100],tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:f=>`${f}%`}),l.jsx(Fd,{cursor:!1,content:({active:f,payload:p})=>{if(!f||!p||p.length===0)return null;const m=p[0].payload;return l.jsx("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:l.jsxs("div",{className:"grid gap-2",children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"text-xs font-semibold",children:m.model}),l.jsxs("span",{className:"text-xs text-muted-foreground mt-0.5",children:[m.passed," passed · ",m.failed," ","failed"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"h-2 w-2 rounded-full",style:{backgroundColor:"var(--color-passRate)"}}),l.jsxs("span",{className:"text-sm font-semibold",children:[m.passRate,"%"]})]})]})})}}),l.jsx(Ml,{dataKey:"passRate",fill:"var(--color-passRate)",radius:[4,4,0,0],isAnimationActive:!1,minPointSize:8})]})})]})]})})]})]})]})}function LGt({iteration:e,isOpen:t,onToggle:n,showModelInfo:r=!1,serverNames:i=[]}){const a=e.startedAt??e.createdAt,s=e.updatedAt??e.createdAt,o=a&&s?Math.max(s-a,0):null,u=e.status==="pending"||e.status==="running",c=e.testCaseSnapshot,d=e.actualToolCalls||[],f=c?.model||"—",p=Fl(e);return l.jsxs("div",{className:`relative ${u?"opacity-60":""}`,children:[l.jsx("div",{className:`absolute left-0 top-0 h-full w-1 ${SK(p)}`}),l.jsxs("button",{onClick:n,className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 cursor-pointer hover:bg-muted/50",children:[l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3 pl-2",children:[l.jsx("div",{className:"text-muted-foreground shrink-0",children:t?l.jsx(Wr,{className:"h-3.5 w-3.5"}):l.jsx(wr,{className:"h-3.5 w-3.5"})}),l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[l.jsx("span",{className:"text-xs font-medium truncate",children:c?.title||"Iteration"}),c?.isNegativeTest&&l.jsx("span",{className:"text-[10px] text-orange-500 shrink-0",title:"Negative test",children:"NEG"})]})]}),l.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground shrink-0",children:[r&&l.jsx("div",{className:"min-w-[120px] text-left truncate",children:l.jsx("span",{className:"font-mono text-xs",children:f})}),l.jsx("div",{className:"min-w-[50px] text-center",children:l.jsx("span",{className:"font-mono",children:u?"—":d.length})}),l.jsx("div",{className:"min-w-[60px] text-center",children:l.jsx("span",{className:"font-mono",children:u?"—":Number(e.tokensUsed||0).toLocaleString()})}),l.jsx("div",{className:"font-mono min-w-[40px] text-right",children:u?"—":o!==null?p5e(o):"—"}),u&&l.jsx("div",{className:"w-3.5 flex items-center justify-center",children:l.jsx(Pn,{className:"h-3.5 w-3.5 animate-spin text-warning"})})]})]}),t?l.jsx("div",{className:"border-t bg-muted/20 px-4 pb-4 pt-3 pl-8",children:l.jsx(jZ,{iteration:e,testCase:null,serverNames:i})}):null]})}function p5e(e){if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;if(n<60)return r?`${n}m ${r}s`:`${n}m`;const i=Math.floor(n/60),a=n%60;return a?`${i}h ${a}m`:`${i}h`}function zGt({suite:e,testCases:t,onUpdate:n,availableModels:r}){const[i,a]=b.useState(!1),s=b.useMemo(()=>{if(!t||t.length===0)return[];const v=new Map;return t.forEach(x=>{x.models&&Array.isArray(x.models)&&x.models.forEach(_=>{const S=`${_.provider}:${_.model}`;if(!v.has(S)){const w=r.find(T=>T.id===_.model);v.set(S,{model:_.model,provider:_.provider,displayName:w?.name||_.model})}})}),Array.from(v.values())},[t,r]),[o,u]=b.useState(s);b.useEffect(()=>{u(s)},[s]);const c=async v=>{await n(v)},d=async v=>{const x=o.filter(_=>_.model!==v);u(x),await c(x)},f=async v=>{if(o.some(S=>S.model===v.id)){a(!1);return}const x={model:v.id,provider:v.provider,displayName:v.name},_=[...o,x];u(_),await c(_),a(!1)},p=b.useMemo(()=>{const v=new Map;return r.forEach(x=>{const _=x.provider;v.has(_)||v.set(_,[]),v.get(_).push(x)}),v},[r]),m=b.useMemo(()=>Array.from(p.entries()).filter(([v,x])=>x.some(_=>_r(_.id))).sort(([v],[x])=>v.localeCompare(x)),[p]),y=b.useMemo(()=>Array.from(p.entries()).filter(([v,x])=>x.some(_=>!_r(_.id))).sort(([v],[x])=>v.localeCompare(x)),[p]);return l.jsx("div",{className:"space-y-3",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"flex items-start justify-between gap-4",children:[l.jsxs("div",{className:"flex-1",children:[l.jsx("h2",{className:"text-base font-semibold text-foreground",children:"Models"}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Select at least one model to run the evaluation."})]}),l.jsxs(Ic,{open:i,onOpenChange:a,children:[l.jsx(jc,{asChild:!0,children:l.jsxs(Ee,{size:"sm",variant:"outline",className:"shrink-0",children:[l.jsx(_o,{className:"h-4 w-4 mr-2"}),"Add model"]})}),l.jsxs(Oc,{align:"end",side:"bottom",sideOffset:4,className:"w-[300px]",children:[m.length>0&&l.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"MCPJam Free Models"}),m.map(([v,x])=>{const _=x.filter(S=>_r(S.id));return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:v}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:v}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.length," model",_.length!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:_.map(S=>l.jsxs(Oi,{onSelect:()=>f(S),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:o.some(w=>w.model===S.id),children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:S.name})}),o.some(w=>w.model===S.id)&&l.jsx(Cn,{variant:"secondary",className:"text-xs",children:"Added"})]},S.id))})]},v)}),m.length>0&&y.length>0&&l.jsx("div",{className:"my-1 h-px bg-muted/50"}),y.length>0&&l.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"Your Providers"}),y.map(([v,x])=>{const _=x.filter(S=>!_r(S.id));return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:v}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:v}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.length," model",_.length!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:_.map(S=>l.jsxs(Oi,{onSelect:()=>f(S),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:o.some(w=>w.model===S.id),children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:S.name})}),o.some(w=>w.model===S.id)&&l.jsx(Cn,{variant:"secondary",className:"text-xs",children:"Added"})]},S.id))})]},v)})]})]})]}),o.length===0?l.jsxs(vx,{className:"p-6 text-center",children:[l.jsx("p",{className:"text-sm text-muted-foreground",children:"No models configured"}),l.jsxs(Ic,{open:i,onOpenChange:a,children:[l.jsx(jc,{asChild:!0,children:l.jsxs(Ee,{className:"mt-4",variant:"outline",children:[l.jsx(_o,{className:"h-4 w-4 mr-2"}),"Add your first model"]})}),l.jsxs(Oc,{align:"center",side:"bottom",sideOffset:4,className:"w-[300px]",children:[m.length>0&&l.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"MCPJam Free Models"}),m.map(([v,x])=>{const _=x.filter(S=>_r(S.id));return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:v}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:v}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.length," model",_.length!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:_.map(S=>l.jsxs(Oi,{onSelect:()=>f(S),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:o.some(w=>w.model===S.id),children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:S.name})}),o.some(w=>w.model===S.id)&&l.jsx(Cn,{variant:"secondary",className:"text-xs",children:"Added"})]},S.id))})]},v)}),m.length>0&&y.length>0&&l.jsx("div",{className:"my-1 h-px bg-muted/50"}),y.length>0&&l.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"Your Providers"}),y.map(([v,x])=>{const _=x.filter(S=>!_r(S.id));return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:v}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:v}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.length," model",_.length!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:_.map(S=>l.jsxs(Oi,{onSelect:()=>f(S),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:o.some(w=>w.model===S.id),children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:S.name})}),o.some(w=>w.model===S.id)&&l.jsx(Cn,{variant:"secondary",className:"text-xs",children:"Added"})]},S.id))})]},v)})]})]})]}):l.jsx("div",{className:"flex flex-wrap gap-2",children:o.map(v=>l.jsxs(Cn,{variant:"secondary",className:"px-3 py-1.5",children:[l.jsx("span",{className:"mr-2",children:v.displayName}),l.jsx("button",{onClick:()=>d(v.model),className:"text-muted-foreground hover:text-destructive",disabled:o.length===1,title:o.length===1?"Cannot remove last model":"Remove model",children:l.jsx(Yn,{className:"h-3 w-3"})})]},v.model))})]})})}var ume=1,UGt=.9,FGt=.8,BGt=.17,y8=.1,x8=.999,qGt=.9999,HGt=.99,VGt=/[\\\/_+.#"@\[\(\{&]/,GGt=/[\\\/_+.#"@\[\(\{&]/g,WGt=/[\s-]/,h5e=/[\s-]/g;function UB(e,t,n,r,i,a,s){if(a===t.length)return i===e.length?ume:HGt;var o=`${i},${a}`;if(s[o]!==void 0)return s[o];for(var u=r.charAt(a),c=n.indexOf(u,i),d=0,f,p,m,y;c>=0;)f=UB(e,t,n,r,c+1,a+1,s),f>d&&(c===i?f*=ume:VGt.test(e.charAt(c-1))?(f*=FGt,m=e.slice(i,c-1).match(GGt),m&&i>0&&(f*=Math.pow(x8,m.length))):WGt.test(e.charAt(c-1))?(f*=UGt,y=e.slice(i,c-1).match(h5e),y&&i>0&&(f*=Math.pow(x8,y.length))):(f*=BGt,i>0&&(f*=Math.pow(x8,c-i))),e.charAt(c)!==t.charAt(a)&&(f*=qGt)),(f<y8&&n.charAt(c-1)===r.charAt(a+1)||r.charAt(a+1)===r.charAt(a)&&n.charAt(c-1)!==r.charAt(a))&&(p=UB(e,t,n,r,c+1,a+2,s),p*y8>f&&(f=p*y8)),f>d&&(d=f),c=n.indexOf(u,c+1);return s[o]=d,d}function cme(e){return e.toLowerCase().replace(h5e," ")}function KGt(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,UB(e,t,cme(e),cme(t),0,0,{})}var ZGt=Symbol.for("react.lazy"),Mj=dO[" use ".trim().toString()];function YGt(e){return typeof e=="object"&&e!==null&&"then"in e}function m5e(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===ZGt&&"_payload"in e&&YGt(e._payload)}function XGt(e){const t=JGt(e),n=b.forwardRef((r,i)=>{let{children:a,...s}=r;m5e(a)&&typeof Mj=="function"&&(a=Mj(a._payload));const o=b.Children.toArray(a),u=o.find(eWt);if(u){const c=u.props.children,d=o.map(f=>f===u?b.Children.count(c)>1?b.Children.only(null):b.isValidElement(c)?c.props.children:null:f);return l.jsx(t,{...s,ref:i,children:b.isValidElement(c)?b.cloneElement(c,void 0,d):null})}return l.jsx(t,{...s,ref:i,children:a})});return n.displayName=`${e}.Slot`,n}function JGt(e){const t=b.forwardRef((n,r)=>{let{children:i,...a}=n;if(m5e(i)&&typeof Mj=="function"&&(i=Mj(i._payload)),b.isValidElement(i)){const s=nWt(i),o=tWt(a,i.props);return i.type!==b.Fragment&&(o.ref=r?Cc(r,s):s),b.cloneElement(i,o)}return b.Children.count(i)>1?b.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var QGt=Symbol("radix.slottable");function eWt(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===QGt}function tWt(e,t){const n={...t};for(const r in t){const i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...o)=>{const u=a(...o);return i(...o),u}:i&&(n[r]=i):r==="style"?n[r]={...i,...a}:r==="className"&&(n[r]=[i,a].filter(Boolean).join(" "))}return{...e,...n}}function nWt(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var rWt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],gh=rWt.reduce((e,t)=>{const n=XGt(`Primitive.${t}`),r=b.forwardRef((i,a)=>{const{asChild:s,...o}=i,u=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l.jsx(u,{...o,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),z_='[cmdk-group=""]',b8='[cmdk-group-items=""]',iWt='[cmdk-group-heading=""]',g5e='[cmdk-item=""]',dme=`${g5e}:not([aria-disabled="true"])`,FB="cmdk-item-select",uv="data-value",aWt=(e,t,n)=>KGt(e,t,n),v5e=b.createContext(void 0),vk=()=>b.useContext(v5e),y5e=b.createContext(void 0),OZ=()=>b.useContext(y5e),x5e=b.createContext(void 0),b5e=b.forwardRef((e,t)=>{let n=cv(()=>{var G,P;return{search:"",value:(P=(G=e.value)!=null?G:e.defaultValue)!=null?P:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=cv(()=>new Set),i=cv(()=>new Map),a=cv(()=>new Map),s=cv(()=>new Set),o=_5e(e),{label:u,children:c,value:d,onValueChange:f,filter:p,shouldFilter:m,loop:y,disablePointerSelection:v=!1,vimBindings:x=!0,..._}=e,S=Ui(),w=Ui(),T=Ui(),N=b.useRef(null),E=gWt();dg(()=>{if(d!==void 0){let G=d.trim();n.current.value=G,A.emit()}},[d]),dg(()=>{E(6,U)},[]);let A=b.useMemo(()=>({subscribe:G=>(s.current.add(G),()=>s.current.delete(G)),snapshot:()=>n.current,setState:(G,P,V)=>{var K,Q,oe,re;if(!Object.is(n.current[G],P)){if(n.current[G]=P,G==="search")R(),$(),E(1,O);else if(G==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let ee=document.getElementById(T);ee?ee.focus():(K=document.getElementById(S))==null||K.focus()}if(E(7,()=>{var ee;n.current.selectedItemId=(ee=z())==null?void 0:ee.id,A.emit()}),V||E(5,U),((Q=o.current)==null?void 0:Q.value)!==void 0){let ee=P??"";(re=(oe=o.current).onValueChange)==null||re.call(oe,ee);return}}A.emit()}},emit:()=>{s.current.forEach(G=>G())}}),[]),I=b.useMemo(()=>({value:(G,P,V)=>{var K;P!==((K=a.current.get(G))==null?void 0:K.value)&&(a.current.set(G,{value:P,keywords:V}),n.current.filtered.items.set(G,M(P,V)),E(2,()=>{$(),A.emit()}))},item:(G,P)=>(r.current.add(G),P&&(i.current.has(P)?i.current.get(P).add(G):i.current.set(P,new Set([G]))),E(3,()=>{R(),$(),n.current.value||O(),A.emit()}),()=>{a.current.delete(G),r.current.delete(G),n.current.filtered.items.delete(G);let V=z();E(4,()=>{R(),V?.getAttribute("id")===G&&O(),A.emit()})}),group:G=>(i.current.has(G)||i.current.set(G,new Set),()=>{a.current.delete(G),i.current.delete(G)}),filter:()=>o.current.shouldFilter,label:u||e["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:S,inputId:T,labelId:w,listInnerRef:N}),[]);function M(G,P){var V,K;let Q=(K=(V=o.current)==null?void 0:V.filter)!=null?K:aWt;return G?Q(G,n.current.search,P):0}function $(){if(!n.current.search||o.current.shouldFilter===!1)return;let G=n.current.filtered.items,P=[];n.current.filtered.groups.forEach(K=>{let Q=i.current.get(K),oe=0;Q.forEach(re=>{let ee=G.get(re);oe=Math.max(ee,oe)}),P.push([K,oe])});let V=N.current;F().sort((K,Q)=>{var oe,re;let ee=K.getAttribute("id"),le=Q.getAttribute("id");return((oe=G.get(le))!=null?oe:0)-((re=G.get(ee))!=null?re:0)}).forEach(K=>{let Q=K.closest(b8);Q?Q.appendChild(K.parentElement===Q?K:K.closest(`${b8} > *`)):V.appendChild(K.parentElement===V?K:K.closest(`${b8} > *`))}),P.sort((K,Q)=>Q[1]-K[1]).forEach(K=>{var Q;let oe=(Q=N.current)==null?void 0:Q.querySelector(`${z_}[${uv}="${encodeURIComponent(K[0])}"]`);oe?.parentElement.appendChild(oe)})}function O(){let G=F().find(V=>V.getAttribute("aria-disabled")!=="true"),P=G?.getAttribute(uv);A.setState("value",P||void 0)}function R(){var G,P,V,K;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let Q=0;for(let oe of r.current){let re=(P=(G=a.current.get(oe))==null?void 0:G.value)!=null?P:"",ee=(K=(V=a.current.get(oe))==null?void 0:V.keywords)!=null?K:[],le=M(re,ee);n.current.filtered.items.set(oe,le),le>0&&Q++}for(let[oe,re]of i.current)for(let ee of re)if(n.current.filtered.items.get(ee)>0){n.current.filtered.groups.add(oe);break}n.current.filtered.count=Q}function U(){var G,P,V;let K=z();K&&(((G=K.parentElement)==null?void 0:G.firstChild)===K&&((V=(P=K.closest(z_))==null?void 0:P.querySelector(iWt))==null||V.scrollIntoView({block:"nearest"})),K.scrollIntoView({block:"nearest"}))}function z(){var G;return(G=N.current)==null?void 0:G.querySelector(`${g5e}[aria-selected="true"]`)}function F(){var G;return Array.from(((G=N.current)==null?void 0:G.querySelectorAll(dme))||[])}function D(G){let P=F()[G];P&&A.setState("value",P.getAttribute(uv))}function W(G){var P;let V=z(),K=F(),Q=K.findIndex(re=>re===V),oe=K[Q+G];(P=o.current)!=null&&P.loop&&(oe=Q+G<0?K[K.length-1]:Q+G===K.length?K[0]:K[Q+G]),oe&&A.setState("value",oe.getAttribute(uv))}function q(G){let P=z(),V=P?.closest(z_),K;for(;V&&!K;)V=G>0?hWt(V,z_):mWt(V,z_),K=V?.querySelector(dme);K?A.setState("value",K.getAttribute(uv)):W(G)}let X=()=>D(F().length-1),L=G=>{G.preventDefault(),G.metaKey?X():G.altKey?q(1):W(1)},Y=G=>{G.preventDefault(),G.metaKey?D(0):G.altKey?q(-1):W(-1)};return b.createElement(gh.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:G=>{var P;(P=_.onKeyDown)==null||P.call(_,G);let V=G.nativeEvent.isComposing||G.keyCode===229;if(!(G.defaultPrevented||V))switch(G.key){case"n":case"j":{x&&G.ctrlKey&&L(G);break}case"ArrowDown":{L(G);break}case"p":case"k":{x&&G.ctrlKey&&Y(G);break}case"ArrowUp":{Y(G);break}case"Home":{G.preventDefault(),D(0);break}case"End":{G.preventDefault(),X();break}case"Enter":{G.preventDefault();let K=z();if(K){let Q=new Event(FB);K.dispatchEvent(Q)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:I.inputId,id:I.labelId,style:yWt},u),AP(e,G=>b.createElement(y5e.Provider,{value:A},b.createElement(v5e.Provider,{value:I},G))))}),sWt=b.forwardRef((e,t)=>{var n,r;let i=Ui(),a=b.useRef(null),s=b.useContext(x5e),o=vk(),u=_5e(e),c=(r=(n=u.current)==null?void 0:n.forceMount)!=null?r:s?.forceMount;dg(()=>{if(!c)return o.item(i,s?.id)},[c]);let d=w5e(i,a,[e.value,e.children,a],e.keywords),f=OZ(),p=Kp(E=>E.value&&E.value===d.current),m=Kp(E=>c||o.filter()===!1?!0:E.search?E.filtered.items.get(i)>0:!0);b.useEffect(()=>{let E=a.current;if(!(!E||e.disabled))return E.addEventListener(FB,y),()=>E.removeEventListener(FB,y)},[m,e.onSelect,e.disabled]);function y(){var E,A;v(),(A=(E=u.current).onSelect)==null||A.call(E,d.current)}function v(){f.setState("value",d.current,!0)}if(!m)return null;let{disabled:x,value:_,onSelect:S,forceMount:w,keywords:T,...N}=e;return b.createElement(gh.div,{ref:Cc(a,t),...N,id:i,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!p,"data-disabled":!!x,"data-selected":!!p,onPointerMove:x||o.getDisablePointerSelection()?void 0:v,onClick:x?void 0:y},e.children)}),oWt=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...a}=e,s=Ui(),o=b.useRef(null),u=b.useRef(null),c=Ui(),d=vk(),f=Kp(m=>i||d.filter()===!1?!0:m.search?m.filtered.groups.has(s):!0);dg(()=>d.group(s),[]),w5e(s,o,[e.value,e.heading,u]);let p=b.useMemo(()=>({id:s,forceMount:i}),[i]);return b.createElement(gh.div,{ref:Cc(o,t),...a,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&b.createElement("div",{ref:u,"cmdk-group-heading":"","aria-hidden":!0,id:c},n),AP(e,m=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?c:void 0},b.createElement(x5e.Provider,{value:p},m))))}),lWt=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),a=Kp(s=>!s.search);return!n&&!a?null:b.createElement(gh.div,{ref:Cc(i,t),...r,"cmdk-separator":"",role:"separator"})}),uWt=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,a=OZ(),s=Kp(c=>c.search),o=Kp(c=>c.selectedItemId),u=vk();return b.useEffect(()=>{e.value!=null&&a.setState("search",e.value)},[e.value]),b.createElement(gh.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":u.listId,"aria-labelledby":u.labelId,"aria-activedescendant":o,id:u.inputId,type:"text",value:i?e.value:s,onChange:c=>{i||a.setState("search",c.target.value),n?.(c.target.value)}})}),cWt=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,a=b.useRef(null),s=b.useRef(null),o=Kp(c=>c.selectedItemId),u=vk();return b.useEffect(()=>{if(s.current&&a.current){let c=s.current,d=a.current,f,p=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let m=c.offsetHeight;d.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return p.observe(c),()=>{cancelAnimationFrame(f),p.unobserve(c)}}},[]),b.createElement(gh.div,{ref:Cc(a,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:u.listId},AP(e,c=>b.createElement("div",{ref:Cc(s,u.listInnerRef),"cmdk-list-sizer":""},c)))}),dWt=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:a,container:s,...o}=e;return b.createElement(bO,{open:n,onOpenChange:r},b.createElement(_O,{container:s},b.createElement(wO,{"cmdk-overlay":"",className:i}),b.createElement(SO,{"aria-label":e.label,"cmdk-dialog":"",className:a},b.createElement(b5e,{ref:t,...o}))))}),fWt=b.forwardRef((e,t)=>Kp(n=>n.filtered.count===0)?b.createElement(gh.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),pWt=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...a}=e;return b.createElement(gh.div,{ref:t,...a,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},AP(e,s=>b.createElement("div",{"aria-hidden":!0},s)))}),yk=Object.assign(b5e,{List:cWt,Item:sWt,Input:uWt,Group:oWt,Separator:lWt,Dialog:dWt,Empty:fWt,Loading:pWt});function hWt(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function mWt(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _5e(e){let t=b.useRef(e);return dg(()=>{t.current=e}),t}var dg=typeof window>"u"?b.useEffect:b.useLayoutEffect;function cv(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Kp(e){let t=OZ(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function w5e(e,t,n,r=[]){let i=b.useRef(),a=vk();return dg(()=>{var s;let o=(()=>{var c;for(let d of n){if(typeof d=="string")return d.trim();if(typeof d=="object"&&"current"in d)return d.current?(c=d.current.textContent)==null?void 0:c.trim():i.current}})(),u=r.map(c=>c.trim());a.value(e,o,u),(s=t.current)==null||s.setAttribute(uv,o),i.current=o}),i}var gWt=()=>{let[e,t]=b.useState(),n=cv(()=>new Map);return dg(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function vWt(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function AP({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(vWt(t),{ref:t.ref},n(t.props.children)):n(t)}var yWt={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function S5e({className:e,...t}){return l.jsx(yk,{"data-slot":"command",className:Ie("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",e),...t})}function k5e({className:e,...t}){return l.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[l.jsx(Bq,{className:"size-4 shrink-0 opacity-50"}),l.jsx(yk.Input,{"data-slot":"command-input",className:Ie("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function E5e({...e}){return l.jsx(yk.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...e})}function T5e({className:e,...t}){return l.jsx(yk.Group,{"data-slot":"command-group",className:Ie("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",e),...t})}function N5e({className:e,...t}){return l.jsx(yk.Item,{"data-slot":"command-item",className:Ie("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function fme({items:e,placeholder:t="Select item...",searchPlaceholder:n="Search...",emptyMessage:r="No item found.",className:i,value:a,onValueChange:s}){const[o,u]=b.useState(!1),[c,d]=b.useState(""),f=a!==void 0?a:c,p=y=>{s?s(y):d(y)},m=()=>{if(f){const y=e.find(v=>v.value===f);return y?y.label:f}return t};return l.jsxs(qo,{open:o,onOpenChange:u,modal:!0,children:[l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"outline",role:"combobox","aria-expanded":o,className:Ie("w-[200px] justify-between bg-background",i),children:[l.jsx("span",{className:"truncate",children:m()}),l.jsx(Lq,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),l.jsx(Ho,{className:"w-96 p-0",align:"start",children:l.jsxs(S5e,{children:[l.jsx(k5e,{placeholder:n,className:"h-9"}),l.jsx(E5e,{children:r}),l.jsx(T5e,{className:"max-h-48 overflow-auto",children:e.map(y=>{const v=f===y.value;return l.jsxs(N5e,{value:y.value,onSelect:x=>{p(y.value),u(!1)},children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{children:y.label}),y.description&&l.jsx("span",{className:"text-xs text-muted-foreground",children:y.description})]}),l.jsx(xi,{className:Ie("ml-auto h-4 w-4",v?"opacity-100":"opacity-0")})]},y.value)})})]})})]})}function C5e({toolCalls:e,onChange:t,availableTools:n=[]}){const r=()=>{t([...e,{toolName:"",arguments:{}}])},i=y=>{t(e.filter((v,x)=>x!==y))},a=(y,v)=>{const x=[...e];x[y]={...x[y],toolName:v,arguments:{}},t(x)},s=(y,v)=>{const x=[...e],_=x[y].arguments||{};let S="arg";{let w=1;for(;_[S]!==void 0;)S=`arg${w}`,w++}x[y]={...x[y],arguments:{..._,[S]:""}},t(x)},o=(y,v)=>{const x=[...e],_={...x[y].arguments||{}};delete _[v],x[y]={...x[y],arguments:_},t(x)},u=(y,v,x)=>{if(!x||v===x)return;const _=[...e],S=_[y].arguments||{},T=Object.entries(S).map(([N,E])=>N===v?[x,E]:[N,E]);_[y]={..._[y],arguments:Object.fromEntries(T)},t(_)},c=(y,v,x)=>{const _=[...e],S={..._[y].arguments||{}};let w=x;if(x.trim()!=="")try{/^-?\d+\.?\d*$/.test(x)?w=parseFloat(x):x==="true"||x==="false"?w=x==="true":(x.startsWith("[")||x.startsWith("{"))&&(w=JSON.parse(x))}catch{w=x}S[v]=w,_[y]={..._[y],arguments:S},t(_)},d=(y,v)=>{const x=e[y],_=n.find(S=>S.name===x.toolName);return _?.inputSchema?.properties?_.inputSchema.properties[v]:null},f=y=>{const v=e[y],x=n.find(S=>S.name===v.toolName);if(!x?.inputSchema?.properties)return[];const _=x.inputSchema.properties;return Object.keys(_).map(S=>({key:S,schema:_[S]}))},p=y=>y==="",m=y=>!y||y.trim()==="";return l.jsxs("div",{className:"space-y-4",children:[e.map((y,v)=>l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/10 p-4 space-y-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("div",{className:"flex-1",children:[l.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1 block",children:"Tool name"}),n.length>0?l.jsx(fme,{items:n.map(x=>({value:x.name,label:x.name,description:x.description})),value:y.toolName,onValueChange:x=>a(v,x),placeholder:"Select tool...",searchPlaceholder:"Search tools...",className:Ie("w-full justify-between font-mono text-sm h-9",m(y.toolName)&&"border-destructive focus-visible:ring-destructive")}):l.jsx(Ct,{value:y.toolName,onChange:x=>a(v,x.target.value),placeholder:"e.g. get_transactions",className:Ie("font-mono text-sm",m(y.toolName)&&"border-destructive focus-visible:ring-destructive")})]}),l.jsx(Ee,{variant:"ghost",size:"icon",onClick:()=>i(v),className:"mt-5 h-8 w-8 text-muted-foreground hover:text-destructive",children:l.jsx(Yn,{className:"h-4 w-4"})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Arguments"}),l.jsx("div",{className:"space-y-2",children:Object.entries(y.arguments||{}).map(([x,_])=>{const S=d(v,x),w=f(v).filter(E=>!y.arguments.hasOwnProperty(E.key)||E.key===x),T=/^arg\d*$/.test(x)&&!f(v).some(E=>E.key===x),N=w.map(E=>{let A=E.schema?.description||"";return E.schema?.type&&(A+=A?` (Type: ${E.schema.type})`:`Type: ${E.schema.type}`),{value:E.key,label:E.key,description:A}});return l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsxs("div",{className:"flex-1",children:[l.jsx(fme,{items:N,value:T?"":x,onValueChange:E=>u(v,x,E),placeholder:"Select argument...",searchPlaceholder:"Search arguments...",className:"w-full justify-between font-mono text-sm h-9"}),S?.description&&l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:S.description})]}),l.jsx("div",{className:"flex-[2]",children:l.jsx(So,{value:typeof _=="string"?_:JSON.stringify(_),onChange:E=>c(v,x,E.target.value),placeholder:S?.type?`${S.type}`:"Value",className:Ie("font-mono text-sm resize-none min-h-[36px]",p(_)&&"border-destructive focus-visible:ring-destructive"),rows:1})}),l.jsx(Ee,{variant:"ghost",size:"icon",onClick:()=>o(v,x),className:"h-8 w-8 text-muted-foreground hover:text-destructive",children:l.jsx(Yn,{className:"h-4 w-4"})})]},x)})}),y.toolName&&l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>s(v),children:[l.jsx(_o,{className:"h-3 w-3 mr-1"}),"Add argument"]})]})]},v)),l.jsxs(Ee,{variant:"outline",onClick:r,className:"w-full",children:[l.jsx(_o,{className:"h-4 w-4 mr-2"}),"Add expected tool call"]})]})}function xWt({iteration:e,testCase:t,loading:n=!1,onClear:r,serverNames:i=[]}){const a=e!==null,s=e?Fl(e):null,o=s==="passed",u=s==="failed",c=s==="pending",d=e?.testCaseSnapshot?.model||"Unknown",f=e?.startedAt??e?.createdAt,p=e?.updatedAt??e?.createdAt,m=f&&p?Math.max(p-f,0):null;return l.jsxs("div",{className:"h-full flex flex-col bg-muted/20",children:[a&&!n&&l.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[o&&l.jsx(ko,{className:"h-5 w-5",style:{color:cle.CHART_COLORS.PASSED}}),u&&l.jsx(qd,{className:"h-5 w-5",style:{color:cle.CHART_COLORS.FAILED}}),c&&l.jsx(Pn,{className:"h-5 w-5 animate-spin text-muted-foreground"}),l.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[l.jsx("span",{className:"font-mono font-medium text-foreground",children:d}),l.jsxs("span",{children:[e.actualToolCalls?.length||0," tools"]}),l.jsxs("span",{children:[e.tokensUsed?.toLocaleString()||0," tokens"]}),m!==null&&l.jsx("span",{children:zPt(m)})]})]}),r&&l.jsx("button",{onClick:r,className:"text-xs text-muted-foreground hover:text-foreground transition-colors",children:"Clear"})]}),l.jsx("div",{className:"flex-1 overflow-hidden h-0",children:n?l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsxs("div",{className:"text-center",children:[l.jsx(Pn,{className:"h-6 w-6 animate-spin text-muted-foreground mx-auto mb-2"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Running test..."})]})}):a?l.jsx(Es,{className:"h-full",children:l.jsx("div",{className:"p-3",children:l.jsx(jZ,{iteration:e,testCase:t,serverNames:i})})}):l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Click Run to execute this test"})})})]})}const pme=(e,t)=>{if(t)return!0;if(e.length===0)return!1;for(const n of e){if(!n.toolName||n.toolName.trim()==="")return!1;if(n.arguments){for(const r of Object.values(n.arguments))if(r==="")return!1}}return!0},Nv=e=>e==null?null:Array.isArray(e)?e.map(t=>Nv(t)):typeof e=="object"?Object.keys(e).sort().reduce((t,n)=>(t[n]=Nv(e[n]),t),{}):e;function bWt({suiteId:e,selectedTestCaseId:t,connectedServerNames:n}){const{getAccessToken:r}=Aa(),{getToken:i,hasToken:a}=zx(),[s,o]=b.useState(null),[u,c]=b.useState(!1),[d,f]=b.useState([]),[p,m]=b.useState(""),[y,v]=b.useState(!1),[x,_]=b.useState(null),[S,w]=b.useState(null),T=Ua("testSuites:listTestCases",{suiteId:e}),N=_n("testSuites:updateTestCase"),E=b.useMemo(()=>T&&T.find(P=>P._id===t)||null,[T,t]),A=E?.lastMessageRun,I=Ua("testSuites:getTestIteration",A?{iterationId:A}:"skip");b.useEffect(()=>{w(null),_(null)},[t]),b.useEffect(()=>{I&&w(I)},[I]),b.useEffect(()=>{E&&o({title:E.title,query:E.query,runs:E.runs,expectedToolCalls:E.expectedToolCalls||[],isNegativeTest:E.isNegativeTest,scenario:E.scenario,expectedOutput:E.expectedOutput,advancedConfig:E.advancedConfig})},[t,E?._id]);const M=Ua("testSuites:getTestSuitesOverview",{}),$=b.useMemo(()=>M?M.find(P=>P.suite._id===e)?.suite:null,[M,e]),O=b.useMemo(()=>$?($.environment?.servers||[]).filter(V=>!n.has(V)):[],[$,n]),R=O.length===0;b.useEffect(()=>{async function P(){if(!$)return;const V=$.environment?.servers||[];if(V.length===0){f([]);return}try{const K=await Yt("/api/mcp/list-tools",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:V})});if(K.ok){const Q=await K.json();f(Q.tools||[])}}catch(K){console.error("Failed to fetch tools:",K)}}P()},[$]);const U=()=>{c(!0)},z=()=>{c(!1)},F=P=>{P.key==="Enter"?(P.preventDefault(),z()):P.key==="Escape"&&(s&&E&&o({...s,title:E.title}),c(!1))},D=b.useMemo(()=>{if(!s||!E)return!1;const P=JSON.stringify(Nv(s.expectedToolCalls||[])),V=JSON.stringify(Nv(E.expectedToolCalls||[])),K=JSON.stringify(Nv(s.advancedConfig||{})),Q=JSON.stringify(Nv(E.advancedConfig||{}));return s.title!==E.title||s.query!==E.query||s.runs!==E.runs||P!==V||K!==Q||(s.scenario||"")!==(E.scenario||"")||(s.expectedOutput||"")!==(E.expectedOutput||"")},[s,E]),W=b.useMemo(()=>s?pme(s.expectedToolCalls||[],E?.isNegativeTest):!0,[s,E?.isNegativeTest]),q=async()=>{if(!(!s||!E)){if(!pme(s.expectedToolCalls||[],E.isNegativeTest)){Pe.error("Cannot save: All tool names must be specified and argument values cannot be empty.");return}try{await N({testCaseId:E._id,title:s.title,query:s.query,runs:s.runs,expectedToolCalls:s.expectedToolCalls,scenario:s.scenario,expectedOutput:s.expectedOutput,advancedConfig:s.advancedConfig}),Pe.success("Changes saved")}catch(P){throw console.error("Failed to save:",P),Pe.error("Failed to save changes"),P}}},X=async()=>{if(!p||!E||!$)return;const[P,...V]=p.split("/"),K=V.join("/");if(!P||!K){Pe.error("Invalid model selection");return}if(!_r(K)){const Q=P.toLowerCase();if(!a(Q)){Pe.error(`Please add your ${P} API key in Settings before running this test`);return}}w(null),v(!0),Tr.capture("eval_test_case_run_started",{location:"test_template_editor",platform:Et(),environment:void 0,suite_id:e,test_case_id:E._id,model:p});try{const Q=await r(),oe=$.environment?.servers||[],re={};if(!_r(K)){const te=P.toLowerCase(),Z=i(te);Z&&(re[P]=Z)}const ee=await Yt("/api/mcp/evals/run-test-case",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({testCaseId:E._id,model:K,provider:P,serverIds:oe,modelApiKeys:Object.keys(re).length>0?re:void 0,convexAuthToken:Q,testCaseOverrides:s?{query:s.query,expectedToolCalls:s.expectedToolCalls,runs:s.runs}:void 0})});if(!ee.ok){const te=await ee.text();throw new Error(te||"Failed to run test case")}const le=await ee.json();if(le.iteration){w(le.iteration);const te=le.iteration,Z=te.startedAt??te.createdAt,ne=te.updatedAt??te.createdAt,J=Z&&ne?Math.max(ne-Z,0):0;Tr.capture("eval_test_case_run_completed",{location:"test_template_editor",platform:Et(),environment:void 0,suite_id:e,test_case_id:E._id,model:p,result:te.result||"unknown",duration_ms:J})}Pe.success("Test completed successfully!")}catch(Q){console.error("Failed to run test case:",Q),Pe.error(Q instanceof Error?Q.message:"Failed to run test case")}finally{v(!1)}},L=async()=>{if(E)try{await N({testCaseId:E._id,lastMessageRun:null}),w(null),Pe.success("Result cleared")}catch(P){console.error("Failed to clear result:",P),Pe.error("Failed to clear result")}},Y=async()=>{if(!E)return;const P=!E.isNegativeTest;_(P);try{await N({testCaseId:E._id,isNegativeTest:P,...P&&{expectedToolCalls:[]}}),_(null)}catch(V){console.error("Failed to toggle negative test:",V),Pe.error("Failed to update test type"),_(null)}},G=b.useMemo(()=>E?(E.models||[]).map(V=>({value:`${V.provider}/${V.model}`,label:V.model,provider:V.provider})):[],[E]);return b.useEffect(()=>{G.length>0&&!p&&m(G[0].value)},[G,p]),E?l.jsxs(Bc,{direction:"vertical",className:"h-full",children:[l.jsx(ta,{defaultSize:40,minSize:20,children:l.jsx("div",{className:"h-full overflow-auto",children:l.jsxs("div",{className:"p-2 space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between gap-4 px-1 pb-3 border-b",children:[l.jsx("div",{className:"flex-1 min-w-0",children:u?l.jsx("input",{type:"text",value:s?.title||"",onChange:P=>s&&o({...s,title:P.target.value}),onBlur:z,onKeyDown:F,autoFocus:!0,className:"px-0 py-0 text-lg font-semibold border-none focus:outline-none focus:ring-0 bg-transparent w-full"}):l.jsx("h2",{className:"text-lg font-semibold cursor-pointer hover:opacity-60 transition-opacity truncate",onClick:U,children:s?.title||E.title})}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[l.jsx(JO,{checked:x??E.isNegativeTest??!1,onCheckedChange:Y,className:"scale-75 data-[state=checked]:bg-orange-500"}),l.jsx("span",{className:`text-[10px] ${x??E.isNegativeTest?"text-orange-500":"text-muted-foreground"}`,children:"NEG"})]})}),l.jsx(zt,{children:l.jsx("p",{className:"text-xs",children:x??E.isNegativeTest?"Negative test: passes when no tools are called":"Click to mark as negative test"})})]}),l.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[l.jsxs(ju,{value:p,onValueChange:m,disabled:y||G.length===0,children:[l.jsx(Ru,{className:"h-9 text-xs border-0 bg-muted/50 hover:bg-muted transition-colors w-[180px]",children:l.jsx(Ou,{placeholder:"Select model"})}),l.jsx(Pu,{children:G.length===0?l.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No models available"}):G.map(P=>l.jsx(Ea,{value:P.value,children:P.label},P.value))})]}),D&&l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsxs(Ee,{onClick:q,disabled:y||!W,variant:"outline",size:"sm",className:"h-9 px-4 text-xs font-medium",children:[l.jsx(vS,{className:"h-3.5 w-3.5 mr-2"}),"Save"]})})}),l.jsx(zt,{children:W?"Save changes to this test case":"All tool names must be specified and argument values cannot be empty"})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsx(Ee,{onClick:X,disabled:!p||y||!s?.query?.trim()||!R,size:"sm",className:"h-9 px-5 text-xs font-medium shadow-sm",children:y?l.jsxs(l.Fragment,{children:[l.jsx(Pn,{className:"h-3.5 w-3.5 animate-spin mr-2"}),"Running..."]}):l.jsxs(l.Fragment,{children:[l.jsx(Tx,{className:"h-3.5 w-3.5 mr-2 fill-current"}),"Run"]})})})}),l.jsx(zt,{children:R?p?s?.query?.trim()?"Run this test":"Enter a query to run":"Select a model to run":`Connect the following servers: ${O.join(", ")}`})]})]})]}),s?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"px-1 pt-2",children:[l.jsx(Zn,{className:"text-xs text-muted-foreground font-medium",children:"Scenario"}),l.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:E?.isNegativeTest?"Describe the scenario where your app should not trigger":"Describe the use case to test"}),l.jsx(So,{value:s.scenario||"",onChange:P=>o({...s,scenario:P.target.value}),rows:2,placeholder:E?.isNegativeTest?"e.g., User asks about unrelated topic...":"e.g., Check current time display...",className:"text-sm resize-none border-0 bg-muted/30 focus-visible:bg-muted/50 transition-colors px-3 py-2"})]}),l.jsxs("div",{className:"px-1 pt-3",children:[l.jsx(Zn,{className:"text-xs text-muted-foreground font-medium",children:"User Prompt"}),l.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:E?.isNegativeTest?"Example prompt where your app should not trigger":"The exact prompt or interaction to begin the test"}),l.jsx(So,{value:s.query,onChange:P=>o({...s,query:P.target.value}),rows:4,placeholder:"Enter your test prompt here...",className:"font-mono text-sm resize-none border-0 bg-muted/30 focus-visible:bg-muted/50 transition-colors px-3 py-2.5"})]}),!E?.isNegativeTest&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"px-1 pt-3",children:[l.jsx(Zn,{className:"text-xs text-muted-foreground font-medium",children:"Tool Triggered"}),l.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"Which tools should be called?"}),l.jsx(C5e,{toolCalls:s.expectedToolCalls||[],onChange:P=>o({...s,expectedToolCalls:P}),availableTools:d})]}),l.jsxs("div",{className:"px-1 pt-3",children:[l.jsx(Zn,{className:"text-xs text-muted-foreground font-medium",children:"Expected Output"}),l.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"The output or experience we should expect to receive back from the MCP server"}),l.jsx(So,{value:s.expectedOutput||"",onChange:P=>o({...s,expectedOutput:P.target.value}),rows:2,placeholder:"e.g., Should return pokemon data with name, type, and stats...",className:"text-sm resize-none border-0 bg-muted/30 focus-visible:bg-muted/50 transition-colors px-3 py-2"})]})]})]}):l.jsx("div",{className:"py-8 text-center text-xs text-muted-foreground",children:"Loading..."})]})})}),l.jsx($u,{withHandle:!0}),l.jsx(ta,{defaultSize:60,minSize:20,maxSize:80,children:l.jsx(xWt,{iteration:S,testCase:E,loading:y,onClear:L,serverNames:($?.environment?.servers||[]).filter(P=>n.has(P))})})]}):l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading test case..."})})}function A5e({minimumPassRate:e,onMinimumPassRateChange:t}){const[n,r]=b.useState(e.toString()),i=()=>{const s=Number(n);if(isNaN(s))r(e.toString());else{const o=Math.max(0,Math.min(100,s));t(o),r(o.toString())}},a=s=>{s.key==="Enter"?(i(),s.target.blur()):s.key==="Escape"&&(r(e.toString()),s.target.blur())};return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Zn,{htmlFor:"pass-criteria",className:"text-sm text-muted-foreground",children:"Minimum accuracy:"}),l.jsx(Ct,{id:"pass-criteria",type:"number",min:0,max:100,value:n,onChange:s=>r(s.target.value),onBlur:i,onKeyDown:a,className:"w-16 text-center [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),l.jsx("span",{className:"text-sm text-muted-foreground",children:"%"})]})}function _Wt({suite:e,cases:t,allIterations:n,runs:r,runsViewMode:i,onViewModeChange:a,onTestCaseClick:s,runTrendData:o,modelStats:u,runsLoading:c,onRunClick:d}){const f=b.useMemo(()=>{const y=new Set(r.filter(v=>v.isActive===!1).map(v=>v._id));return t.map(v=>{const x=n.filter(I=>I.testCaseId===v._id&&(!I.suiteRunId||!y.has(I.suiteRunId))),_=x.map(I=>Fl(I)),S=_.filter(I=>I==="passed").length,w=_.filter(I=>I==="passed"||I==="failed").length,T=w>0?Math.round(S/w*100):0,N=x.filter(I=>I.startedAt&&I.updatedAt&&I.result!=="pending"),E=N.reduce((I,M)=>{const $=(M.updatedAt??0)-(M.startedAt??0);return I+$},0),A=N.length>0?E/N.length:0;return{testCase:v,iterations:w,avgAccuracy:T,avgDuration:A}})},[t,n,r]),p=y=>{if(y<1e3)return`${y}ms`;const v=Math.round(y/1e3);if(v<60)return`${v}s`;const x=Math.floor(v/60),_=v%60;return _?`${x}m ${_}s`:`${x}m`},m={passRate:{label:"Pass Rate",color:"var(--chart-1)"}};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Accuracy"})}),l.jsx("div",{className:"px-4 pb-4",children:l.jsx(IZ,{data:o,isLoading:c,height:"h-32",onClick:d})})]}),l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Performance by model"})}),l.jsx("div",{className:"px-4 pb-4",children:u.length>0?l.jsx(Ud,{config:m,className:"aspect-auto h-32 w-full",children:l.jsxs(Xv,{data:u,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"model",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:11},interval:0,height:40,tickFormatter:y=>y.length>15?y.substring(0,12)+"...":y}),l.jsx(Nu,{domain:[0,100],tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:y=>`${y}%`}),l.jsx(Fd,{cursor:!1,content:({active:y,payload:v})=>{if(!y||!v||v.length===0)return null;const x=v[0].payload;return l.jsx("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:l.jsxs("div",{className:"grid gap-2",children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"text-xs font-semibold",children:x.model}),l.jsxs("span",{className:"text-xs text-muted-foreground mt-0.5",children:[x.passed," passed · ",x.failed," failed"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"h-2 w-2 rounded-full",style:{backgroundColor:"var(--color-passRate)"}}),l.jsxs("span",{className:"text-sm font-semibold",children:[x.passRate,"%"]})]})]})})}}),l.jsx(Ml,{dataKey:"passRate",fill:"var(--color-passRate)",radius:[4,4,0,0],isAnimationActive:!1,minPointSize:8})]})}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"No model data available."})})]})]}),l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground flex flex-col max-h-[600px]",children:[l.jsxs("div",{className:"border-b px-4 py-2 shrink-0 flex items-center justify-between",children:[l.jsx("div",{children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Click on a test case to view its run history and performance."})}),l.jsxs("select",{value:i,onChange:y=>a(y.target.value),className:"text-xs border rounded px-2 py-1 bg-background",children:[l.jsx("option",{value:"runs",children:"Runs"}),l.jsx("option",{value:"test-cases",children:"Test Cases"})]})]}),f.length>0&&l.jsxs("div",{className:"flex items-center gap-6 w-full px-4 py-1.5 bg-muted/30 border-b text-xs font-medium text-muted-foreground",children:[l.jsx("div",{className:"flex-1 min-w-[200px]",children:"Test Case Name"}),l.jsx("div",{className:"min-w-[100px] text-right",children:"Iterations"}),l.jsx("div",{className:"min-w-[100px] text-right",children:"Avg Accuracy"}),l.jsx("div",{className:"min-w-[100px] text-right",children:"Avg Duration"})]}),l.jsx("div",{className:"divide-y overflow-y-auto",children:f.length===0?l.jsx("div",{className:"px-4 py-12 text-center text-sm text-muted-foreground",children:"No test cases found."}):f.map(({testCase:y,iterations:v,avgAccuracy:x,avgDuration:_})=>l.jsxs("button",{onClick:()=>s(y._id),className:"flex items-center gap-6 w-full px-4 py-2.5 text-left transition-colors hover:bg-muted/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:[l.jsx("span",{className:"text-xs font-medium flex-1 min-w-[200px] truncate",children:y.title||"Untitled test case"}),l.jsx("span",{className:"min-w-[100px] text-right text-xs font-mono text-muted-foreground",children:v}),l.jsx("span",{className:"min-w-[100px] text-right text-xs font-mono text-muted-foreground",children:v>0?`${x}%`:"—"}),l.jsx("span",{className:"min-w-[100px] text-right text-xs font-mono text-muted-foreground",children:v>0?p(_):"—"})]},y._id))})]})]})}function wWt({testCase:e,iterations:t,runs:n,onBack:r,onViewRun:i,serverNames:a=[]}){const[s,o]=b.useState(null),u=b.useMemo(()=>{const p=new Set(n.filter(m=>m.isActive===!1).map(m=>m._id));return t.filter(m=>!m.suiteRunId||!p.has(m.suiteRunId))},[t,n]),c=b.useMemo(()=>{const p=new Map;u.forEach(y=>{y.suiteRunId&&(p.has(y.suiteRunId)||p.set(y.suiteRunId,[]),p.get(y.suiteRunId).push(y))});const m=[];return n.forEach(y=>{if(y.isActive===!1)return;const v=p.get(y._id);if(v&&v.length>0){const x=v.map(T=>Fl(T)),_=x.filter(T=>T==="passed").length,S=x.filter(T=>T==="passed"||T==="failed").length,w=S>0?Math.round(_/S*100):0;m.push({runId:y._id,runIdDisplay:y._id.slice(-6),passRate:w,label:new Date(y.completedAt??y.createdAt).toLocaleString()})}}),m.sort((y,v)=>{const x=n.find(T=>T._id===y.runId),_=n.find(T=>T._id===v.runId),S=x?.createdAt??0,w=_?.createdAt??0;return S-w})},[u,n]),d=b.useMemo(()=>{const p=new Map;return u.forEach(m=>{const y=m.testCaseSnapshot;if(!y)return;const v=Fl(m);if(v!=="passed"&&v!=="failed")return;const x=`${y.provider}/${y.model}`;p.has(x)||p.set(x,{provider:y.provider,model:y.model,passed:0,failed:0,total:0});const _=p.get(x);_.total+=1,v==="passed"?_.passed+=1:_.failed+=1}),Array.from(p.values()).map(m=>({model:`${m.provider}/${m.model}`,passRate:m.total>0?Math.round(m.passed/m.total*100):0,passed:m.passed,failed:m.failed})).sort((m,y)=>y.passRate-m.passRate)},[u]),f={passRate:{label:"Pass Rate",color:"var(--chart-1)"}};return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-lg font-semibold",children:e.title||"Untitled test case"}),e.query&&l.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:e.query})]}),l.jsx(Ee,{variant:"ghost",size:"icon",onClick:r,children:l.jsx(Yn,{className:"h-4 w-4"})})]}),l.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[c.length>0&&l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Performance across runs"})}),l.jsx("div",{className:"px-4 pb-4",children:l.jsx(IZ,{data:c,height:"h-32",showLabel:!0,onClick:i})})]}),d.length>0&&l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Performance by model"})}),l.jsx("div",{className:"px-4 pb-4",children:l.jsx(Ud,{config:f,className:"aspect-auto h-32 w-full",children:l.jsxs(Xv,{data:d,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"model",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:11},interval:0,height:40,tickFormatter:p=>{const m=p.split("/");return m.length===2&&m[1].length>15?`${m[0]}/${m[1].substring(0,12)}...`:p}}),l.jsx(Nu,{domain:[0,100],tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:p=>`${p}%`}),l.jsx(Fd,{cursor:!1,content:({active:p,payload:m})=>{if(!p||!m||m.length===0)return null;const y=m[0].payload;return l.jsx("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:l.jsxs("div",{className:"grid gap-2",children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"text-xs font-semibold",children:y.model}),l.jsxs("span",{className:"text-xs text-muted-foreground mt-0.5",children:[y.passed," passed · ",y.failed," failed"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"h-2 w-2 rounded-full",style:{backgroundColor:"var(--color-passRate)"}}),l.jsxs("span",{className:"text-sm font-semibold",children:[y.passRate,"%"]})]})]})})}}),l.jsx(Ml,{dataKey:"passRate",fill:"var(--color-passRate)",radius:[4,4,0,0],isAnimationActive:!1,minPointSize:8})]})})})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs font-medium text-muted-foreground",children:"Iterations"}),u.length===0?l.jsx("div",{className:"py-12 text-center text-sm text-muted-foreground",children:"No iterations found for this test."}):l.jsx("div",{className:"rounded-md border bg-card text-card-foreground divide-y overflow-hidden",children:u.map(p=>{const m=p.testCaseSnapshot,y=p.startedAt??p.createdAt,v=p.updatedAt??p.createdAt,x=y&&v?Math.max(v-y,0):null,_=p.actualToolCalls||[],S=p.result==="pending",w=s===p._id,T=N=>{if(N<1e3)return`${N}ms`;const E=Math.round(N/1e3);if(E<60)return`${E}s`;const A=Math.floor(E/60),I=E%60;return I?`${A}m ${I}s`:`${A}m`};return l.jsxs("div",{className:`relative ${S?"opacity-60":""}`,children:[l.jsx("div",{className:`absolute left-0 top-0 h-full w-1 ${SK(p.result)}`}),l.jsxs("button",{onClick:()=>o(w?null:p._id),className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 cursor-pointer hover:bg-muted/50",children:[l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3 pl-2",children:[l.jsx("div",{className:"text-muted-foreground shrink-0",children:w?l.jsx(Wr,{className:"h-3.5 w-3.5"}):l.jsx(wr,{className:"h-3.5 w-3.5"})}),l.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:l.jsx("span",{className:"text-xs font-medium capitalize",children:p.result})})]}),l.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground shrink-0",children:[l.jsx("div",{className:"min-w-[120px] text-left truncate",children:l.jsx("span",{className:"font-mono text-xs",children:m?`${m.provider}/${m.model}`:"—"})}),l.jsx("div",{className:"min-w-[50px] text-center",children:l.jsx("span",{className:"font-mono",children:S?"—":_.length})}),l.jsx("div",{className:"min-w-[60px] text-center",children:l.jsx("span",{className:"font-mono",children:S?"—":Number(p.tokensUsed||0).toLocaleString()})}),l.jsx("div",{className:"font-mono min-w-[40px] text-right",children:S?"—":x!==null?T(x):"—"}),p.suiteRunId&&i&&!S&&l.jsx("div",{className:"min-w-[100px]",children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-5 text-[11px] px-2",onClick:N=>{N.stopPropagation(),i(p.suiteRunId)},children:["Run ",r2(p.suiteRunId)]})}),S&&l.jsx("div",{className:"w-3.5 flex items-center justify-center",children:l.jsx(Pn,{className:"h-3.5 w-3.5 animate-spin text-warning"})})]})]}),w&&l.jsx("div",{className:"border-t bg-muted/20 px-4 pb-4 pt-3 pl-8",children:l.jsx(jZ,{iteration:p,testCase:e,serverNames:a})})]},p._id)})})]})]})}function SWt(e,t,n,r,i,a){const s=b.useMemo(()=>new Set(i.filter(p=>p.isActive!==!1).map(p=>p._id)),[i]),o=b.useMemo(()=>{const p=a?.totals;if(!p)return{passRate:0,passed:0,failed:0,total:0,cancelled:0,pending:0};const m=p.passed+p.failed+p.cancelled+p.pending;return{passRate:m>0?Math.round(p.passed/m*100):0,passed:p.passed,failed:p.failed,total:m,cancelled:p.cancelled,pending:p.pending}},[a]),u=b.useMemo(()=>i.filter(y=>y.isActive!==!1).slice().reverse().map(y=>{const x=r.filter(T=>T.suiteRunId===y._id).map(T=>Fl(T)),_=x.filter(T=>T==="passed").length,S=x.filter(T=>T==="passed"||T==="failed").length;let w;if(S>0)w=Math.round(_/S*100);else if(y.summary)w=Math.round(y.summary.passRate*100);else return null;return{runId:y._id,runIdDisplay:r2(y._id),passRate:w,label:LPt(y.completedAt??y.createdAt)}}).filter(y=>y!==null),[i,r]),c=b.useMemo(()=>{const p=r.filter(v=>!v.suiteRunId||s.has(v.suiteRunId)),m=new Map;return p.forEach(v=>{const x=v.testCaseSnapshot?.model||"Unknown",_=v.testCaseSnapshot?.model||"Unknown Model",S=Fl(v);if(S!=="passed"&&S!=="failed")return;m.has(x)||m.set(x,{passed:0,failed:0,total:0,modelName:_});const w=m.get(x);w.total+=1,S==="passed"?w.passed+=1:w.failed+=1}),Array.from(m.entries()).map(([v,x])=>({model:x.modelName,passRate:x.total>0?Math.round(x.passed/x.total*100):0,passed:x.passed,failed:x.failed,total:x.total})).sort((v,x)=>v.model.localeCompare(x.model))},[r,s]),d=b.useMemo(()=>{const p=new Map;t.forEach(v=>{p.set(v._id,{testCase:v,iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}})});const m={testCase:null,iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}};n.forEach(v=>{if(v.testCaseId){const x=p.get(v.testCaseId);x?x.iterations.push(v):m.iterations.push(v)}else if(v.testCaseSnapshot){const x=`snapshot-${v.testCaseSnapshot.title}-${v.testCaseSnapshot.query}`;if(!p.has(x)){const _={_id:x,evalTestSuiteId:e._id,createdBy:v.createdBy||"",title:v.testCaseSnapshot.title,query:v.testCaseSnapshot.query,provider:v.testCaseSnapshot.provider,model:v.testCaseSnapshot.model,expectedToolCalls:v.testCaseSnapshot.expectedToolCalls};p.set(x,{testCase:_,iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}})}p.get(x).iterations.push(v)}else m.iterations.push(v)});const y=Array.from(p.values()).filter(v=>v.iterations.length>0).map(v=>{const x=[...v.iterations].sort((_,S)=>_.iterationNumber!=null&&S.iterationNumber!=null?_.iterationNumber-S.iterationNumber:(_.createdAt??0)-(S.createdAt??0));return{...v,iterations:x,summary:mD(x)}});if(m.iterations.length>0){const v=[...m.iterations].sort((x,_)=>x.iterationNumber!=null&&_.iterationNumber!=null?x.iterationNumber-_.iterationNumber:(x.createdAt??0)-(_.createdAt??0));y.push({...m,iterations:v,summary:mD(v)})}return y},[t,n,e._id]),f=b.useMemo(()=>{const p=new Map;return(e.config?.tests||[]).forEach(y=>{const v=y.title.replace(/\s*\[.*?\]\s*$/,"").trim(),x=`template:${v}-${y.query}`;if(p.has(x)||p.set(x,{title:v,query:y.query,testCaseIds:[],iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}}),y.testCaseId){const _=p.get(x);_.testCaseIds.includes(y.testCaseId)||_.testCaseIds.push(y.testCaseId)}}),d.forEach(y=>{if(!y.testCase)return;const v=UPt(y.testCase),x=y.testCase.title.replace(/\s*\[.*?\]\s*$/,"").trim(),_=`template:${x}-${y.testCase.query}`,S=p.has(_)?_:v;p.has(S)||p.set(S,{title:x,query:y.testCase.query,testCaseIds:[],iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}});const w=p.get(S);w.testCaseIds.includes(y.testCase._id)||w.testCaseIds.push(y.testCase._id),w.iterations.push(...y.iterations)}),Array.from(p.values()).map(y=>({...y,summary:mD(y.iterations)}))},[d,e.config?.tests]);return{activeRunIds:s,generalSummary:o,runTrendData:u,modelStats:c,caseGroups:d,templateGroups:f}}function kWt(e,t,n){const r=b.useMemo(()=>e?t.filter(s=>s.suiteRunId===e):[],[e,t]),i=b.useMemo(()=>e?[...r.map(u=>{const c=u.testCaseSnapshot;return{iteration:u,model:c?.model||"",provider:c?.provider||"",title:c?.title||"",query:c?.query||"",result:u.result}})].sort((u,c)=>{if(n==="model"){const d=`${u.provider}/${u.model}`,f=`${c.provider}/${c.model}`;if(d!==f)return d.localeCompare(f);if(u.title!==c.title)return u.title.localeCompare(c.title);const p=u.iteration.iterationNumber??0,m=c.iteration.iterationNumber??0;return p-m}else if(n==="test"){if(u.title!==c.title)return u.title.localeCompare(c.title);const d=`${u.provider}/${u.model}`,f=`${c.provider}/${c.model}`;if(d!==f)return d.localeCompare(f);const p=u.iteration.iterationNumber??0,m=c.iteration.iterationNumber??0;return p-m}else{const d={passed:0,failed:1,cancelled:2,pending:3},f=d[u.result]??4,p=d[c.result]??4;if(f!==p)return f-p;if(u.title!==c.title)return u.title.localeCompare(c.title);const m=`${u.provider}/${u.model}`,y=`${c.provider}/${c.model}`;return m.localeCompare(y)}}).map(u=>u.iteration):[],[e,r,n]),a=b.useMemo(()=>{if(!e||i.length===0)return{donutData:[],durationData:[],tokensData:[],modelData:[]};let s=0,o=0,u=0,c=0;const d=new Map;r.forEach(x=>{const _=x.testCaseSnapshot?.model||"Unknown",S=x.testCaseSnapshot?.model||"Unknown Model",w=Fl(x);if(w!=="passed"&&w!=="failed")return;d.has(_)||d.set(_,{passed:0,failed:0,total:0,modelName:S});const T=d.get(_);T.total+=1,w==="passed"?T.passed+=1:T.failed+=1});const f=Array.from(d.entries()).map(([x,_])=>({model:_.modelName,passRate:_.total>0?Math.round(_.passed/_.total*100):0,passed:_.passed,failed:_.failed,total:_.total})).sort((x,_)=>x.model.localeCompare(_.model)),p=new Map;i.forEach(x=>{const _=x.testCaseSnapshot?.title||"Unknown";p.has(_)||p.set(_,{title:_,durations:[],tokens:[],passed:0,failed:0,pending:0,cancelled:0});const S=p.get(_);x.result==="pending"?S.pending++:x.result==="cancelled"?S.cancelled++:MI(x)?S.passed++:S.failed++;const w=x.startedAt??x.createdAt,T=x.updatedAt??x.createdAt;w&&T&&x.result!=="pending"&&S.durations.push(Math.max(T-w,0)),x.result!=="pending"&&x.tokensUsed&&S.tokens.push(x.tokensUsed)}),p.forEach(x=>{s+=x.passed,o+=x.failed,u+=x.pending,c+=x.cancelled});const m=Array.from(p.values()).map(x=>{const _=x.durations.length>0?x.durations.reduce((S,w)=>S+w,0)/x.durations.length:0;return{name:x.title,duration:_,durationSeconds:_/1e3}}),y=Array.from(p.values()).map(x=>{const _=x.tokens.length>0?x.tokens.reduce((S,w)=>S+w,0)/x.tokens.length:0;return{name:x.title,tokens:_}}),v=[];return s>0&&v.push({name:"Passed",value:s,fill:"hsl(142.1 76.2% 36.3%)"}),o>0&&v.push({name:"Failed",value:o,fill:"hsl(0 84.2% 60.2%)"}),u>0&&v.push({name:"Pending",value:u,fill:"hsl(45.4 93.4% 47.5%)"}),c>0&&v.push({name:"Cancelled",value:c,fill:"hsl(240 3.7% 15.9%)"}),{donutData:v,durationData:m,tokensData:y,modelData:f}},[e,i,r]);return{iterationsForSelectedRun:r,caseGroupsForSelectedRun:i,selectedRunChartData:a}}function EWt({suite:e,cases:t,iterations:n,allIterations:r,runs:i,runsLoading:a,aggregate:s,onRerun:o,onCancelRun:u,onDelete:c,onDeleteRun:d,onDirectDeleteRun:f,connectedServerNames:p,rerunningSuiteId:m,cancellingRunId:y,deletingSuiteId:v,deletingRunId:x,availableModels:_,route:S}){const w=S.type==="suite-edit",T=S.type==="test-detail"||S.type==="test-edit"?S.testId:null,N=S.type==="run-detail"?S.runId:null,E=S.type==="run-detail"?"run-detail":S.type==="test-detail"?"test-detail":S.type==="test-edit"?"test-edit":"overview",A=S.type==="suite-overview"&&S.view==="test-cases"?"test-cases":"runs",[I,M]=b.useState(!1),[$,O]=b.useState("model"),[R,U]=b.useState(100),[z,F]=b.useState(e.description||""),[D,W]=b.useState(!1),q=_n("testSuites:updateTestSuite"),X=_n("testSuites:updateSuiteModels"),{runTrendData:L,modelStats:Y}=SWt(e,t,n,r,i,s),{caseGroupsForSelectedRun:G,selectedRunChartData:P}=kWt(N,r,$),V=b.useMemo(()=>N?i.find(Z=>Z._id===N)??null:null,[N,i]);b.useEffect(()=>{F(e.description||"")},[e.description]),b.useEffect(()=>{if(e.defaultPassCriteria?.minimumPassRate!==void 0){if(U(e.defaultPassCriteria.minimumPassRate),typeof window<"u")try{localStorage.setItem(`suite-${e._id}-criteria-rate`,String(e.defaultPassCriteria.minimumPassRate))}catch(te){console.warn("Failed to sync default pass criteria to localStorage",te)}}else if(typeof window<"u")try{const te=localStorage.getItem(`suite-${e._id}-criteria-rate`);te&&U(Number(te))}catch(te){console.warn("Failed to load default pass criteria",te)}},[e._id,e.defaultPassCriteria]);const K=b.useCallback(()=>{W(!0),F(e.description||"")},[e.description]),Q=b.useCallback(async()=>{if(W(!1),z!==e.description)try{await q({suiteId:e._id,description:z}),Pe.success("Suite description updated")}catch(te){Pe.error("Failed to update suite description"),console.error("Failed to update suite description:",te),F(e.description||"")}else F(e.description||"")},[z,e.description,e._id,q]),oe=b.useCallback(te=>{te.key==="Escape"&&(W(!1),F(e.description||""))},[e.description]),re=async te=>{try{await X({suiteId:e._id,models:te.map(Z=>({model:Z.model,provider:Z.provider}))}),Pe.success("Models updated successfully")}catch(Z){throw Pe.error("Failed to update models"),console.error("Failed to update models:",Z),Z}},ee=te=>{_s({type:"run-detail",suiteId:e._id,runId:te})},le=()=>{M(!1),_s({type:"suite-overview",suiteId:e._id})};return l.jsxs("div",{className:"flex flex-col h-full",children:[l.jsx("div",{className:"shrink-0",children:l.jsx(IGt,{suite:e,viewMode:E,selectedRunDetails:V,isEditMode:w,onRerun:o,onDelete:c,onCancelRun:u,onDeleteRun:d,onViewModeChange:le,connectedServerNames:p,rerunningSuiteId:m,cancellingRunId:y,deletingSuiteId:v,deletingRunId:x,showRunSummarySidebar:I,setShowRunSummarySidebar:M,runsViewMode:A,runs:i,allIterations:r,aggregate:s,testCases:t,availableModels:_,onUpdateModels:re})}),!w&&l.jsx("div",{className:"flex-1 min-h-0",children:E==="test-edit"&&T?l.jsx("div",{className:"h-full",children:l.jsx(bWt,{suiteId:e._id,selectedTestCaseId:T,connectedServerNames:p})}):E==="test-detail"&&T?(()=>{const te=t.find(ne=>ne._id===T);if(!te)return null;const Z=r.filter(ne=>ne.testCaseId===T);return l.jsx(wWt,{testCase:te,iterations:Z,runs:i,serverNames:(e.environment?.servers||[]).filter(ne=>p.has(ne)),onBack:()=>{_s({type:"suite-overview",suiteId:e._id,view:"test-cases"})},onViewRun:ne=>{_s({type:"run-detail",suiteId:e._id,runId:ne})}})})():E==="overview"?l.jsx("div",{className:"space-y-4",children:A==="runs"?l.jsx(jGt,{suite:e,runs:i,runsLoading:a,allIterations:r,runTrendData:L,modelStats:Y,onRunClick:ee,onDirectDeleteRun:f,runsViewMode:A,onViewModeChange:te=>{_s({type:"suite-overview",suiteId:e._id,view:te})}}):l.jsx(_Wt,{suite:e,cases:t,allIterations:r,runs:i,runsViewMode:A,onViewModeChange:te=>{_s({type:"suite-overview",suiteId:e._id,view:te})},onTestCaseClick:te=>{_s({type:"test-detail",suiteId:e._id,testId:te})},runTrendData:L,modelStats:Y,runsLoading:a,onRunClick:ee})},A):E==="run-detail"&&V?l.jsx(DGt,{selectedRunDetails:V,caseGroupsForSelectedRun:G,selectedRunChartData:P,runDetailSortBy:$,onSortChange:O,showRunSummarySidebar:I,setShowRunSummarySidebar:M,serverNames:(e.environment?.servers||[]).filter(te=>p.has(te))}):null}),w&&l.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:l.jsxs("div",{className:"p-6 max-w-5xl mx-auto space-y-8",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-base font-semibold text-foreground",children:"Description"}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Provide context about what this evaluation suite tests"})]}),D?l.jsx("textarea",{value:z,onChange:te=>F(te.target.value),onBlur:Q,onKeyDown:oe,placeholder:"Enter a description for this suite...",autoFocus:!0,className:"w-full px-4 py-3 text-sm border border-input rounded-lg focus:outline-none focus:ring-2 focus:ring-ring resize-none min-h-[100px] bg-background",rows:4}):l.jsx("button",{onClick:K,className:"w-full px-4 py-3 text-sm text-left rounded-lg border border-border hover:border-input hover:bg-accent/50 whitespace-pre-wrap transition-all",children:e.description?l.jsx("span",{className:"text-foreground leading-relaxed",children:e.description}):l.jsx("span",{className:"text-muted-foreground italic",children:"Click to add a description..."})})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-base font-semibold text-foreground",children:"Default Pass/Fail Criteria"}),l.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Set the default criteria for ",l.jsx("strong",{children:"new"})," evaluation runs of this suite. Existing runs keep their original criteria."]})]}),l.jsx(A5e,{minimumPassRate:R,onMinimumPassRateChange:async te=>{U(te),localStorage.setItem(`suite-${e._id}-criteria-rate`,String(te));try{await q({suiteId:e._id,defaultPassCriteria:{minimumPassRate:te}}),Pe.success("Suite updated successfully")}catch(Z){Pe.error("Failed to update suite"),console.error("Failed to update suite:",Z),U(e.defaultPassCriteria?.minimumPassRate??100)}}})]}),l.jsx(zGt,{suite:e,testCases:t,onUpdate:re,availableModels:_})]})})]})}function TWt({server:e,selected:t,onToggle:n}){const[r,i]=b.useState(null),[a,s]=b.useState(!0),{label:o,Icon:u,iconClassName:c,indicatorColor:d}=B1e(e.connectionStatus),f=H1e(e.config),p=q1e(e.config),m=JSON.stringify(e.config,null,2),y=()=>{n(e.name)},v=S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),y())},x=async(S,w,T)=>{S.stopPropagation();try{await navigator.clipboard.writeText(w),i(T),setTimeout(()=>i(null),2e3)}catch(N){console.error("Failed to copy text:",N)}},_=e.connectionStatus==="failed"?`${o} (${e.retryCount} retries)`:o;return l.jsx(vx,{role:"button",tabIndex:0,onClick:y,onKeyDown:v,className:Ie("border bg-card/50 backdrop-blur-sm hover:border-primary/50 hover:shadow-md hover:bg-card/70 transition-all duration-200 cursor-pointer relative",t?"border-primary/60 ring-2 ring-primary/30 shadow-lg":"border-border/50"),children:l.jsxs("div",{className:"p-4 space-y-3 py-0",children:[l.jsx("div",{className:"flex items-baseline justify-between",children:l.jsxs("div",{className:"flex items-baseline gap-3 flex-1",children:[l.jsx("div",{className:"h-2 w-2 rounded-full flex-shrink-0 mt-1",style:{backgroundColor:d}}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h3",{className:"font-medium text-sm text-foreground",children:e.name}),l.jsxs("div",{className:"flex items-center gap-1 leading-none",children:[l.jsx(u,{className:c}),l.jsx("p",{className:"text-xs text-muted-foreground leading-none",children:_})]})]}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:f})]})]})}),l.jsxs("div",{className:"font-mono text-xs text-muted-foreground bg-muted/30 p-2 rounded border border-border/30 break-all relative group",onClick:S=>S.stopPropagation(),children:[l.jsx("div",{className:"pr-8",children:p}),l.jsx("button",{type:"button",onClick:S=>x(S,p,"command"),className:"absolute top-1 right-1 p-1 text-muted-foreground/50 hover:text-foreground transition-colors cursor-pointer",children:r==="command"?l.jsx(xi,{className:"h-3 w-3 text-success"}):l.jsx(Ca,{className:"h-3 w-3"})})]}),a&&l.jsxs("div",{className:"relative rounded border border-border/20 bg-muted/20 p-2 font-mono text-xs text-muted-foreground",onClick:S=>S.stopPropagation(),children:[l.jsx("pre",{className:"max-h-40 overflow-auto pr-8 whitespace-pre-wrap",children:m}),l.jsx("button",{type:"button",onClick:S=>x(S,m,"config"),className:"absolute top-1 right-1 p-1 text-muted-foreground/50 hover:text-foreground transition-colors cursor-pointer",children:r==="config"?l.jsx(xi,{className:"h-3 w-3 text-success"}):l.jsx(Ca,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex justify-end pt-0.5",children:l.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),s(w=>!w)},"aria-label":a?"Hide config":"Show config",className:"rounded-full border border-border/50 bg-background/70 p-1 text-muted-foreground transition-colors hover:text-foreground cursor-pointer",children:a?l.jsx(Ex,{className:"h-3 w-3"}):l.jsx(Wr,{className:"h-3 w-3"})})})]})})}function NWt({connectedServers:e,selectedServers:t,onToggleServer:n}){return l.jsxs("div",{className:"space-y-4",children:[l.jsx("div",{className:"flex items-center justify-between",children:l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg pb-2",children:"Select servers to test"}),l.jsx("p",{className:"text-sm text-muted-foreground pb-2",children:"Choose at least one connected MCP server. You can evaluate multiple servers in the same run."})]})}),e.length>0?l.jsx("div",{className:"grid grid-cols-1 gap-3 lg:grid-cols-2 xl:grid-cols-3",children:e.map(([r,i])=>{const a=t.includes(r);return l.jsx(TWt,{server:i,selected:a,onToggle:n},r)})}):l.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:[l.jsx("p",{className:"font-medium text-foreground",children:"No connected servers yet"}),l.jsx("p",{className:"mt-2",children:"Launch a server from the Workspaces tab to make it available here. Once connected, it will appear instantly."}),l.jsx(Ee,{type:"button",variant:"outline",size:"sm",className:"mt-4",onClick:()=>{window.location.hash="servers"},children:"Go to Workspaces tab"})]})]})}function CWt({availableModels:e,selectedModels:t,modelTab:n,onModelTabChange:r,onToggleModel:i,hasProviderToken:a}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg pb-2",children:"Choose evaluation models"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Select one or more models. Each test will run against all selected models."})]}),l.jsxs("div",{className:"flex items-center gap-1 rounded-lg border p-1 w-fit",children:[l.jsx("button",{type:"button",onClick:()=>r("mcpjam"),className:Ie("rounded-md px-4 py-2 text-sm font-medium transition-colors",n==="mcpjam"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"MCPJam Free Models"}),l.jsx("button",{type:"button",onClick:()=>r("yours"),className:Ie("rounded-md px-4 py-2 text-sm font-medium transition-colors",n==="yours"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Your Providers"})]}),l.jsx("div",{className:"grid grid-cols-1 gap-3 lg:grid-cols-2 xl:grid-cols-3",children:e.filter(s=>n==="mcpjam"?_r(s.id):!_r(s.id)).map(s=>{const o=t.some(d=>d.id===s.id),c=!_r(s.id)&&!a(s.provider);return l.jsx("button",{type:"button",onClick:()=>i(s),className:Ie("rounded-xl border p-4 text-left transition-colors relative",o?"border-primary bg-primary/5":"hover:border-primary/40",c&&"opacity-60"),children:l.jsx("div",{className:"flex items-start justify-between gap-3",children:l.jsxs("div",{className:"flex-1",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h4",{className:"font-semibold text-sm",children:s.name}),o&&l.jsx(xi,{className:"h-4 w-4 text-primary shrink-0"})]}),l.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["by ",s.provider]}),c&&l.jsx("p",{className:"text-xs text-destructive mt-2",children:"Missing API key"})]})})},s.id)})}),t.length>0&&l.jsx("div",{className:"rounded-lg border bg-muted/30 p-3",children:l.jsxs("p",{className:"text-sm font-medium",children:[t.length," model",t.length===1?"":"s"," selected"]})})]})}function AWt({testTemplates:e,availableTools:t,canGenerateTests:n,hasServerAndModelSelection:r,isGenerating:i,isGeneratingNegativeTests:a,onGenerateTests:s,onGenerateNegativeTests:o,onAddTestTemplate:u,onAddNegativeTestTemplate:c,onRemoveTestTemplate:d,onUpdateTestTemplate:f}){const p=e.length>0&&e.some(S=>S.query.trim().length>0),m=(S,w)=>l.jsxs("div",{className:"space-y-3 rounded-lg border bg-background p-4",children:[l.jsxs("div",{className:"flex items-start justify-between gap-3",children:[l.jsxs("div",{className:"flex flex-col flex-1 space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Title"}),l.jsx(Ct,{className:"w-full",value:S.title,onChange:T=>f(w,"title",T.target.value),placeholder:"(Paypal) List transactions"})]}),e.length>1&&l.jsx(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(w),children:l.jsx(Yn,{className:"h-4 w-4"})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Query"}),l.jsx(So,{value:S.query,onChange:T=>f(w,"query",T.target.value),placeholder:"Can you find the most recent Paypal transactions, then create an invoice?",rows:3})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Runs"}),l.jsx(Ct,{type:"number",min:1,value:S.runs,onChange:T=>f(w,"runs",Number(T.target.value)>0?Number(T.target.value):1)})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Expected tools"}),l.jsx(C5e,{toolCalls:S.expectedToolCalls,onChange:T=>f(w,"expectedToolCalls",T),availableTools:t})]})]},w),y=(S,w)=>l.jsxs("div",{className:"space-y-3 rounded-lg border border-orange-500/50 bg-orange-50/5 p-4",children:[l.jsxs("div",{className:"flex items-start justify-between gap-3",children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsxs(Cn,{variant:"outline",className:"bg-orange-500/10 text-orange-600 border-orange-500/30",children:[l.jsx(Lv,{className:"h-3 w-3 mr-1"}),"Negative Test"]})}),e.length>1&&l.jsx(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(w),children:l.jsx(Yn,{className:"h-4 w-4"})})]}),l.jsxs("div",{className:"flex flex-col flex-1 space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Title"}),l.jsx(Ct,{className:"w-full",value:S.title,onChange:T=>f(w,"title",T.target.value),placeholder:"Meta question about search"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Scenario"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Describe why the AI should NOT trigger any tools for this prompt"}),l.jsx(So,{value:S.scenario||"",onChange:T=>f(w,"scenario",T.target.value),placeholder:"User is asking about how the search feature works, not performing a search",rows:2})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"User Prompt"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"The prompt that should NOT trigger any tools"}),l.jsx(So,{value:S.query,onChange:T=>f(w,"query",T.target.value),placeholder:"Can you explain what parameters the search tool accepts?",rows:3})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Runs"}),l.jsx(Ct,{type:"number",min:1,value:S.runs,onChange:T=>f(w,"runs",Number(T.target.value)>0?Number(T.target.value):1)})]})]},w),v=()=>l.jsxs("div",{className:"space-y-12",children:[e.map((S,w)=>S.isNegativeTest?y(S,w):m(S,w)),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Ee,{type:"button",variant:"outline",onClick:u,"aria-label":"Add test case",className:"flex-1",children:[l.jsx(_o,{className:"h-4 w-4 mr-2"}),"Add test case"]}),l.jsxs(Ee,{type:"button",variant:"outline",onClick:c,"aria-label":"Add negative test case",className:"flex-1 border-orange-500/30 text-orange-600 hover:bg-orange-50/10",children:[l.jsx(Lv,{className:"h-4 w-4 mr-2"}),"Add negative test"]})]})]});if(!r&&!p)return l.jsxs("div",{className:"space-y-6",children:[l.jsx("div",{className:"flex items-start justify-between",children:l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg pb-2",children:"Define your test cases"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Specify tool names and their expected arguments. Leave arguments empty to skip argument checking."})]})}),l.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:[l.jsx("p",{className:"font-medium text-foreground",children:"Finish previous steps first"}),l.jsx("p",{className:"mt-2",children:"Select at least one server and choose a model to unlock test authoring. That ensures generated tests know which stack to target."})]})]});const _=i||a;return l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg",children:"Define your test cases"}),l.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Specify tool names and their expected arguments. Leave arguments empty to skip argument checking."})]}),n&&l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Ee,{type:"button",variant:"outline",onClick:s,disabled:_,children:[i?"Generating...":"Generate tests",l.jsx(D1e,{className:"h-4 w-4 ml-2"})]}),l.jsxs(Ee,{type:"button",variant:"outline",onClick:o,disabled:_,className:"border-orange-500/30 text-orange-600 hover:bg-orange-50/10",children:[a?"Generating...":"Generate negative tests",l.jsx(Lv,{className:"h-4 w-4 ml-2"})]})]})]}),_&&r?l.jsx("div",{className:"flex items-center justify-center rounded-lg border p-6",children:l.jsx("div",{className:"text-center text-sm text-muted-foreground",children:i?"Generating test cases...":"Generating negative test cases..."})}):v()]})}function IWt({suiteName:e,suiteDescription:t,minimumPassRate:n,selectedServers:r,selectedModels:i,validTestTemplates:a,onSuiteNameChange:s,onSuiteDescriptionChange:o,onMinimumPassRateChange:u,onEditStep:c,showNameError:d=!1}){return l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsxs(Zn,{htmlFor:"suite-name",className:"text-sm font-medium",children:["Test Suite Name ",l.jsx("span",{className:"text-destructive",children:"*"})]}),l.jsx(Ct,{id:"suite-name",type:"text",value:e,onChange:f=>s(f.target.value),placeholder:"e.g., Weather API Integration Tests",className:Ie("text-lg font-semibold",d&&!e.trim()&&"border-destructive focus-visible:ring-destructive"),autoFocus:!0}),d&&!e.trim()&&l.jsx("p",{className:"text-sm text-destructive font-medium",children:"Please provide a name for this test suite"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{htmlFor:"suite-description",className:"text-sm font-medium",children:"Description (optional)"}),l.jsx(So,{id:"suite-description",value:t,onChange:f=>o(f.target.value),rows:3,placeholder:"What does this suite cover?",className:"resize-none"})]})]}),l.jsx(A5e,{minimumPassRate:n,onMinimumPassRateChange:u}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("h3",{className:"text-lg",children:"Review your configuration"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"After confirming the run, you will see your run begin in the eval results tab."})]}),l.jsxs("div",{className:"space-y-4 rounded-lg border bg-background p-4",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Servers"}),l.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:r.map(f=>l.jsx(Cn,{variant:"outline",children:f},f))})]}),l.jsx(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(0),children:"Edit"})]}),l.jsx(Ew,{}),l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Models"}),i.length>0?l.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:i.map(f=>l.jsx(Cn,{variant:"outline",children:f.name},f.id))}):l.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"No models selected"})]}),l.jsx(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(1),children:"Edit"})]}),l.jsx(Ew,{}),l.jsxs("div",{className:"flex items-start justify-between gap-6",children:[l.jsxs("div",{className:"flex-1",children:[l.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Test Templates"}),l.jsx("div",{className:"mt-3 space-y-3",children:a.map((f,p)=>l.jsxs("div",{className:Ie("rounded-md border p-3",f.isNegativeTest?"bg-orange-50/5 border-orange-500/30":"bg-muted/30"),children:[l.jsxs("div",{className:"flex items-center gap-2",children:[f.isNegativeTest&&l.jsxs(Cn,{variant:"outline",className:"bg-orange-500/10 text-orange-600 border-orange-500/30 text-xs",children:[l.jsx(Lv,{className:"h-3 w-3 mr-1"}),"Negative"]}),l.jsx("p",{className:"text-sm font-semibold text-foreground",children:f.title})]}),f.isNegativeTest&&f.scenario&&l.jsxs("p",{className:"mt-1 text-xs text-orange-600/80 italic",children:["Scenario: ",f.scenario]}),l.jsx("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:f.query}),f.expectedOutput&&l.jsxs("p",{className:"mt-1 text-xs text-muted-foreground/80 italic",children:["Expected: ",f.expectedOutput]}),l.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[l.jsxs("span",{children:[f.runs," run",f.runs===1?"":"s"]}),!f.isNegativeTest&&f.expectedToolCalls.length>0&&l.jsxs("span",{children:["Tools:"," ",f.expectedToolCalls.map(m=>m.toolName).join(", ")]}),f.isNegativeTest&&l.jsx("span",{className:"text-orange-600",children:"Expected: No tools triggered"})]})]},p))})]}),l.jsx(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(2),children:"Edit"})]})]})]})}const _8=()=>({title:"",query:"",runs:wK.RUNS_PER_TEST,expectedToolCalls:[]}),jWt=()=>({title:"",query:"",runs:wK.RUNS_PER_TEST,expectedToolCalls:[],isNegativeTest:!0,scenario:""}),hme=e=>{if(e.length===0)return!1;for(const t of e){if(!t.toolName||t.toolName.trim()==="")return!1;if(t.arguments){for(const n of Object.values(t.arguments))if(n==="")return!1}}return!0};function OWt({availableModels:e,inline:t=!1,onSuccess:n,preselectedServer:r}){const[i,a]=b.useState(!1),[s,o]=b.useState(!1),[u,c]=b.useState(!1),[d,f]=b.useState(!1),p=r&&r!=="none",[m,y]=b.useState(p?1:0),[v,x]=b.useState(null),{isAuthenticated:_}=Ba(),{getAccessToken:S}=Aa(),w=Rx(),{getToken:T,hasToken:N}=zx(),[E,A]=b.useState(()=>p?[r]:[]),[I,M]=b.useState([]),[$,O]=b.useState([_8()]),[R,U]=b.useState("mcpjam"),[z,F]=b.useState(p?r:""),[D,W]=b.useState(""),[q,X]=b.useState(!1),[L,Y]=b.useState(!1),[G,P]=b.useState([]),[V,K]=b.useState(wK.MIN_PASS_RATE),Q=b.useMemo(()=>Object.entries(w.servers).filter(([,fe])=>fe.connectionStatus==="connected"),[w.servers]),oe=b.useMemo(()=>new Set(Q.map(([fe])=>fe)),[Q]);b.useEffect(()=>{if(!(typeof window>"u"))try{const fe=localStorage.getItem(ule.EVAL_RUNNER_PREFERENCES);if(!fe)return;const xe=JSON.parse(fe);x({servers:xe.servers??[],modelIds:xe.modelIds??[]}),xe.passCriteria&&xe.passCriteria.minimumPassRate!==void 0&&K(xe.passCriteria.minimumPassRate)}catch(fe){console.warn("Failed to load eval runner preferences",fe)}},[]),b.useEffect(()=>{if(v&&!p&&v.servers?.length){const fe=v.servers.filter(xe=>oe.has(xe));fe.length&&A(fe)}},[v,oe,p]),b.useEffect(()=>{if(!L&&e.length!==0){if(v?.modelIds&&v.modelIds.length>0){const fe=e.filter(xe=>v.modelIds.includes(xe.id));fe.length>0&&M(fe)}Y(!0)}},[e,v,L]),b.useEffect(()=>{if(!(typeof window>"u"))try{const fe={servers:E,modelIds:I.map(xe=>xe.id),passCriteria:{minimumPassRate:V}};localStorage.setItem(ule.EVAL_RUNNER_PREFERENCES,JSON.stringify(fe))}catch(fe){console.warn("Failed to persist eval runner preferences",fe)}},[E,I,V]),b.useEffect(()=>{async function fe(){if(E.length===0){P([]);return}try{const xe=await fetch(y1.LIST_TOOLS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:E})});if(xe.ok){const Ce=await xe.json();P(Ce.tools||[])}}catch(xe){console.error("Failed to fetch tools:",xe)}}fe()},[E]),b.useEffect(()=>{!t&&!i&&(y(p?1:0),Y(!1))},[t,i,p]);const re=b.useMemo(()=>$.filter(fe=>fe.query.trim().length>0),[$]),ee=b.useMemo(()=>{const fe=I.every(Ce=>_r(Ce.id)||N(Ce.provider)),xe=re.every(Ce=>Ce.isNegativeTest?Ce.query.trim().length>0&&(Ce.scenario?.trim().length??0)>0:hme(Ce.expectedToolCalls));return{servers:E.length>0,model:I.length>0&&fe,tests:re.length>0&&xe}},[E,I,re,N]),le=b.useMemo(()=>ee.servers?ee.model?ee.tests?3:2:1:0,[ee]),te=b.useMemo(()=>{switch(m){case 0:return ee.servers;case 1:return ee.model;case 2:return ee.tests;case 3:return ee.tests&&ee.servers&&ee.model;default:return!1}},[m,ee]),Z=fe=>{A(xe=>xe.includes(fe)?xe.filter(Ce=>Ce!==fe):[...xe,fe])},ne=fe=>{M(xe=>xe.some(He=>He.id===fe.id)?xe.filter(He=>He.id!==fe.id):[...xe,fe])},J=()=>{O(fe=>[...fe,_8()])},se=()=>{O(fe=>[...fe,jWt()])},ie=fe=>{O(xe=>xe.filter((Ce,He)=>He!==fe))},he=(fe,xe,Ce)=>{O(He=>{const Ze=[...He];return Ze[fe]={...Ze[fe],[xe]:Ce},Ze})},ye=async()=>{if(Tr.capture("eval_generate_tests_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),!_){Pe.error("Please sign in to generate tests");return}if(E.length===0){Pe.error("Please select at least one server");return}c(!0);try{const fe=await S(),xe=await fetch(y1.EVALS_GENERATE_TESTS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:E,convexAuthToken:fe})}),Ce=await xe.json();if(!xe.ok)throw new Error(Ce.error||"Failed to generate tests");if(Ce.tests&&Ce.tests.length>0){const He=Ce.tests.map((Ze,st)=>({title:Ze.title||`Generated test ${st+1}`,query:Ze.query||"",runs:Number(Ze.runs)>0?Number(Ze.runs):1,expectedToolCalls:Array.isArray(Ze.expectedToolCalls)?Ze.expectedToolCalls:[]}));O(He),y(2),Pe.success(`Generated ${He.length} test template(s).`)}}catch(fe){console.error("Failed to generate tests:",fe),Pe.error(fe instanceof Error?fe.message:"Failed to generate test cases")}finally{c(!1)}},Ne=async()=>{if(Tr.capture("eval_generate_negative_tests_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),!_){Pe.error("Please sign in to generate negative tests");return}if(E.length===0){Pe.error("Please select at least one server");return}f(!0);try{const fe=await S(),xe=await fetch(y1.EVALS_GENERATE_NEGATIVE_TESTS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:E,convexAuthToken:fe})}),Ce=await xe.json();if(!xe.ok)throw new Error(Ce.error||"Failed to generate negative tests");if(Ce.tests&&Ce.tests.length>0){const He=Ce.tests.map(Ze=>({title:Ze.title||"Untitled Negative Test",query:Ze.query||"",runs:Number(Ze.runs)>0?Number(Ze.runs):1,expectedToolCalls:[],isNegativeTest:!0,scenario:Ze.scenario||""}));O(Ze=>[...Ze,...He]),y(2),Pe.success(`Generated ${He.length} negative test template(s).`)}}catch(fe){console.error("Failed to generate negative tests:",fe),Pe.error(fe instanceof Error?fe.message:"Failed to generate negative test cases")}finally{f(!1)}},ce=()=>{m>=gl.length-1||te&&y(fe=>Math.min(fe+1,gl.length-1))},Te=()=>{m!==0&&y(fe=>Math.max(fe-1,0))},we=async()=>{if(!_){Pe.error("Please sign in to run evals");return}if(E.length===0){Pe.error("Please select at least one server"),y(0);return}if(I.length===0){Pe.error("Please select at least one model"),y(1);return}const fe={};for(const xe of I)if(!_r(xe.id)){const Ce=T(xe.provider);if(!Ce){Pe.error(`Please configure your ${xe.provider} API key in Settings`),y(1);return}fe[xe.provider]=Ce}if(re.length===0){Pe.error("Please add at least one test template with a query"),y(2);return}if(!z.trim()){X(!0);return}X(!1),t?n?.():(a(!1),window.location.hash="evals"),o(!0);try{const xe=await S(),Ce=re.flatMap(ot=>{const mt=crypto.randomUUID();return I.map(Bt=>({title:ot.title,query:ot.query,runs:ot.runs,model:Bt.id,provider:Bt.provider,expectedToolCalls:ot.expectedToolCalls,isNegativeTest:ot.isNegativeTest,scenario:ot.scenario,testTemplateKey:mt}))}),He=`Pass Criteria: Min ${V}% Accuracy`,Ze=await fetch(y1.EVALS_RUN,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({suiteName:z.trim(),suiteDescription:D.trim()||void 0,tests:Ce,serverIds:E,modelApiKeys:fe,convexAuthToken:xe,passCriteria:{minimumPassRate:V},notes:He})});if(!Ze.ok){let ot="Failed to start evals";try{ot=(await Ze.json()).error||ot}catch(mt){console.error("Failed to parse error response:",mt)}throw new Error(ot)}const st=await Ze.json();Pe.success(st.message||"Evals started successfully!"),Tr.capture("eval_suite_created",{location:"eval_runner",platform:Et(),environment:void 0,suite_id:st.suiteId,num_test_cases:re.length,num_models:I.length,num_servers:E.length}),O([_8()]),F(""),W(""),X(!1),y(3)}catch(xe){Pe.error(xe instanceof Error?xe.message:"Failed to start evals")}finally{o(!1)}},Oe=()=>{switch(gl[m].key){case"servers":return l.jsx(NWt,{connectedServers:Q,selectedServers:E,onToggleServer:Z});case"model":return l.jsx(CWt,{availableModels:e,selectedModels:I,modelTab:R,onModelTabChange:U,onToggleModel:ne,hasProviderToken:N});case"tests":return l.jsx(AWt,{testTemplates:$,availableTools:G,canGenerateTests:ee.servers&&ee.model,hasServerAndModelSelection:ee.servers&&ee.model,isGenerating:u,isGeneratingNegativeTests:d,onGenerateTests:ye,onGenerateNegativeTests:Ne,onAddTestTemplate:J,onAddNegativeTestTemplate:se,onRemoveTestTemplate:ie,onUpdateTestTemplate:he});case"review":return l.jsx(IWt,{suiteName:z,suiteDescription:D,minimumPassRate:V,selectedServers:E,selectedModels:I,validTestTemplates:re,onSuiteNameChange:F,onSuiteDescriptionChange:W,onMinimumPassRateChange:K,onEditStep:y,showNameError:q});default:return null}},Ue=l.jsx("ol",{className:"flex flex-col items-center gap-4 text-center md:flex-row md:gap-6",children:gl.map((fe,xe)=>{const Ce=m===xe,He=xe<m&&xe<=le,Ze=xe<=Math.max(le,m);return l.jsx("li",{className:"flex flex-col items-center gap-2",children:l.jsxs("button",{type:"button",onClick:()=>Ze?y(xe):void 0,disabled:!Ze,className:Ie("flex flex-col items-center gap-2 transition",!Ze&&"cursor-not-allowed opacity-60"),children:[l.jsx("span",{className:Ie("flex h-8 w-8 items-center justify-center rounded-full border text-sm font-medium",He&&"border-primary bg-primary text-primary-foreground",Ce&&!He&&"border-primary bg-primary/10 text-primary",!Ce&&!He&&"border-border text-muted-foreground"),children:xe+1}),l.jsx("span",{className:Ie("text-xs leading-tight",Ce?"text-foreground":"text-muted-foreground"),children:fe.title})]})},fe.key)})}),Me=m<gl.length-1?!te:s||!te,be=Me?"secondary":"default",je=()=>{if(!Me)return m===gl.length-1?"Start the eval run":"Continue to next step";if(m===2){const fe=re.some(Ce=>!Ce.isNegativeTest&&!hme(Ce.expectedToolCalls)),xe=re.some(Ce=>Ce.isNegativeTest&&(!Ce.scenario?.trim()||!Ce.query.trim()));if(fe)return"All tool names must be specified and argument values cannot be empty";if(xe)return"Negative tests require both a scenario description and user prompt"}return m===0?"Select at least one server to continue":m===1?"Select at least one model and ensure all models have API keys configured":m===2?"Add at least one test case with a query to continue":m===3?"Complete all required fields to start the eval run":"Complete the current step to continue"},Xe=()=>{t?n?.():a(!1)},ue=l.jsxs("div",{className:Ie("mx-auto flex w-full flex-col gap-8 pb-10 pt-4",t?"max-w-none px-4 sm:px-6 md:px-12 lg:px-32":"max-w-3xl px-4"),children:[l.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[t&&l.jsx(Ee,{type:"button",variant:"ghost",size:"icon",onClick:Xe,"aria-label":"Close",className:"h-8 w-8",children:l.jsx(Yn,{className:"h-4 w-4"})}),l.jsxs(Ee,{type:"button",variant:"outline",onClick:Te,disabled:m===0,"aria-label":"Back",className:"justify-center gap-2",children:[l.jsx(Dq,{className:"h-4 w-4"}),"Back"]}),l.jsx("div",{className:"flex flex-1 justify-center",children:l.jsx("div",{className:"max-w-xl",children:Ue})}),Me?l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsxs(Ee,{type:"button",variant:be,onClick:()=>{m<gl.length-1?(Tr.capture("eval_setup_next_step_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),ce()):(Tr.capture("eval_setup_start_eval_run_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),we())},disabled:Me,"aria-label":m===gl.length-1?"Start":"Next",className:Ie("justify-center gap-2",!Me&&"shadow-sm"),children:[m===gl.length-1?"Start":"Next",l.jsx(wr,{className:"h-4 w-4"})]})})}),l.jsx(zt,{children:je()})]}):l.jsxs(Ee,{type:"button",variant:be,onClick:()=>{m<gl.length-1?(Tr.capture("eval_setup_next_step_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),ce()):(Tr.capture("eval_setup_start_eval_run_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),we())},disabled:Me,"aria-label":m===gl.length-1?"Start":"Next",className:Ie("justify-center gap-2",!Me&&"shadow-sm"),children:[m===gl.length-1?"Start":"Next",l.jsx(wr,{className:"h-4 w-4"})]})]}),l.jsx("div",{className:"space-y-6",children:Oe()})]});return t?ue:l.jsxs(si,{open:i,onOpenChange:a,children:[l.jsx(r2e,{asChild:!0,children:l.jsxs(Ee,{children:[l.jsx(_o,{className:"mr-2 h-4 w-4"}),"New eval run"]})}),l.jsxs(oi,{className:"max-h-[80vh] w-full max-w-4xl overflow-y-auto sm:max-w-4xl",children:[l.jsxs(vi,{className:"mx-auto w-full max-w-3xl gap-1 text-left",children:[l.jsx(yi,{children:"Create eval run"}),l.jsx(us,{children:"Follow the guided steps to configure your evaluation and run it with confidence."})]}),ue]})]})}function RWt({testCases:e,suiteId:t,selectedTestId:n,isLoading:r,onCreateTestCase:i,onDeleteTestCase:a,onDuplicateTestCase:s,onGenerateTests:o,deletingTestCaseId:u,duplicatingTestCaseId:c,isGeneratingTests:d,showingOverview:f,noServerSelected:p,selectedServer:m,suite:y,onRerun:v,rerunningSuiteId:x,connectedServerNames:_}){const w=(y?.environment?.servers||[]).filter(A=>!_?.has(A)),T=w.length===0&&y&&v,N=x===y?._id,E=()=>{t&&_s({type:"suite-overview",suiteId:t})};return p?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"p-4 border-b",children:l.jsx("h2",{className:"text-sm font-semibold",children:"Test Cases"})}),l.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:l.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Select a server to view test cases."})})]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"p-4 border-b flex items-center justify-between",children:[l.jsxs("h2",{className:"text-sm font-semibold",children:["Test Cases",m&&l.jsxs("span",{className:"text-muted-foreground font-normal",children:[" ","[",m,"]"]})]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsx(Ee,{variant:"ghost",size:"sm",onClick:()=>{y&&v&&(Tr.capture("rerun_suite_button_clicked",{location:"test_case_list_sidebar",platform:Et(),environment:void 0}),v(y))},disabled:!T||N||e.length===0,className:"h-7 w-7 p-0",children:l.jsx(bU,{className:Ie("h-4 w-4",N&&"animate-spin")})})})}),l.jsx(zt,{children:e.length===0?"Add test cases first":!T&&w.length>0?`Connect the following servers: ${w.join(", ")}`:N?"Running...":"Run all tests"})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsx(Ee,{variant:"ghost",size:"sm",onClick:()=>{o&&(Tr.capture("generate_tests_button_clicked",{location:"test_case_list_sidebar",platform:Et(),environment:void 0}),o())},disabled:d||!o,className:"h-7 w-7 p-0",children:l.jsx(D1e,{className:Ie("h-4 w-4",d&&"animate-pulse")})})})}),l.jsx(zt,{children:d?"Generating...":"Generate test cases with AI"})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:"ghost",size:"sm",onClick:()=>{Tr.capture("create_test_case_button_clicked",{location:"test_case_list_sidebar",platform:Et(),environment:void 0}),i()},className:"h-7 w-7 p-0",children:l.jsx(_o,{className:"h-4 w-4"})})}),l.jsx(zt,{children:"Create new test case"})]})]})]}),t&&l.jsxs("div",{onClick:E,className:Ie("flex items-center gap-2 px-4 py-2.5 text-sm cursor-pointer transition-colors border-b","hover:bg-accent/50",f&&"bg-accent font-medium"),children:[l.jsx(T1e,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{children:"Results & Runs"})]}),l.jsx("div",{className:"flex-1 overflow-y-auto",children:r?l.jsx("div",{className:"p-4 text-center text-xs text-muted-foreground",children:"Loading test cases..."}):d?l.jsxs("div",{className:"p-4 flex flex-col items-center justify-center gap-2 text-xs text-muted-foreground",children:[l.jsx(Pn,{className:"h-5 w-5 animate-spin"}),l.jsx("span",{children:"Generating test cases..."})]}):e.length===0?l.jsx("div",{className:"p-4 text-center text-xs text-muted-foreground",children:"No test cases yet"}):l.jsx("div",{className:"py-2",children:e.map(A=>{const I=n===A._id,M=u===A._id,$=c===A._id;return l.jsxs("div",{onClick:()=>{t&&_s({type:"test-edit",suiteId:t,testId:A._id})},className:Ie("group w-full flex items-center gap-1 px-4 py-2 text-left text-sm hover:bg-accent/50 transition-colors cursor-pointer",I&&"bg-accent font-medium"),children:[l.jsxs("div",{className:"flex-1 min-w-0 text-left flex items-center gap-1.5",children:[l.jsx("span",{className:"truncate",children:A.title}),A.isNegativeTest&&l.jsx("span",{className:"text-[10px] text-orange-500 shrink-0",title:"Negative test",children:"NEG"})]}),l.jsxs(Ic,{children:[l.jsx(jc,{asChild:!0,children:l.jsx("button",{onClick:O=>O.stopPropagation(),className:"shrink-0 p-1 hover:bg-accent/50 rounded transition-colors opacity-0 group-hover:opacity-100","aria-label":"Test case options",children:l.jsx(A1e,{className:"h-4 w-4"})})}),l.jsxs(Oc,{align:"end",children:[l.jsxs(Oi,{onClick:O=>{O.stopPropagation(),s(A._id)},disabled:$,children:[l.jsx(Ca,{className:"h-4 w-4 mr-2 text-foreground"}),$?"Duplicating...":"Duplicate"]}),l.jsxs(Oi,{onClick:O=>{O.stopPropagation(),a(A._id,A.title)},disabled:M,variant:"destructive",children:[l.jsx(Ll,{className:"h-4 w-4 mr-2"}),M?"Deleting...":"Delete"]})]})]})]},A._id)})})})]})}const w8="skipDeleteTestCaseConfirmation";function PWt({suiteToDelete:e,setSuiteToDelete:t,deletingSuiteId:n,onConfirmDeleteSuite:r,runToDelete:i,setRunToDelete:a,deletingRunId:s,onConfirmDeleteRun:o,testCaseToDelete:u,setTestCaseToDelete:c,deletingTestCaseId:d,onConfirmDeleteTestCase:f}){const[p,m]=b.useState(!1);b.useEffect(()=>{u&&localStorage.getItem(w8)==="true"&&f()},[u,f]);const y=()=>{p&&localStorage.setItem(w8,"true"),f()},v=localStorage.getItem(w8)==="true";return l.jsxs(l.Fragment,{children:[l.jsx(si,{open:!!e,onOpenChange:x=>!x&&t(null),children:l.jsxs(oi,{children:[l.jsxs(vi,{children:[l.jsxs(yi,{className:"flex items-center gap-2",children:[l.jsx(wo,{className:"h-5 w-5 text-destructive"}),"Delete Test Suite"]}),l.jsxs(us,{children:["Are you sure you want to delete the test suite?",l.jsx("br",{}),l.jsx("br",{})]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:()=>t(null),disabled:!!n,children:"Cancel"}),l.jsx(Ee,{variant:"destructive",onClick:r,disabled:!!n,children:n?"Deleting...":"Delete Suite"})]})]})}),l.jsx(si,{open:!!i,onOpenChange:x=>!x&&a(null),children:l.jsxs(oi,{children:[l.jsxs(vi,{children:[l.jsxs(yi,{className:"flex items-center gap-2",children:[l.jsx(wo,{className:"h-5 w-5 text-destructive"}),"Delete Run"]}),l.jsxs(us,{children:["Are you sure you want to delete this run?",l.jsx("br",{}),l.jsx("br",{}),"This will permanently delete all iterations and results associated with this run. This action cannot be undone."]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:()=>a(null),disabled:!!s,children:"Cancel"}),l.jsx(Ee,{variant:"destructive",onClick:o,disabled:!!s,children:s?"Deleting...":"Delete Run"})]})]})}),!v&&l.jsx(si,{open:!!u,onOpenChange:x=>!x&&c(null),children:l.jsxs(oi,{children:[l.jsxs(vi,{children:[l.jsxs(yi,{className:"flex items-center gap-2",children:[l.jsx(wo,{className:"h-5 w-5 text-destructive"}),"Delete Test Case"]}),l.jsx(us,{children:"Are you sure you want to delete the test case?"})]}),l.jsxs(Js,{className:"flex-row items-center sm:justify-between",children:[l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Hw,{id:"dont-show-delete-test-case",checked:p,onCheckedChange:x=>m(x===!0)}),l.jsx(Zn,{htmlFor:"dont-show-delete-test-case",className:"text-sm text-muted-foreground cursor-pointer",children:"Do not show this again"})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Ee,{variant:"outline",onClick:()=>c(null),disabled:!!d,children:"Cancel"}),l.jsx(Ee,{variant:"destructive",onClick:y,disabled:!!d,children:d?"Deleting...":"Delete Test Case"})]})]})]})})]})}function mme({isAuthenticated:e,user:t,selectedSuiteId:n,deletingSuiteId:r}){const i=e&&!!t,a=Ua("testSuites:getTestSuitesOverview",i?{}:"skip"),s=e&&!!t&&!!n&&r!==n,o=Ua("testSuites:getAllTestCasesAndIterationsBySuite",s?{suiteId:n}:"skip"),u=Ua("testSuites:listTestSuiteRuns",s?{suiteId:n,limit:20}:"skip"),c=a===void 0,d=s&&o===void 0,f=s&&u===void 0,p=b.useMemo(()=>!n||!a?null:a.find(S=>S.suite._id===n)??null,[n,a]),m=p?.suite??null,y=b.useMemo(()=>o?[...o.iterations].sort((S,w)=>(w.startedAt||w.createdAt)-(S.startedAt||S.createdAt)):[],[o]),v=b.useMemo(()=>u?[...u]:[],[u]),x=b.useMemo(()=>{if(!u||y.length===0)return y;const S=new Set(u.filter(w=>w.isActive!==!1).map(w=>w._id));return y.filter(w=>!w.suiteRunId||S.has(w.suiteRunId))},[y,u]),_=b.useMemo(()=>a?[...a].sort((S,w)=>{const T=S.suite.updatedAt??S.latestRun?.completedAt??S.latestRun?.createdAt??S.suite._creationTime??0;return(w.suite.updatedAt??w.latestRun?.completedAt??w.latestRun?.createdAt??w.suite._creationTime??0)-T}):[],[a]);return{suiteOverview:a,suiteDetails:o,suiteRuns:u,selectedSuiteEntry:p,selectedSuite:m,sortedIterations:y,runsForSelectedSuite:v,activeIterations:x,sortedSuites:_,isOverviewLoading:c,isSuiteDetailsLoading:d,isSuiteRunsLoading:f,enableOverviewQuery:i,enableSuiteDetailsQuery:s}}function $Wt(){const e=_n("testSuites:deleteTestSuite"),t=_n("testSuites:deleteTestSuiteRun"),n=_n("testSuites:cancelTestSuiteRun"),r=_n("testSuites:duplicateTestSuite"),i=_n("testSuites:createTestCase"),a=_n("testSuites:deleteTestCase"),s=_n("testSuites:duplicateTestCase"),o=_n("testSuites:createTestSuite");return{deleteSuiteMutation:e,deleteRunMutation:t,cancelRunMutation:n,duplicateSuiteMutation:r,createTestCaseMutation:i,deleteTestCaseMutation:a,duplicateTestCaseMutation:s,createTestSuiteMutation:o}}function MWt({mutations:e,selectedSuiteEntry:t,selectedSuiteId:n,selectedTestId:r}){const i=gve(),{getAccessToken:a}=Aa(),{getToken:s,hasToken:o}=zx(),[u,c]=b.useState(null),[d,f]=b.useState(null),[p,m]=b.useState(null),[y,v]=b.useState(null),[x,_]=b.useState(null),[S,w]=b.useState(null),[T,N]=b.useState(null),[E,A]=b.useState(!1),[I,M]=b.useState(null),[$,O]=b.useState(null),[R,U]=b.useState(null),[z,F]=b.useState(!1),D=b.useCallback(async le=>{try{return await i.query("testSuites:listTestCases",{suiteId:le})}catch(te){return console.error("Failed to fetch test cases:",te),[]}},[i]),W=b.useCallback(async le=>{if(u)return;const te=le.environment?.servers||[],Z=await D(le._id);if(!Z||Z.length===0){Pe.error("No test cases found in this suite");return}const ne=[];for(const ie of Z)if(!(!ie.models||ie.models.length===0))for(const he of ie.models)ne.push({title:ie.title,query:ie.query,runs:ie.runs||1,model:he.model,provider:he.provider,expectedToolCalls:ie.expectedToolCalls||[],isNegativeTest:ie.isNegativeTest,scenario:ie.scenario,advancedConfig:ie.advancedConfig,testCaseId:ie._id});if(ne.length===0){Pe.error("No tests to run. Please add models to your test cases.");return}const J={},se=new Set;for(const ie of ne)_r(ie.model)||se.add(ie.provider);for(const ie of se){const he=ie.toLowerCase();if(!o(he)){Pe.error(`Please add your ${ie} API key in Settings before running evals`);return}const ye=s(he);ye&&(J[ie]=ye)}c(le._id),Pe.success("Run started successfully! Results will appear shortly.");try{const ie=await a(),he=le.defaultPassCriteria?.minimumPassRate,ye=t?.latestRun,Ne=he??ye?.passCriteria?.minimumPassRate??100,ce=`Pass Criteria: Min ${Ne}% Accuracy`,Te=await Yt("/api/mcp/evals/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({suiteId:le._id,suiteName:le.name,suiteDescription:le.description,tests:ne.map(we=>({title:we.title,query:we.query,runs:we.runs??1,model:we.model,provider:we.provider,expectedToolCalls:we.expectedToolCalls,isNegativeTest:we.isNegativeTest,scenario:we.scenario,advancedConfig:we.advancedConfig})),serverIds:te,modelApiKeys:Object.keys(J).length>0?J:void 0,convexAuthToken:ie,passCriteria:{minimumPassRate:Ne},notes:ce})});if(!Te.ok){const we=await Te.text();throw new Error(we||"Failed to start eval run")}Tr.capture("eval_suite_run_started",{location:"evals_tab",platform:Et(),environment:void 0,suite_id:le._id,num_test_cases:Z.length,num_tests:ne.length,num_models:se.size,minimum_pass_rate:Ne}),Pe.success("Eval run completed!")}catch(ie){console.error("Failed to rerun evals:",ie),Pe.error(ie instanceof Error?ie.message:"Failed to start eval run")}finally{c(null)}},[u,t,a,o,s,D]),q=b.useCallback(le=>{p||v(le)},[p]),X=b.useCallback(async()=>{if(!(!y||p)){m(y._id);try{await e.deleteSuiteMutation({suiteId:y._id}),Pe.success("Test suite deleted successfully"),n===y._id&&_s({type:"list"}),v(null)}catch(le){console.error("Failed to delete suite:",le),Pe.error(le instanceof Error?le.message:"Failed to delete test suite")}finally{m(null)}}},[y,p,e.deleteSuiteMutation,n]),L=b.useCallback(async le=>{if(!x){_(le._id);try{const te=await e.duplicateSuiteMutation({suiteId:le._id});Pe.success("Test suite duplicated successfully"),te&&te._id&&Tr.capture("eval_suite_duplicated",{location:"evals_tab",platform:Et(),environment:void 0,original_suite_id:le._id,new_suite_id:te._id}),te&&te._id&&_s({type:"suite-overview",suiteId:te._id})}catch(te){console.error("Failed to duplicate suite:",te),Pe.error(te instanceof Error?te.message:"Failed to duplicate test suite")}finally{_(null)}}},[x,e.duplicateSuiteMutation]),Y=b.useCallback(async le=>{if(!d){f(le);try{await e.cancelRunMutation({runId:le}),Pe.success("Run cancelled successfully")}catch(te){console.error("Failed to cancel run:",te),Pe.error(te instanceof Error?te.message:"Failed to cancel run")}finally{f(null)}}},[d,e.cancelRunMutation]),G=b.useCallback(le=>{S||N(le)},[S]),P=b.useCallback(async le=>{try{await e.deleteRunMutation({runId:le})}catch(te){throw console.error("Failed to delete run:",te),te}},[e.deleteRunMutation]),V=b.useCallback(async()=>{if(!(!T||S)){w(T);try{await e.deleteRunMutation({runId:T}),Pe.success("Run deleted successfully"),N(null)}catch(le){console.error("Failed to delete run:",le),Pe.error(le instanceof Error?le.message:"Failed to delete run")}finally{w(null)}}},[T,S,e.deleteRunMutation]),K=b.useCallback(async le=>{if(!E){A(!0);try{const te=await i.query("testSuites:listTestCases",{suiteId:le});let Z=[];if(te&&Array.isArray(te)&&te.length>0){const J=new Map;for(const se of te)if(se.models&&Array.isArray(se.models)){for(const ie of se.models)if(ie.model&&ie.provider){const he=`${ie.provider}:${ie.model}`;J.has(he)||J.set(he,{model:ie.model,provider:ie.provider})}}Z=Array.from(J.values())}Z.length===0&&(Z=[{model:"anthropic/claude-haiku-4.5",provider:"anthropic"}]);const ne=await e.createTestCaseMutation({suiteId:le,title:"Untitled test case",query:"",models:Z});return Pe.success("Test case created"),Tr.capture("eval_test_case_created",{location:"evals_tab",platform:Et(),environment:void 0,suite_id:le,test_case_id:ne,num_models:Z.length}),_s({type:"test-detail",suiteId:le,testId:ne}),ne}catch(te){return console.error("Failed to create test case:",te),Pe.error(te instanceof Error?te.message:"Failed to create test case"),null}finally{A(!1)}}},[E,e.createTestCaseMutation,i]),Q=b.useCallback((le,te)=>{I||U({id:le,title:te})},[I]),oe=b.useCallback(async()=>{if(!(!R||I)){M(R.id);try{await e.deleteTestCaseMutation({testCaseId:R.id}),Pe.success("Test case deleted successfully"),r===R.id&&n&&_s({type:"suite-overview",suiteId:n}),U(null)}catch(le){console.error("Failed to delete test case:",le),Pe.error(le instanceof Error?le.message:"Failed to delete test case")}finally{M(null)}}},[R,I,e.deleteTestCaseMutation,r,n]),re=b.useCallback(async(le,te)=>{if(!$){O(le);try{const Z=await e.duplicateTestCaseMutation({testCaseId:le});return Pe.success("Test case duplicated successfully"),Z&&Z._id&&Tr.capture("eval_test_case_duplicated",{location:"evals_tab",platform:Et(),environment:void 0,suite_id:te,original_test_case_id:le,new_test_case_id:Z._id}),Z&&Z._id&&_s({type:"test-edit",suiteId:te,testId:Z._id}),Z}catch(Z){return console.error("Failed to duplicate test case:",Z),Pe.error(Z instanceof Error?Z.message:"Failed to duplicate test case"),null}finally{O(null)}}},[$,e.duplicateTestCaseMutation]),ee=b.useCallback(async(le,te)=>{if(!z){F(!0);try{const Z=await a(),ne=await i.query("testSuites:listTestCases",{suiteId:le});let J=[];if(ne&&Array.isArray(ne)&&ne.length>0){const ye=new Map;for(const Ne of ne)if(Ne.models&&Array.isArray(Ne.models)){for(const ce of Ne.models)if(ce.model&&ce.provider){const Te=`${ce.provider}:${ce.model}`;ye.has(Te)||ye.set(Te,{model:ce.model,provider:ce.provider})}}J=Array.from(ye.values())}J.length===0&&(J=[{model:"anthropic/claude-haiku-4.5",provider:"anthropic"}]);const se=await Yt(y1.EVALS_GENERATE_TESTS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:te,convexAuthToken:Z})}),ie=await se.json();if(!se.ok)throw new Error(ie.error||"Failed to generate tests");if(!ie.tests||ie.tests.length===0){Pe.info("No test cases were generated");return}let he=0;for(const ye of ie.tests)try{await e.createTestCaseMutation({suiteId:le,title:ye.title||"Generated test",query:ye.query||"",models:J,expectedToolCalls:ye.expectedToolCalls||[],runs:ye.runs||1,isNegativeTest:ye.isNegativeTest||!1,scenario:ye.scenario,expectedOutput:ye.expectedOutput}),he++}catch(Ne){console.error("Failed to create test case:",Ne)}he>0&&(Pe.success(`Generated ${he} test case${he>1?"s":""}`),Tr.capture("eval_tests_generated_from_sidebar",{location:"test_case_list_sidebar",platform:Et(),environment:void 0,suite_id:le,generated_count:he}))}catch(Z){console.error("Failed to generate tests:",Z),Pe.error(Z instanceof Error?Z.message:"Failed to generate test cases")}finally{F(!1)}}},[z,a,i,e.createTestCaseMutation]);return{handleRerun:W,handleDelete:q,confirmDelete:X,handleDuplicateSuite:L,handleCancelRun:Y,handleDeleteRun:G,directDeleteRun:P,confirmDeleteRun:V,handleCreateTestCase:K,handleDeleteTestCase:Q,confirmDeleteTestCase:oe,handleDuplicateTestCase:re,handleGenerateTests:ee,rerunningSuiteId:u,cancellingRunId:d,deletingSuiteId:p,suiteToDelete:y,setSuiteToDelete:v,duplicatingSuiteId:x,deletingRunId:S,runToDelete:T,setRunToDelete:N,isCreatingTestCase:E,deletingTestCaseId:I,duplicatingTestCaseId:$,testCaseToDelete:R,setTestCaseToDelete:U,isGeneratingTests:z}}function DWt({selectedServer:e}){const{isAuthenticated:t,isLoading:n}=Ba(),{user:r}=Aa(),i=OPt(),a=i.type==="test-detail"||i.type==="test-edit"?i.testId:null,s=i.type==="test-edit"?i.testId:null,{availableModels:o}=PPt({systemPrompt:"",temperature:1,selectedServers:[]}),u=Rx(),c=b.useMemo(()=>new Set(Object.entries(u.servers).filter(([,D])=>D.connectionStatus==="connected").map(([D])=>D)),[u.servers]),d=$Wt(),f=mme({isAuthenticated:t,user:r,selectedSuiteId:null,deletingSuiteId:null}),p=e&&e!=="none"&&u.servers[e]?.connectionStatus==="connected",m=b.useMemo(()=>p?f.sortedSuites.find(D=>D.suite.environment?.servers?.[0]===e):null,[f.sortedSuites,e,p]),y=m?.suite??null,v=y?._id??null,x=MWt({mutations:d,selectedSuiteEntry:m??null,selectedSuiteId:v,selectedTestId:a}),_=mme({isAuthenticated:t,user:r,selectedSuiteId:v,deletingSuiteId:x.deletingSuiteId}),{selectedSuite:S,suiteDetails:w,sortedIterations:T,runsForSelectedSuite:N,activeIterations:E,isOverviewLoading:A,isSuiteDetailsLoading:I,isSuiteRunsLoading:M,enableOverviewQuery:$}=_;b.useEffect(()=>{Tr.capture("evals_tab_viewed",{location:"evals_tab",platform:Et(),environment:void 0})},[]);const O=b.useMemo(()=>!S||!w?null:FPt(S,w.testCases,E),[S,w,E]),R=b.useCallback(D=>{_s(D?{type:"suite-overview",suiteId:D}:{type:"list"})},[]),U=b.useCallback(async()=>{let D=v;if(!D&&e&&p)try{D=(await d.createTestSuiteMutation({name:e,description:`Test suite for ${e}`,environment:{servers:[e]}}))?._id}catch(W){console.error("Failed to create suite:",W),Pe.error("Failed to create test case. Please try again.");return}D&&await x.handleCreateTestCase(D)},[v,e,p,d.createTestSuiteMutation,x.handleCreateTestCase]),z=b.useCallback(D=>{v&&x.handleDuplicateTestCase(D,v)},[v,x.handleDuplicateTestCase]),F=b.useCallback(async()=>{if(!e||!p)return;let D=v;if(!D)try{D=(await d.createTestSuiteMutation({name:e,description:`Test suite for ${e}`,environment:{servers:[e]}}))?._id}catch(W){console.error("Failed to create suite:",W),Pe.error("Failed to generate tests. Please try again.");return}D&&await x.handleGenerateTests(D,[e])},[v,e,p,d.createTestSuiteMutation,x.handleGenerateTests]);return n?l.jsx("div",{className:"p-6",children:l.jsx("div",{className:"flex min-h-[calc(100vh-200px)] items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading..."})]})})}):!t||!r?l.jsx("div",{className:"p-6",children:l.jsx(Rc,{icon:T1,title:"Sign in to use evals",description:"Create an account or sign in to run evaluations and view results.",className:"h-[calc(100vh-200px)]"})}):A&&$&&i.type!=="create"?l.jsx("div",{className:"p-6",children:l.jsx("div",{className:"flex min-h-[calc(100vh-200px)] items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading your eval data..."})]})})}):l.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[i.type==="create"?l.jsx("div",{className:"flex-1 overflow-y-auto px-6 pb-6 pt-6",children:l.jsx(OWt,{availableModels:o,inline:!0,onSuccess:R,preselectedServer:e})}):l.jsxs(Bc,{direction:"horizontal",className:"flex-1 overflow-hidden",children:[l.jsx(ta,{defaultSize:30,minSize:15,maxSize:40,className:"border-r bg-muted/30 flex flex-col",children:l.jsx(RWt,{testCases:w?.testCases||[],suiteId:v,selectedTestId:s,isLoading:I,onCreateTestCase:U,onDeleteTestCase:x.handleDeleteTestCase,onDuplicateTestCase:z,onGenerateTests:F,deletingTestCaseId:x.deletingTestCaseId,duplicatingTestCaseId:x.duplicatingTestCaseId,isGeneratingTests:x.isGeneratingTests,showingOverview:!s&&v!==null,noServerSelected:!p,selectedServer:e,suite:S,onRerun:x.handleRerun,rerunningSuiteId:x.rerunningSuiteId,connectedServerNames:c})}),l.jsx($u,{withHandle:!0}),l.jsx(ta,{defaultSize:70,className:"flex flex-col overflow-hidden",children:p?y?I?l.jsx("div",{className:"flex h-full items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading test cases..."})]})}):S?l.jsx("div",{className:"flex-1 overflow-y-auto px-6 pb-6 pt-6",children:l.jsx(EWt,{suite:S,cases:w?.testCases||[],iterations:E,allIterations:T,runs:N,runsLoading:M,aggregate:O,onRerun:x.handleRerun,onCancelRun:x.handleCancelRun,onDelete:x.handleDelete,onDeleteRun:x.handleDeleteRun,onDirectDeleteRun:x.directDeleteRun,connectedServerNames:c,rerunningSuiteId:x.rerunningSuiteId,cancellingRunId:x.cancellingRunId,deletingSuiteId:x.deletingSuiteId,deletingRunId:x.deletingRunId,availableModels:o,route:i})}):null:l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsxs("div",{className:"text-center max-w-md mx-auto p-8",children:[l.jsx("div",{className:"w-20 h-20 bg-muted rounded-full flex items-center justify-center mx-auto mb-6",children:l.jsx(T1,{className:"h-10 w-10 text-muted-foreground"})}),l.jsx("h2",{className:"text-2xl font-semibold text-foreground mb-2",children:"No test cases yet"}),l.jsxs("p",{className:"text-sm text-muted-foreground mb-6",children:['Create your first test case for "',e,'" to start evaluating your MCP server.']})]})}):l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsxs("div",{className:"text-center max-w-md mx-auto p-8",children:[l.jsx("div",{className:"w-20 h-20 bg-muted rounded-full flex items-center justify-center mx-auto mb-6",children:l.jsx(T1,{className:"h-10 w-10 text-muted-foreground"})}),l.jsx("h2",{className:"text-2xl font-semibold text-foreground mb-2",children:"Select a server"}),l.jsx("p",{className:"text-sm text-muted-foreground mb-6",children:"Choose a server from the tabs above to view and manage its test cases."})]})})})]}),l.jsx(PWt,{suiteToDelete:x.suiteToDelete,setSuiteToDelete:x.setSuiteToDelete,deletingSuiteId:x.deletingSuiteId,onConfirmDeleteSuite:x.confirmDelete,runToDelete:x.runToDelete,setRunToDelete:x.setRunToDelete,deletingRunId:x.deletingRunId,onConfirmDeleteRun:x.confirmDeleteRun,testCaseToDelete:x.testCaseToDelete,setTestCaseToDelete:x.setTestCaseToDelete,deletingTestCaseId:x.deletingTestCaseId,onConfirmDeleteTestCase:x.confirmDeleteTestCase})]})}function LWt({views:e,selectedViewId:t,onSelectView:n,onEditView:r,onDuplicateView:i,onDeleteView:a,deletingViewId:s,duplicatingViewId:o,isLoading:u}){return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"p-4 border-b",children:l.jsx("h2",{className:"text-sm font-semibold",children:"Views"})}),l.jsx("div",{className:"flex-1 overflow-y-auto",children:u?l.jsx("div",{className:"p-4 text-center text-xs text-muted-foreground",children:"Loading views..."}):e.length===0?l.jsx("div",{className:"p-4 text-center text-xs text-muted-foreground",children:"No views yet"}):l.jsx("div",{className:"py-1",children:e.map(c=>{const d=t===c._id,f=s===c._id,p=o===c._id;return l.jsxs("div",{onClick:()=>n(c._id),className:Ie("group flex items-center gap-3 px-4 py-3 cursor-pointer transition-colors",d?"bg-accent":"hover:bg-accent/50"),children:[l.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[l.jsx("span",{className:Ie("text-sm truncate",d?"font-medium":"font-normal"),children:c.name}),l.jsx("span",{className:"text-xs text-muted-foreground truncate shrink-0",children:c.toolName})]}),l.jsxs("div",{className:Ie("flex items-center gap-0.5 shrink-0 transition-opacity",d?"opacity-100":"opacity-0 group-hover:opacity-100"),children:[l.jsx(Ee,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:m=>{m.stopPropagation(),r(c)},"aria-label":"Edit view",children:l.jsx(Fq,{className:"h-3.5 w-3.5"})}),l.jsx(Ee,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:m=>{m.stopPropagation(),i(c)},disabled:p,"aria-label":"Duplicate view",children:l.jsx(Ca,{className:"h-3.5 w-3.5"})}),l.jsx(Ee,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:m=>{m.stopPropagation(),a(c)},disabled:f,"aria-label":"Delete view",children:l.jsx(Ll,{className:"h-3.5 w-3.5"})})]})]},c._id)})})})]})}function zWt({view:e,displayMode:t="inline",onDisplayModeChange:n,serverName:r,serverConnectionStatus:i,toolInputOverride:a,toolOutputOverride:s,widgetStateOverride:o,isLoadingOverride:u,toolOutputErrorOverride:c}){const[d,f]=b.useState(null),[p,m]=b.useState(!0),[y,v]=b.useState(null),x=i!=="connected",_=a!==void 0?a:e.toolInput,S=s!==void 0?s:d,w=u!==void 0?u:p,T=c!==void 0?c:y;b.useEffect(()=>{if(s!==void 0){m(!1),v(null);return}async function $(){if(!e.toolOutputUrl){f(null),m(!1),v("No output URL available");return}m(!0),v(null);try{const O=await fetch(e.toolOutputUrl);if(!O.ok)throw new Error(`Failed to fetch output: ${O.status}`);const R=await O.json();f(R)}catch(O){console.error("Failed to load output:",O),v(O instanceof Error?O.message:"Failed to load output"),f(null)}finally{m(!1)}}$()},[e.toolOutputUrl,e._id,s]);const N=b.useCallback(()=>{},[]),E=b.useCallback(async()=>({}),[]),A=b.useCallback(()=>{},[]),I=b.useCallback(()=>{},[]),M=b.useMemo(()=>`view-preview-${e._id}`,[e._id]);if(w)return l.jsxs("div",{className:"flex items-center justify-center p-8 text-muted-foreground",children:[l.jsx(Pn,{className:"h-6 w-6 animate-spin mr-2"}),"Loading preview..."]});if(!S)return l.jsxs("div",{className:"flex items-center justify-center p-8 text-destructive",children:[l.jsx(Gs,{className:"h-5 w-5 mr-2"}),T||"No output data available"]});if(!r)return l.jsxs("div",{className:"flex items-center justify-center p-8 text-destructive",children:[l.jsx(Gs,{className:"h-5 w-5 mr-2"}),"Server not found. The server that created this view may have been deleted."]});if(e.protocol==="mcp-apps"){const $=e;return l.jsx("div",{className:"relative",children:l.jsx(yK,{serverId:r,toolCallId:M,toolName:e.toolName,toolState:e.toolState,toolInput:_,toolOutput:S,toolErrorText:e.toolErrorText,resourceUri:$.resourceUri,toolMetadata:e.toolMetadata,toolsMetadata:$.toolsMetadata,onSendFollowUp:N,onCallTool:E,onWidgetStateChange:A,onModelContextUpdate:I,displayMode:t,onDisplayModeChange:n,pipWidgetId:null,fullscreenWidgetId:null,isOffline:x,cachedWidgetHtmlUrl:$.widgetHtmlUrl??void 0},M)})}if(e.protocol==="openai-apps"){const $=e,O=o!==void 0?o:$.widgetState,R=e.toolMetadata,U=$.outputTemplate||R?.["openai/outputTemplate"]||"",z={...R,...U?{"openai/outputTemplate":U}:{}};return l.jsx(vK,{serverId:r,toolCallId:M,toolName:e.toolName,toolState:e.toolState,toolInput:_,toolOutput:S,toolMetadata:z,onSendFollowUp:N,onCallTool:E,onWidgetStateChange:A,serverInfo:$.serverInfo,initialWidgetState:O,displayMode:t,onDisplayModeChange:n,pipWidgetId:null,fullscreenWidgetId:null,isOffline:x,cachedWidgetHtmlUrl:$.widgetHtmlUrl??void 0},M)}return l.jsxs("div",{className:"flex items-center justify-center p-8 text-muted-foreground",children:["Unknown protocol: ",e.protocol]})}const UWt=[{label:"Light",value:"light"},{label:"Dark",value:"dark"}];UWt.map(e=>e.value);const I5e=[{label:"Default",value:"default",primary:{light:"oklch(0.205 0 0)",dark:"oklch(0.922 0 0)"}},{label:"Brutalist",value:"brutalist",primary:{light:"oklch(0.6489 0.2370 26.9728)",dark:"oklch(0.7044 0.1872 23.1858)"}},{label:"Soft Pop",value:"soft-pop",primary:{light:"oklch(0.5106 0.2301 276.9656)",dark:"oklch(0.6801 0.1583 276.9349)"}},{label:"Tangerine",value:"tangerine",primary:{light:"oklch(0.64 0.17 36.44)",dark:"oklch(0.64 0.17 36.44)"}}];I5e.map(e=>e.value);function FWt(){try{const e=localStorage.getItem(yPe);if(e==="dark"||e==="light")return e}catch(e){console.warn("Cannot access localStorage for theme mode:",e)}return"light"}function RZ(e){const t=document.documentElement;t.classList.add("disable-transitions"),t.classList.toggle("dark",e==="dark"),requestAnimationFrame(()=>{t.classList.remove("disable-transitions")})}function BWt(){try{const e=localStorage.getItem(xPe),t=I5e.map(n=>n.value);if(e&&t.includes(e))return e}catch(e){console.warn("Cannot access localStorage for theme preset:",e)}return"default"}function qWt(e){document.documentElement.setAttribute("data-theme-preset",e)}const gme=[{preset:"none",label:"None",shortLabel:"None"},{preset:"iphone-notch",label:"iPhone Notch",shortLabel:"Notch"},{preset:"iphone-dynamic-island",label:"Dynamic Island",shortLabel:"Island"},{preset:"android-gesture",label:"Android",shortLabel:"Android"}];function HWt({insets:e}){const t=e.top>0||e.bottom>0||e.left>0||e.right>0;return l.jsxs("div",{className:"relative w-full h-[140px] rounded-lg border-2 border-dashed border-border overflow-hidden bg-muted/30",children:[e.top>0&&l.jsx("div",{className:"absolute top-0 left-0 right-0 bg-destructive/20 border-b border-dashed border-destructive/40 flex items-center justify-center",style:{height:`${Math.min(e.top*.8,40)}px`},children:l.jsxs("span",{className:"text-[9px] text-muted-foreground font-medium",children:[e.top,"px"]})}),e.bottom>0&&l.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-destructive/20 border-t border-dashed border-destructive/40 flex items-center justify-center",style:{height:`${Math.min(e.bottom*.8,40)}px`},children:l.jsxs("span",{className:"text-[9px] text-muted-foreground font-medium",children:[e.bottom,"px"]})}),e.left>0&&l.jsx("div",{className:"absolute left-0 bg-destructive/20 border-r border-dashed border-destructive/40 flex items-center justify-center",style:{width:`${Math.min(e.left*.8,30)}px`,top:`${Math.min(e.top*.8,40)}px`,bottom:`${Math.min(e.bottom*.8,40)}px`},children:l.jsx("span",{className:"text-[9px] text-muted-foreground font-medium writing-mode-vertical",children:e.left})}),e.right>0&&l.jsx("div",{className:"absolute right-0 bg-destructive/20 border-l border-dashed border-destructive/40 flex items-center justify-center",style:{width:`${Math.min(e.right*.8,30)}px`,top:`${Math.min(e.top*.8,40)}px`,bottom:`${Math.min(e.bottom*.8,40)}px`},children:l.jsx("span",{className:"text-[9px] text-muted-foreground font-medium writing-mode-vertical",children:e.right})}),l.jsx("div",{className:"absolute bg-green-500/10 border border-dashed border-green-500/40 flex items-center justify-center",style:{top:`${Math.min(e.top*.8,40)}px`,bottom:`${Math.min(e.bottom*.8,40)}px`,left:`${Math.min(e.left*.8,30)}px`,right:`${Math.min(e.right*.8,30)}px`},children:l.jsx("span",{className:"text-[10px] text-muted-foreground",children:t?"Safe Content Area":"No Insets"})})]})}function ON({label:e,value:t,onChange:n}){return l.jsxs("div",{className:"flex flex-col items-center gap-1",children:[l.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:e}),l.jsxs("div",{className:"relative",children:[l.jsx(Ct,{type:"number",min:0,max:100,value:t,onChange:r=>n(Math.max(0,parseInt(r.target.value)||0)),className:"w-16 h-7 text-xs text-center pr-5 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),l.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-[10px] text-muted-foreground",children:"px"})]})]})}function vme(){const e=Zt(s=>s.safeAreaPreset),t=Zt(s=>s.safeAreaInsets),n=Zt(s=>s.setSafeAreaPreset),r=Zt(s=>s.setSafeAreaInsets),i=(s,o)=>{r({[s]:o})},a=t.top>0||t.bottom>0||t.left>0||t.right>0;return l.jsxs(qo,{children:[l.jsx(Sl,{asChild:!0,children:l.jsx(Ee,{variant:a?"secondary":"ghost",size:"icon",className:"h-7 w-7",children:l.jsx(SQe,{className:"h-3.5 w-3.5"})})}),l.jsx(Ho,{className:"w-[280px] p-3",align:"start",children:l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Safe Area"}),e!=="none"&&e!=="custom"&&l.jsx("span",{className:"text-[10px] text-muted-foreground",children:gme.find(s=>s.preset===e)?.label})]}),l.jsx(HWt,{insets:t}),l.jsx("div",{className:"flex gap-1",children:gme.map(s=>l.jsx(Ee,{variant:e===s.preset?"secondary":"ghost",size:"sm",onClick:()=>n(s.preset),className:Ie("flex-1 h-6 text-[10px] px-1",e===s.preset&&"ring-1 ring-ring"),children:s.shortLabel},s.preset))}),l.jsxs("div",{className:"grid grid-cols-4 gap-2",children:[l.jsx(ON,{label:"Top",value:t.top,onChange:s=>i("top",s)}),l.jsx(ON,{label:"Bottom",value:t.bottom,onChange:s=>i("bottom",s)}),l.jsx(ON,{label:"Left",value:t.left,onChange:s=>i("left",s)}),l.jsx(ON,{label:"Right",value:t.right,onChange:s=>i("right",s)})]})]})})]})}const sw={mobile:{..._5.mobile,label:"Phone",icon:HQe},tablet:{..._5.tablet,label:"Tablet",icon:JQe},desktop:{..._5.desktop,label:"Desktop",icon:QJe}},VWt={label:"Custom",icon:oy},yme=[{code:"en-US",label:"English (US)"},{code:"en-GB",label:"English (UK)"},{code:"es-ES",label:"Español"},{code:"es-MX",label:"Español (MX)"},{code:"fr-FR",label:"Français"},{code:"de-DE",label:"Deutsch"},{code:"it-IT",label:"Italiano"},{code:"pt-BR",label:"Português (BR)"},{code:"ja-JP",label:"日本語"},{code:"zh-CN",label:"简体中文"},{code:"zh-TW",label:"繁體中文"},{code:"ko-KR",label:"한국어"},{code:"ar-SA",label:"العربية"},{code:"hi-IN",label:"हिन्दी"},{code:"ru-RU",label:"Русский"},{code:"nl-NL",label:"Nederlands"}],xme=[{zone:"America/New_York",label:"New York",offset:"UTC-5/-4"},{zone:"America/Chicago",label:"Chicago",offset:"UTC-6/-5"},{zone:"America/Denver",label:"Denver",offset:"UTC-7/-6"},{zone:"America/Los_Angeles",label:"Los Angeles",offset:"UTC-8/-7"},{zone:"America/Sao_Paulo",label:"São Paulo",offset:"UTC-3"},{zone:"America/Mexico_City",label:"Mexico City",offset:"UTC-6/-5"},{zone:"Europe/London",label:"London",offset:"UTC+0/+1"},{zone:"Europe/Paris",label:"Paris",offset:"UTC+1/+2"},{zone:"Europe/Berlin",label:"Berlin",offset:"UTC+1/+2"},{zone:"Europe/Moscow",label:"Moscow",offset:"UTC+3"},{zone:"Asia/Dubai",label:"Dubai",offset:"UTC+4"},{zone:"Asia/Kolkata",label:"Mumbai",offset:"UTC+5:30"},{zone:"Asia/Singapore",label:"Singapore",offset:"UTC+8"},{zone:"Asia/Shanghai",label:"Shanghai",offset:"UTC+8"},{zone:"Asia/Tokyo",label:"Tokyo",offset:"UTC+9"},{zone:"Asia/Seoul",label:"Seoul",offset:"UTC+9"},{zone:"Australia/Sydney",label:"Sydney",offset:"UTC+10/+11"},{zone:"Pacific/Auckland",label:"Auckland",offset:"UTC+12/+13"},{zone:"UTC",label:"UTC",offset:"UTC+0"}],RN=[{mode:"permissive",label:"Permissive",description:"Allows all HTTPS resources"},{mode:"widget-declared",label:"Strict",description:"Only widget-declared domains"}];function j5e({protocol:e,showThemeToggle:t=!1,className:n}){const[r,i]=b.useState(!1),[a,s]=b.useState(!1),[o,u]=b.useState(!1),[c,d]=b.useState(!1),f=Zt(q=>q.deviceType),p=Zt(q=>q.setDeviceType),m=Zt(q=>q.customViewport),y=Zt(q=>q.setCustomViewport),v=Zt(q=>q.globals),x=Zt(q=>q.updateGlobal),_=Zt(q=>q.capabilities),S=Zt(q=>q.setCapabilities),w=Zt(q=>q.cspMode),T=Zt(q=>q.setCspMode),N=Zt(q=>q.mcpAppsCspMode),E=Zt(q=>q.setMcpAppsCspMode),A=e===bn.MCP_APPS?N:w,I=e===bn.MCP_APPS?E:T,M=eo(q=>q.themeMode),$=eo(q=>q.setThemeMode),O=b.useCallback(()=>{const q=M==="dark"?"light":"dark";RZ(q),$(q)},[M,$]),R=b.useMemo(()=>f==="custom"?{...VWt,width:m.width,height:m.height}:sw[f],[f,m]),U=R.icon,z=v.locale,F=v.timeZone,D=e===null||e===bn.OPENAI_SDK,W=e===bn.MCP_APPS;return l.jsx("div",{className:n,children:l.jsxs("div",{className:"flex items-center gap-4",children:[D&&l.jsxs(l.Fragment,{children:[l.jsxs(qo,{open:r,onOpenChange:i,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(U,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:R.label}),l.jsxs("span",{className:"text-muted-foreground text-[10px]",children:[R.width,"×",R.height]})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Device"})})]}),l.jsx(Ho,{className:"w-56 p-2",align:"start",children:l.jsxs("div",{className:"space-y-2",children:[Object.entries(sw).map(([q,X])=>{const L=X.icon,Y=f===q;return l.jsxs("button",{onClick:()=>{p(q),i(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${Y?"bg-accent text-accent-foreground":""}`,children:[l.jsx(L,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:X.label}),l.jsxs("span",{className:"text-muted-foreground text-[10px] ml-auto",children:[X.width,"×",X.height]})]},q)}),l.jsxs("button",{onClick:()=>p("custom"),className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${f==="custom"?"bg-accent text-accent-foreground":""}`,children:[l.jsx(oy,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:"Custom"}),l.jsxs("span",{className:"text-muted-foreground text-[10px] ml-auto",children:[m.width,"×",m.height]})]}),f==="custom"&&l.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{htmlFor:"custom-width",className:"text-[10px] text-muted-foreground",children:"Width"}),l.jsx(Ct,{id:"custom-width",type:"number",min:100,max:2560,defaultValue:m.width,onBlur:q=>{const X=parseInt(q.target.value)||100;y({width:Math.max(100,Math.min(2560,X))})},className:"h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"},`w-${m.width}`)]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{htmlFor:"custom-height",className:"text-[10px] text-muted-foreground",children:"Height"}),l.jsx(Ct,{id:"custom-height",type:"number",min:100,max:2560,defaultValue:m.height,onBlur:q=>{const X=parseInt(q.target.value)||100;y({height:Math.max(100,Math.min(2560,X))})},className:"h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"},`h-${m.height}`)]})]})]})})]}),l.jsxs(qo,{open:a,onOpenChange:s,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(vte,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:z})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Locale"})})]}),l.jsx(Ho,{className:"w-48 p-2",align:"start",children:l.jsx("div",{className:"space-y-1",children:yme.map(q=>l.jsxs("button",{onClick:()=>{x("locale",q.code),s(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${z===q.code?"bg-accent text-accent-foreground":""}`,children:[l.jsx("span",{children:q.label}),l.jsx("span",{className:"text-muted-foreground text-[10px] ml-auto",children:q.code})]},q.code))})})]}),l.jsxs(qo,{open:o,onOpenChange:u,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(lA,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:RN.find(q=>q.mode===A)?.label})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"CSP"})})]}),l.jsx(Ho,{className:"w-56 p-2",align:"start",children:l.jsx("div",{className:"space-y-1",children:RN.map(q=>l.jsxs("button",{onClick:()=>{I(q.mode),u(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${A===q.mode?"bg-accent text-accent-foreground":""}`,children:[l.jsx("span",{className:"font-medium",children:q.label}),l.jsx("span",{className:"text-muted-foreground text-[10px] ml-auto",children:q.description})]},q.mode))})})]}),l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:_.hover?"secondary":"ghost",size:"icon",onClick:()=>S({hover:!_.hover}),className:"h-7 w-7",children:l.jsx(xte,{className:"h-3.5 w-3.5"})})}),l.jsxs(zt,{children:[l.jsx("p",{className:"font-medium",children:"Hover"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:_.hover?"Enabled":"Disabled"})]})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:_.touch?"secondary":"ghost",size:"icon",onClick:()=>S({touch:!_.touch}),className:"h-7 w-7",children:l.jsx(yte,{className:"h-3.5 w-3.5"})})}),l.jsxs(zt,{children:[l.jsx("p",{className:"font-medium",children:"Touch"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:_.touch?"Enabled":"Disabled"})]})]})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("div",{children:l.jsx(vme,{})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Safe Area"})})]})]}),W&&l.jsxs(l.Fragment,{children:[l.jsxs(qo,{open:r,onOpenChange:i,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(U,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:R.label}),l.jsxs("span",{className:"text-muted-foreground text-[10px]",children:[R.width,"×",R.height]})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Device"})})]}),l.jsx(Ho,{className:"w-56 p-2",align:"start",children:l.jsxs("div",{className:"space-y-2",children:[Object.entries(sw).map(([q,X])=>{const L=X.icon,Y=f===q;return l.jsxs("button",{onClick:()=>{p(q),i(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${Y?"bg-accent text-accent-foreground":""}`,children:[l.jsx(L,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:X.label}),l.jsxs("span",{className:"text-muted-foreground text-[10px] ml-auto",children:[X.width,"×",X.height]})]},q)}),l.jsxs("button",{onClick:()=>p("custom"),className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${f==="custom"?"bg-accent text-accent-foreground":""}`,children:[l.jsx(oy,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:"Custom"}),l.jsxs("span",{className:"text-muted-foreground text-[10px] ml-auto",children:[m.width,"×",m.height]})]}),f==="custom"&&l.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{htmlFor:"custom-width-mcp",className:"text-[10px] text-muted-foreground",children:"Width"}),l.jsx(Ct,{id:"custom-width-mcp",type:"number",min:100,max:2560,defaultValue:m.width,onBlur:q=>{const X=parseInt(q.target.value)||100;y({width:Math.max(100,Math.min(2560,X))})},className:"h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"},`w-mcp-${m.width}`)]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{htmlFor:"custom-height-mcp",className:"text-[10px] text-muted-foreground",children:"Height"}),l.jsx(Ct,{id:"custom-height-mcp",type:"number",min:100,max:2560,defaultValue:m.height,onBlur:q=>{const X=parseInt(q.target.value)||100;y({height:Math.max(100,Math.min(2560,X))})},className:"h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"},`h-mcp-${m.height}`)]})]})]})})]}),l.jsxs(qo,{open:a,onOpenChange:s,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(vte,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:z})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Locale"})})]}),l.jsx(Ho,{className:"w-48 p-2",align:"start",children:l.jsx("div",{className:"space-y-1",children:yme.map(q=>l.jsxs("button",{onClick:()=>{x("locale",q.code),s(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${z===q.code?"bg-accent text-accent-foreground":""}`,children:[l.jsx("span",{children:q.label}),l.jsx("span",{className:"text-muted-foreground text-[10px] ml-auto",children:q.code})]},q.code))})})]}),l.jsxs(qo,{open:c,onOpenChange:d,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(Sw,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:xme.find(q=>q.zone===F)?.label||F})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Timezone"})})]}),l.jsx(Ho,{className:"w-56 p-2",align:"start",children:l.jsx("div",{className:"space-y-1",children:xme.map(q=>l.jsxs("button",{onClick:()=>{x("timeZone",q.zone),d(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${F===q.zone?"bg-accent text-accent-foreground":""}`,children:[l.jsx("span",{children:q.label}),l.jsx("span",{className:"text-muted-foreground text-[10px] ml-auto",children:q.offset})]},q.zone))})})]}),l.jsxs(qo,{open:o,onOpenChange:u,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(lA,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:RN.find(q=>q.mode===N)?.label})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"CSP"})})]}),l.jsx(Ho,{className:"w-56 p-2",align:"start",children:l.jsx("div",{className:"space-y-1",children:RN.map(q=>l.jsxs("button",{onClick:()=>{E(q.mode),u(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${N===q.mode?"bg-accent text-accent-foreground":""}`,children:[l.jsx("span",{className:"font-medium",children:q.label}),l.jsx("span",{className:"text-muted-foreground text-[10px] ml-auto",children:q.description})]},q.mode))})})]}),l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:_.hover?"secondary":"ghost",size:"icon",onClick:()=>S({hover:!_.hover}),className:"h-7 w-7",children:l.jsx(xte,{className:"h-3.5 w-3.5"})})}),l.jsxs(zt,{children:[l.jsx("p",{className:"font-medium",children:"Hover"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:_.hover?"Enabled":"Disabled"})]})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:_.touch?"secondary":"ghost",size:"icon",onClick:()=>S({touch:!_.touch}),className:"h-7 w-7",children:l.jsx(yte,{className:"h-3.5 w-3.5"})})}),l.jsxs(zt,{children:[l.jsx("p",{className:"font-medium",children:"Touch"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:_.touch?"Enabled":"Disabled"})]})]})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("div",{children:l.jsx(vme,{})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Safe Area"})})]})]}),t&&l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:"ghost",size:"icon",onClick:O,className:"h-7 w-7",children:M==="dark"?l.jsx(z1e,{className:"h-3.5 w-3.5"}):l.jsx($1e,{className:"h-3.5 w-3.5"})})}),l.jsx(zt,{children:M==="dark"?"Light mode":"Dark mode"})]})]})})}function GWt({view:e,serverName:t,serverConnectionStatus:n,toolInputOverride:r,toolOutputOverride:i,widgetStateOverride:a,isLoadingOverride:s,toolOutputErrorOverride:o,isEditing:u=!1}){const c=Zt(T=>T.deviceType),d=Zt(T=>T.customViewport),f=Zt(T=>T.setPlaygroundActive),p=Zt(T=>T.setDeviceType),m=Zt(T=>T.setCustomViewport),y=Zt(T=>T.updateGlobal),v=Zt(T=>T.setCapabilities),x=Zt(T=>T.setSafeAreaInsets),_=Zt(T=>T.setSelectedProtocol),S=b.useMemo(()=>c==="custom"?{width:d.width,height:d.height}:sw[c],[c,d]);b.useEffect(()=>(f(!0),()=>f(!1)),[f]),b.useEffect(()=>{const T=e.protocol==="mcp-apps"?bn.MCP_APPS:bn.OPENAI_SDK;_(T)},[e.protocol,_]),b.useEffect(()=>{if(e.defaultContext){const T=e.defaultContext;T.deviceType&&p(T.deviceType),T.viewport&&m(T.viewport),T.locale&&y("locale",T.locale),T.timeZone&&y("timeZone",T.timeZone),T.capabilities&&v(T.capabilities),T.safeAreaInsets&&x(T.safeAreaInsets)}},[e._id,e.defaultContext,p,m,y,v,x]);const w=e.protocol==="mcp-apps"?bn.MCP_APPS:bn.OPENAI_SDK;return l.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[u&&l.jsx("div",{className:"flex items-center justify-center px-4 py-2 border-b bg-muted/30 text-xs text-muted-foreground",children:l.jsx(j5e,{protocol:w})}),l.jsx("div",{className:"flex-1 flex items-center justify-center p-4 min-h-0 overflow-auto bg-muted/20",children:l.jsx("div",{className:"relative bg-background border border-border rounded-xl shadow-lg flex flex-col overflow-hidden",style:{width:S.width,maxWidth:"100%",height:S.height,maxHeight:"100%"},children:l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-contain",children:l.jsx(zWt,{view:e,displayMode:"inline",serverName:t,serverConnectionStatus:n,toolInputOverride:r,toolOutputOverride:i,widgetStateOverride:a,isLoadingOverride:s,toolOutputErrorOverride:o})})})})]})}function bme({value:e,onSave:t,className:n,inputClassName:r,disabled:i=!1,truncate:a=!0,onClick:s}){const[o,u]=b.useState(!1),[c,d]=b.useState(e),[f,p]=b.useState(!1),m=b.useRef(null);b.useEffect(()=>{d(e)},[e]),b.useEffect(()=>{o&&m.current&&(m.current.focus(),m.current.select())},[o]);const y=b.useCallback(()=>{!i&&t&&(d(e),u(!0))},[i,t,e]),v=b.useCallback(()=>{d(e),u(!1)},[e]),x=b.useCallback(async()=>{const T=c.trim();if(!T||T===e){v();return}if(!t){v();return}p(!0);try{await t(T),u(!1)}catch{}finally{p(!1)}},[c,e,t,v]),_=b.useCallback(T=>{T.key==="Enter"?(T.preventDefault(),x()):T.key==="Escape"&&v()},[x,v]),S=b.useCallback(T=>{s?.(T)},[s]),w=b.useCallback(T=>{s?.(T),y()},[s,y]);return o?l.jsx("input",{ref:m,type:"text",value:c,onChange:T=>d(T.target.value),onClick:S,onBlur:x,onKeyDown:_,disabled:f,className:Ie("px-0 py-0 bg-transparent border-none focus:outline-none focus:ring-0",f&&"opacity-50",n,r)}):l.jsx("span",{onClick:w,className:Ie(a&&"truncate",!i&&t&&"cursor-pointer hover:opacity-60 transition-opacity",n),children:e})}function WWt({view:e,onBack:t,initialToolOutput:n,liveToolOutput:r,initialWidgetState:i,liveWidgetState:a,isLoadingToolOutput:s,onDataChange:o,isSaving:u=!1,onSave:c,hasUnsavedChanges:d=!1,serverConnectionStatus:f,isRunning:p=!1,onRun:m,onRename:y}){const v=b.useCallback((I,M,$)=>{const O={toolInput:I,toolOutput:M};return e.protocol==="openai-apps"?{...O,widgetState:$??null}:O},[e.protocol]),[x,_]=b.useState(()=>v(e.toolInput,n??null,i??null)),S=b.useRef(r),w=b.useRef(a);b.useEffect(()=>{_(v(e.toolInput,n??null,i??null))},[e._id,n,i,v]),b.useEffect(()=>{r!==S.current&&(S.current=r,_(I=>({...I,toolOutput:r??null})))},[r]),b.useEffect(()=>{e.protocol==="openai-apps"&&a!==w.current&&(w.current=a,_(I=>({...I,widgetState:a??null})))},[e.protocol,a]);const T=b.useCallback(I=>{if(I&&typeof I=="object"){const M=I,$=e.protocol==="openai-apps"?{toolInput:M.toolInput,toolOutput:M.toolOutput,widgetState:"widgetState"in M?M.widgetState:null}:{toolInput:M.toolInput,toolOutput:M.toolOutput};_($),e.protocol==="openai-apps"?o?.({toolInput:$.toolInput,toolOutput:$.toolOutput,widgetState:$.widgetState}):o?.({toolInput:$.toolInput,toolOutput:$.toolOutput})}},[o,e.protocol]),N=b.useCallback(async()=>{!d||!c||await c()},[d,c]);if(s)return l.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[l.jsx("div",{className:"flex items-center justify-between px-3 py-1.5 bg-muted/30",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ee,{variant:"ghost",size:"sm",onClick:t,className:"h-7 w-7 p-0",children:l.jsx(mte,{className:"h-4 w-4"})}),l.jsx(bme,{value:e.name,onSave:y,disabled:!y,className:"text-sm font-medium max-w-[200px]"})]})}),l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsx(Pn,{className:"h-6 w-6 animate-spin text-muted-foreground"})})]});const E=l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ee,{variant:"ghost",size:"sm",onClick:t,className:"h-7 w-7 p-0",children:l.jsx(mte,{className:"h-4 w-4"})}),l.jsx(bme,{value:e.name,onSave:y,disabled:!y,className:"text-sm font-medium max-w-[200px]"})]}),A=l.jsxs("div",{className:"flex items-center gap-2",children:[f==="connected"&&m&&l.jsxs(Ee,{variant:"outline",size:"sm",onClick:m,disabled:p||u,className:"h-7 px-2 text-xs",children:[p?l.jsx(Pn,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):l.jsx(Tx,{className:"h-3.5 w-3.5 mr-1"}),"Run"]}),l.jsxs(Ee,{size:"sm",onClick:N,disabled:!d||u||p,className:"h-7 px-2 text-xs",children:[u?l.jsx(Pn,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):l.jsx(vS,{className:"h-3.5 w-3.5 mr-1"}),"Save"]})]});return l.jsx("div",{className:"flex flex-col h-full overflow-hidden",children:l.jsx(zn,{value:x,onChange:T,expandJsonStrings:!0,mode:"edit",showToolbar:!0,showModeToggle:!1,wrapLongLinesInEdit:!0,allowMaximize:!0,height:"100%",toolbarLeftContent:E,toolbarRightContent:A})})}function KWt({selectedServer:e}){const{isAuthenticated:t,isLoading:n}=Ba(),r=ci(),i=Rx(),s=i.workspaces[i.activeWorkspaceId]?.sharedWorkspaceId??null,[o,u]=b.useState(null),[c,d]=b.useState(!1),[f,p]=b.useState(null),[m,y]=b.useState(null),[v,x]=b.useState(null),[_,S]=b.useState(null),[w,T]=b.useState(null),[N,E]=b.useState(null),[A,I]=b.useState(null),[M,$]=b.useState(!1),[O,R]=b.useState(!1),[U,z]=b.useState(!1),F=CPe(),D=bs(Me=>Me.widgets),W=b.useRef(null),{sortedViews:q,isLoading:X}=xK({isAuthenticated:t,workspaceId:s}),{serversById:L,serversByName:Y}=bK({isAuthenticated:t,workspaceId:s}),G=e?Y.get(e):void 0,P=b.useMemo(()=>G?q.filter(Me=>Me.serverId===G):[],[q,G]),V=P.length>0;b.useEffect(()=>{o&&G&&(P.some(be=>be._id===o)||(u(null),d(!1),x(null),S(null),T(null),E(null),I(null),$(!1),W.current=null))},[G,o,P]);const K=b.useCallback(Me=>{if(Me)return i.servers[Me]?.connectionStatus},[i.servers]),{createMcpView:Q,createOpenaiView:oe,updateMcpView:re,updateOpenaiView:ee,removeMcpView:le,removeOpenaiView:te,generateMcpUploadUrl:Z,generateOpenaiUploadUrl:ne}=NPe(),J=b.useMemo(()=>o?P.find(Me=>Me._id===o)??null:null,[o,P]);b.useEffect(()=>{if(!J){x(null),S(null),T(null),E(null),I(null),$(!1),W.current=null;return}if(W.current===J._id)return;const Me=J._id,be=new AbortController;let je=!0;x(J.toolInput),S(null),T(J.protocol==="openai-apps"?J.widgetState??null:null),E(null),I(null);const Xe=!!J.toolOutputUrl;$(Xe);async function ue(){if(!J?.toolOutputUrl){W.current=Me;return}try{const fe=await fetch(J.toolOutputUrl,{signal:be.signal});if(!fe.ok)throw new Error(`Failed to fetch output: ${fe.status}`);const xe=await fe.json();if(!je)return;S(xe),E(xe),W.current=Me}catch(fe){if(!je||fe instanceof DOMException&&fe.name==="AbortError")return;console.error("Failed to load toolOutput:",fe),I(fe instanceof Error?fe.message:"Failed to load output"),W.current=Me}finally{je&&$(!1)}}return ue(),()=>{je=!1,be.abort()}},[J]),b.useEffect(()=>{r.capture("views_tab_viewed",{location:"views_tab",platform:Et(),environment:void 0})},[r]);const se=b.useCallback(Me=>{u(Me),W.current=null,r.capture("view_selected",{location:"views_tab",platform:Et(),environment:void 0})},[r]),ie=b.useCallback(async Me=>{p(Me._id);try{Me.protocol==="mcp-apps"?await le({viewId:Me._id}):await te({viewId:Me._id}),Pe.success(`View "${Me.name}" deleted`),r.capture("view_deleted",{location:"views_tab",platform:Et(),environment:void 0}),o===Me._id&&u(null)}catch(be){console.error("Failed to delete view:",be),Pe.error("Failed to delete view")}finally{p(null)}},[o,le,te,r]),he=b.useCallback(Me=>{u(Me._id),d(!0),W.current=null,r.capture("view_edit_started",{location:"views_tab",platform:Et(),environment:void 0})},[r]),ye=b.useCallback(async(Me,be)=>{try{const je={viewId:Me._id,name:be};Me.protocol==="mcp-apps"?await re(je):await ee(je),Pe.success(`View renamed to "${be}"`),r.capture("view_renamed",{location:"views_tab",platform:Et(),environment:void 0})}catch(je){throw console.error("Failed to rename view:",je),Pe.error("Failed to rename view"),je}},[re,ee,r]),Ne=b.useCallback(async Me=>{if(s){y(Me._id);try{let be;if(Me.toolOutputUrl){const Ce=await fetch(Me.toolOutputUrl);if(Ce.ok){const He=await Ce.json(),Ze=Me.protocol==="mcp-apps"?await Z():await ne(),st=await fetch(Ze,{method:"POST",body:JSON.stringify(He),headers:{"Content-Type":"application/json"}});if(st.ok){const{storageId:ot}=await st.json();be=ot}}}let je;if(Me.widgetHtmlUrl){const Ce=await fetch(Me.widgetHtmlUrl);if(Ce.ok){const He=await Ce.text(),Ze=Me.protocol==="mcp-apps"?await Z():await ne(),st=await fetch(Ze,{method:"POST",body:He,headers:{"Content-Type":"text/html"}});if(st.ok){const{storageId:ot}=await st.json();je=ot}}}const Xe=Me.name.replace(/ \(copy( \d+)?\)$/,""),fe=P.filter(Ce=>Ce.name.startsWith(Xe)&&Ce.name.match(/ \(copy( \d+)?\)$/)).length+1,xe=fe===1?`${Xe} (copy)`:`${Xe} (copy ${fe})`;Me.protocol==="mcp-apps"?await Q({workspaceId:s,serverId:Me.serverId,name:xe,description:Me.description,resourceUri:Me.resourceUri,toolName:Me.toolName,toolState:Me.toolState,toolInput:Me.toolInput,toolOutputBlobId:be,widgetHtmlBlobId:je,toolErrorText:Me.toolErrorText,toolMetadata:Me.toolMetadata,prefersBorder:Me.prefersBorder,tags:Me.tags,category:Me.category,defaultContext:Me.defaultContext}):await oe({workspaceId:s,serverId:Me.serverId,name:xe,description:Me.description,outputTemplate:Me.outputTemplate,toolName:Me.toolName,toolState:Me.toolState,toolInput:Me.toolInput,toolOutputBlobId:be,widgetHtmlBlobId:je,toolErrorText:Me.toolErrorText,toolMetadata:Me.toolMetadata,prefersBorder:Me.prefersBorder,tags:Me.tags,category:Me.category,defaultContext:Me.defaultContext,serverInfo:Me.serverInfo,widgetState:Me.widgetState}),Pe.success(`View duplicated as "${xe}"`),r.capture("view_duplicated",{location:"views_tab",platform:Et(),environment:void 0})}catch(be){console.error("Failed to duplicate view:",be),Pe.error("Failed to duplicate view")}finally{y(null)}}},[s,P,Q,oe,Z,ne,r]),ce=b.useCallback(Me=>{x(Me.toolInput),S(Me.toolOutput),"widgetState"in Me&&T(Me.widgetState)},[]),Te=b.useMemo(()=>{if(!J)return!1;const Me=JSON.stringify(v)!==JSON.stringify(J.toolInput),be=JSON.stringify(_)!==JSON.stringify(N),je=!nle(F,J.defaultContext),Xe=J.protocol==="openai-apps"?J.widgetState??null:null,ue=J.protocol==="openai-apps"&&JSON.stringify(w??null)!==JSON.stringify(Xe);return Me||be||je||ue},[J,v,_,w,N,F]),we=b.useCallback(async()=>{if(!(!J||!Te)){R(!0);try{const Me=JSON.stringify(_)!==JSON.stringify(N),be=!nle(F,J.defaultContext),je=J.protocol==="openai-apps"?J.widgetState??null:null,Xe=J.protocol==="openai-apps"&&JSON.stringify(w??null)!==JSON.stringify(je);let ue,fe;if(Me&&_!==null){const st=J.protocol==="mcp-apps"?await Z():await ne(),ot=await fetch(st,{method:"POST",body:JSON.stringify(_),headers:{"Content-Type":"application/json"}});if(!ot.ok)throw new Error(`Failed to upload toolOutput: ${ot.status}`);const{storageId:mt}=await ot.json();ue=mt}const xe=`view-preview-${J._id}`,Ce=D.get(xe),He=Ce?.widgetHtml;if(He){const st=J.protocol==="mcp-apps"?await Z():await ne(),ot=await fetch(st,{method:"POST",body:He,headers:{"Content-Type":"text/html"}});if(!ot.ok)throw new Error(`Failed to upload widget HTML: ${ot.status}`);const{storageId:mt}=await ot.json();fe=mt}const Ze={viewId:J._id,toolInput:v};ue&&(Ze.toolOutputBlobId=ue),fe&&(Ze.widgetHtmlBlobId=fe),be&&(Ze.defaultContext=F),J.protocol==="openai-apps"&&(Xe?Ze.widgetState=w??null:Ce!==void 0&&(Ze.widgetState=Ce.widgetState)),J.protocol==="mcp-apps"?await re(Ze):await ee(Ze),E(_),Pe.success("View saved successfully"),r.capture("view_saved",{location:"views_tab",platform:Et(),environment:void 0})}catch(Me){console.error("Failed to save view:",Me),Pe.error("Failed to save view")}finally{R(!1)}}},[J,Te,v,_,w,N,F,Z,ne,re,ee,D,r]),Oe=b.useCallback(async()=>{if(!J||v===null||!e)return;if(K(e)!=="connected"){Pe.error("Server is not connected");return}z(!0);try{const be=v??{},je=await n3(e,J.toolName,be);if("error"in je){Pe.error(`Execution failed: ${je.error}`);return}if(je.status==="elicitation_required"){Pe.error("Tool requires elicitation (not supported in Views)");return}if(je.status==="task_created"){Pe.error("Background tasks not supported in Views");return}S(je.result),Pe.success("Tool executed successfully"),r.capture("view_tool_executed",{location:"views_tab",platform:Et(),environment:void 0})}catch(be){const je=be instanceof Error?be.message:"Execution failed";Pe.error(je)}finally{z(!1)}},[J,v,e,K,r]),Ue=b.useCallback(()=>{u(null),d(!1),x(null),S(null),T(null),E(null),W.current=null},[]);return n?l.jsx("div",{className:"p-6",children:l.jsx("div",{className:"flex min-h-[calc(100vh-200px)] items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading..."})]})})}):t?s?X?l.jsx("div",{className:"p-6",children:l.jsx("div",{className:"flex min-h-[calc(100vh-200px)] items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading views..."})]})})}):l.jsx("div",{className:"h-full flex flex-col overflow-hidden",children:l.jsxs(Bc,{direction:"horizontal",className:"flex-1 overflow-hidden",children:[l.jsx(ta,{defaultSize:55,minSize:30,maxSize:70,className:"border-r bg-muted/30 flex flex-col",children:J&&c?l.jsx(WWt,{view:J,onBack:Ue,initialToolOutput:N,liveToolOutput:_,initialWidgetState:J.protocol==="openai-apps"?J.widgetState:void 0,liveWidgetState:J.protocol==="openai-apps"?w:void 0,isLoadingToolOutput:M,onDataChange:ce,isSaving:O,onSave:we,hasUnsavedChanges:Te,serverConnectionStatus:K(e),isRunning:U,onRun:Oe,onRename:Me=>ye(J,Me)}):l.jsx(LWt,{views:P,selectedViewId:o,onSelectView:se,onEditView:he,onDuplicateView:Ne,onDeleteView:ie,deletingViewId:f,duplicatingViewId:m,isLoading:X})}),l.jsx($u,{withHandle:!0}),l.jsx(ta,{defaultSize:50,className:"flex flex-col overflow-hidden",children:J?l.jsx(GWt,{view:J,serverName:L.get(J.serverId),serverConnectionStatus:K(L.get(J.serverId)),toolInputOverride:v,isLoadingOverride:M,toolOutputErrorOverride:A,toolOutputOverride:_,widgetStateOverride:J.protocol==="openai-apps"?w:void 0,isEditing:c}):l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsxs("div",{className:"text-center max-w-md mx-auto p-8",children:[l.jsx("div",{className:"w-20 h-20 bg-muted rounded-full flex items-center justify-center mx-auto mb-6",children:l.jsx(N1,{className:"h-10 w-10 text-muted-foreground"})}),l.jsx("h2",{className:"text-2xl font-semibold text-foreground mb-2",children:V?"Select a view":e?"No views for this server":"Select a server"}),l.jsx("p",{className:"text-sm text-muted-foreground mb-6",children:V?"Choose a view from the list to see its details and preview.":e?"This server has no saved views yet. Save tool executions from the Chat tab to create reusable views.":"Select a server from the tabs above to view its saved views."})]})})})]})}):l.jsx("div",{className:"p-6",children:l.jsx(Rc,{icon:N1,title:"No workspace selected",description:"Select a shared workspace to view and manage saved views.",className:"h-[calc(100vh-200px)]"})}):l.jsx("div",{className:"p-6",children:l.jsx(Rc,{icon:N1,title:"Sign in to view saved views",description:"Create an account or sign in to save and manage tool execution snapshots.",className:"h-[calc(100vh-200px)]"})})}function ZWt({open:e,onOpenChange:t,provider:n,value:r,onValueChange:i,baseUrlValue:a,onBaseUrlChange:s,onSave:o,onCancel:u,onRemove:c,isConfigured:d}){const f=ci();return l.jsx(si,{open:e,onOpenChange:t,children:l.jsxs(oi,{className:"max-w-md",children:[l.jsx(vi,{children:l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[n&&l.jsx("div",{className:"w-12 h-12 rounded-lg bg-card p-2 border",children:l.jsx("img",{src:n.logo,alt:n.logoAlt,className:"w-full h-full object-contain"})}),l.jsxs("div",{children:[l.jsxs(yi,{className:"text-left",children:["Configure ",n?.name]}),l.jsx(us,{className:"text-left",children:n?.description})]})]})}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{htmlFor:"api-key",className:"text-sm font-medium",children:"API Key"}),l.jsx(Ct,{id:"api-key",type:"password",value:r,onChange:p=>i(p.target.value),placeholder:n?.placeholder,className:"mt-1"})]}),n?.defaultBaseUrl&&s&&l.jsxs("div",{children:[l.jsx("label",{htmlFor:"base-url",className:"text-sm font-medium",children:"Base URL (Optional)"}),l.jsx(Ct,{id:"base-url",type:"text",value:a||"",onChange:p=>s(p.target.value),placeholder:n.defaultBaseUrl,className:"mt-1"}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave empty to use the default endpoint"})]}),l.jsxs("div",{className:"flex items-center gap-2 p-3 bg-info/10 rounded-lg",children:[l.jsx(Iu,{className:"w-4 h-4 text-info"}),l.jsxs("span",{className:"text-sm text-info",children:["Need an API key?"," ",l.jsx("button",{onClick:()=>n&&window.open(n.getApiKeyUrl,"_blank"),className:"underline hover:no-underline",children:"Get one here"})]})]}),n?.id==="openai"&&l.jsx(mK,{children:l.jsx(gK,{children:l.jsxs("p",{children:[l.jsx("strong",{children:"GPT-5 models require organization verification."})," ","If you encounter access errors, visit"," ",l.jsx("a",{href:"https://platform.openai.com/settings/organization/general",target:"_blank",rel:"noreferrer",className:"underline hover:no-underline font-medium align-baseline inline",children:"OpenAI Settings"})," ","and verify your organization. Access may take up to 15 minutes after verification."]})})})]}),l.jsxs(Js,{className:"flex-row justify-between sm:justify-between",children:[d&&c?l.jsx(Ee,{variant:"ghost",className:"text-destructive hover:text-destructive hover:bg-destructive/10",onClick:c,children:"Remove"}):l.jsx("div",{}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Ee,{variant:"outline",onClick:u,children:"Cancel"}),l.jsx(Ee,{onClick:()=>{f.capture("save_api_key",{location:"provider_config_dialog",platform:Et(),environment:void 0}),o()},disabled:!r.trim(),children:"Save"})]})]})]})})}function YWt({open:e,onOpenChange:t,value:n,onValueChange:r,onSave:i,onCancel:a}){return l.jsx(si,{open:e,onOpenChange:t,children:l.jsxs(oi,{className:"max-w-md",children:[l.jsx(vi,{children:l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[l.jsx("div",{className:"w-12 h-12 rounded-lg bg-card p-2 border",children:l.jsx("img",{src:"/ollama_logo.svg",alt:"Ollama",className:"w-full h-full object-contain"})}),l.jsxs("div",{children:[l.jsx(yi,{className:"text-left pb-2",children:"Configure Ollama URL"}),l.jsx(us,{className:"text-left",children:"Set the base URL for your Ollama instance"})]})]})}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{htmlFor:"ollama-url",className:"text-sm font-medium",children:"Base URL"}),l.jsx(Ct,{id:"ollama-url",type:"url",value:n,onChange:s=>r(s.target.value),placeholder:"http://127.0.0.1:11434/api",className:"mt-1"})]}),l.jsxs("div",{className:"flex items-center gap-2 p-3 bg-info/10 rounded-lg",children:[l.jsx(Iu,{className:"w-4 h-4 text-info"}),l.jsxs("span",{className:"text-sm text-info",children:["Need help?"," ",l.jsx("button",{onClick:()=>window.open("https://ollama.ai/download","_blank"),className:"underline hover:no-underline",children:"Download Ollama"})]})]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:a,children:"Cancel"}),l.jsx(Ee,{onClick:i,disabled:!n.trim(),children:"Save URL"})]})]})})}function XWt({open:e,onOpenChange:t,baseUrl:n,apiKey:r,modelAlias:i,onBaseUrlChange:a,onApiKeyChange:s,onModelAliasChange:o,onSave:u,onCancel:c}){return l.jsx(si,{open:e,onOpenChange:t,children:l.jsxs(oi,{className:"max-w-md",children:[l.jsx(vi,{children:l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[l.jsx("div",{className:"w-12 h-12 rounded-lg bg-card p-2 flex items-center justify-center border",children:l.jsx("img",{src:"/litellm_logo.png",alt:"LiteLLM Logo",className:"w-full h-full object-contain"})}),l.jsxs("div",{children:[l.jsx(yi,{className:"text-left pb-2",children:"Configure LiteLLM Proxy"}),l.jsx(us,{className:"text-left",children:"Set up your LiteLLM proxy connection"})]})]})}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{htmlFor:"litellm-url",className:"text-sm font-medium",children:"Base URL"}),l.jsx(Ct,{id:"litellm-url",type:"url",value:n,onChange:d=>a(d.target.value),placeholder:"http://localhost:4000",className:"mt-1"})]}),l.jsxs("div",{children:[l.jsx("label",{htmlFor:"litellm-api-key",className:"text-sm font-medium",children:"API Key"}),l.jsx(Ct,{id:"litellm-api-key",type:"password",value:r,onChange:d=>s(d.target.value),placeholder:"sk-...",className:"mt-1"})]}),l.jsxs("div",{children:[l.jsxs("label",{htmlFor:"litellm-model",className:"text-sm font-medium",children:["Model Aliases"," ",l.jsx("span",{className:"text-muted-foreground",children:"(comma-separated)"})]}),l.jsx(Ct,{id:"litellm-model",type:"text",value:i,onChange:d=>o(d.target.value),placeholder:"gemini/gemini-2.5-flash, gpt-4, claude-3-opus",className:"mt-1"}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Enter multiple model aliases separated by commas. Each will appear as a separate option in the chat."})]}),l.jsxs("div",{className:"flex items-center gap-2 p-3 bg-info/10 rounded-lg",children:[l.jsx(Iu,{className:"w-4 h-4 text-info"}),l.jsxs("span",{className:"text-sm text-info",children:["Need help?"," ",l.jsx("button",{onClick:()=>window.open("https://docs.litellm.ai/docs/proxy/quick_start","_blank"),className:"underline hover:no-underline",children:"LiteLLM Proxy Docs"})]})]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:c,children:"Cancel"}),l.jsx(Ee,{onClick:u,disabled:!n.trim()||!i.trim(),children:"Save Configuration"})]})]})})}function JWt({items:e,placeholder:t="Select item...",searchPlaceholder:n="Search...",emptyMessage:r="No item found.",className:i,value:a,onValueChange:s,label:o="Model"}){const[u,c]=b.useState(!1),[d,f]=b.useState([]),p=a!==void 0?a:d,m=v=>{s?s(v):f(v)},y=()=>{const v=p;return v&&v.length>0?v.length===1?`1 ${o} Selected`:`${v.length} ${o}s Selected`:t};return l.jsxs(qo,{open:u,onOpenChange:c,modal:!0,children:[l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"outline",role:"combobox","aria-expanded":u,className:Ie("w-[200px] justify-between bg-background",i),children:[l.jsx("span",{className:"truncate",children:y()}),l.jsx(Lq,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),l.jsx(Ho,{className:"w-96 p-0",align:"start",children:l.jsxs(S5e,{children:[l.jsx(k5e,{placeholder:n,className:"h-9"}),l.jsx(E5e,{children:r}),l.jsx(T5e,{className:"max-h-48 overflow-auto",children:e.map(v=>{const x=p.includes(v.value);return l.jsxs(N5e,{value:v.value,onSelect:_=>{const S=p||[],w=S.includes(v.value)?S.filter(T=>T!==v.value):[...S,v.value];m(w)},children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{children:v.label}),v.description&&l.jsx("span",{className:"text-xs text-muted-foreground",children:v.description})]}),l.jsx(xi,{className:Ie("ml-auto h-4 w-4",x?"opacity-100":"opacity-0")})]},v.value)})})]})})]})}function QWt(){const[e,t]=b.useState([]),[n,r]=b.useState(!1),[i,a]=b.useState(null),s=b.useCallback(async()=>{r(!0),a(null);try{const o=await fetch("https://openrouter.ai/api/v1/models?supported_parameters=tools");if(!o.ok)throw new Error(`Failed to fetch models: ${o.statusText}`);const d=((await o.json()).data||[]).map(f=>({value:f.id,label:f.name,description:f.id}));d.sort((f,p)=>f.label.localeCompare(p.label)),t(d)}catch(o){const u=o instanceof Error?o.message:"Failed to fetch models";a(u),console.error("Error fetching OpenRouter models:",o)}finally{r(!1)}},[]);return b.useEffect(()=>{s()},[s]),{models:e,loading:n,error:i,refetch:s}}function eKt({open:e,onOpenChange:t,apiKey:n,selectedModels:r,onApiKeyChange:i,onSelectedModelsChange:a,onSave:s,onCancel:o,onRemove:u,isConfigured:c}){const{models:d,loading:f,error:p}=QWt(),[m,y]=b.useState(r);b.useEffect(()=>{y(r)},[r]);const v=()=>{a(m),s(n,m)};return l.jsx(si,{open:e,onOpenChange:t,children:l.jsxs(oi,{className:"max-w-md",children:[l.jsx(vi,{children:l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[l.jsx("div",{className:"w-12 h-12 rounded-lg bg-card p-2 flex items-center justify-center border",children:l.jsx("img",{src:"/openrouter_logo.png",alt:"OpenRouter Logo",className:"w-full h-full object-contain"})}),l.jsxs("div",{children:[l.jsx(yi,{className:"text-left pb-2",children:"Configure OpenRouter"}),l.jsx(us,{className:"text-left",children:"Add your OpenRouter API Key"})]})]})}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{htmlFor:"openrouter-api-key",className:"text-sm font-medium",children:"API Key"}),l.jsx(Ct,{id:"openrouter-api-key",type:"password",value:n,onChange:x=>i(x.target.value),placeholder:"sk-...",className:"mt-1"})]}),l.jsxs("div",{children:[l.jsx("label",{htmlFor:"openrouter-model",className:"text-sm font-medium",children:"Models"}),f?l.jsx("div",{className:"w-full mt-1 p-2 text-sm text-muted-foreground",children:"Loading models..."}):p?l.jsx("div",{className:"w-full mt-1 p-2 text-sm text-destructive",children:p}):l.jsxs(l.Fragment,{children:[l.jsx(JWt,{items:d,placeholder:"Select models...",searchPlaceholder:"Search models...",value:m,onValueChange:y,className:"w-full mt-1"}),m.length>0&&l.jsx("div",{className:"mt-3",children:l.jsx("div",{className:"flex flex-wrap gap-2",children:m.map(x=>{const _=d.find(S=>S.value===x);return l.jsxs(Cn,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[_?.label||x,l.jsx("button",{type:"button",onClick:()=>{y(S=>S.filter(w=>w!==x))},className:"ml-1 hover:bg-destructive hover:text-destructive-foreground rounded-sm p-0.5 transition-colors",children:l.jsx(Yn,{className:"h-3 w-3"})})]},x)})})}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"We only show models that support tool calling. Select one or more to surface them in the chat."})]})]}),l.jsxs("div",{className:"flex items-center gap-2 p-3 bg-info/10 rounded-lg",children:[l.jsx(Iu,{className:"w-4 h-4 text-info"}),l.jsxs("span",{className:"text-sm text-info",children:["Need help?"," ",l.jsx("button",{type:"button",onClick:()=>window.open("https://openrouter.ai/docs/quickstart","_blank"),className:"underline hover:no-underline",children:"OpenRouter Docs"})]})]})]}),l.jsxs(Js,{className:"flex-row justify-between sm:justify-between",children:[c&&u?l.jsx(Ee,{variant:"ghost",className:"text-destructive hover:text-destructive hover:bg-destructive/10",onClick:u,children:"Remove"}):l.jsx("div",{}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Ee,{variant:"outline",onClick:o,children:"Cancel"}),l.jsx(Ee,{onClick:v,disabled:m.length===0,children:"Save"})]})]})]})})}function tKt({open:e,onOpenChange:t,baseUrl:n,apiKey:r,onBaseUrlChange:i,onApiKeyChange:a,onSave:s,onCancel:o}){return l.jsx(si,{open:e,onOpenChange:t,children:l.jsxs(oi,{className:"max-w-md",children:[l.jsx(vi,{children:l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[l.jsx("div",{className:"w-12 h-12 rounded-lg bg-card p-2 flex items-center justify-center border",children:l.jsx("img",{src:"/azure_logo.png",alt:"Azure OpenAI Logo",className:"w-full h-full object-contain"})}),l.jsxs("div",{children:[l.jsx(yi,{className:"text-left pb-2",children:"Configure Azure OpenAI"}),l.jsx(us,{className:"text-left",children:"Set up your Azure OpenAI connection"})]})]})}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{htmlFor:"azure-url",className:"text-sm font-medium",children:"Base URL"}),l.jsx(Ct,{id:"azure-url",type:"url",value:n,onChange:u=>i(u.target.value),placeholder:"https://RESOURCE_NAME.openai.azure.com/openai",className:"mt-1"})]}),l.jsxs("div",{children:[l.jsx("label",{htmlFor:"azure-api-key",className:"text-sm font-medium",children:"API Key"}),l.jsx(Ct,{id:"azure-api-key",type:"password",value:r,onChange:u=>a(u.target.value),placeholder:"Open AI Key",className:"mt-1"})]}),l.jsxs("div",{className:"flex items-center gap-2 p-3 bg-info/10 rounded-lg",children:[l.jsx(Iu,{className:"w-4 h-4 text-info"}),l.jsxs("span",{className:"text-sm text-info",children:["Need help?"," ",l.jsx("button",{onClick:()=>window.open("https://ai-sdk.dev/providers/ai-sdk-providers/azure#chat-models","_blank"),className:"underline hover:no-underline",children:"Azure OpenAI Docs"})]})]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:o,children:"Cancel"}),l.jsx(Ee,{onClick:s,disabled:!n.trim(),children:"Save Configuration"})]})]})})}function _me({title:e,children:t}){return l.jsxs("div",{className:"space-y-2",children:[l.jsx("h2",{className:"text-sm font-medium text-muted-foreground",children:e}),l.jsx("div",{className:"space-y-1",children:t})]})}function nKt({label:e,value:t}){return l.jsxs("div",{className:"flex items-center justify-between px-4 py-3 rounded-md border border-border/40",children:[l.jsx("span",{className:"text-sm text-muted-foreground",children:e}),l.jsx("span",{className:"text-sm",children:t})]})}function wme({logo:e,logoAlt:t,name:n,isConfigured:r,onEdit:i,configType:a="api-key"}){const s=a==="base-url"?"Add Base URL":"Add API Key";return l.jsxs("button",{type:"button",onClick:i,className:Ie("w-full flex items-center justify-between px-4 py-3 rounded-md border transition-colors text-left","hover:bg-muted/30 cursor-pointer",r?"border-success/30":"border-border/40"),children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("img",{src:e,alt:t,className:"size-5 object-contain"}),l.jsx("span",{className:"text-sm font-medium",children:n}),r&&l.jsx(xi,{className:"size-4 text-success"})]}),l.jsx("span",{className:"text-sm text-muted-foreground",children:r?"Edit":s})]})}function rKt(){const{tokens:e,setToken:t,clearToken:n,hasToken:r,getOllamaBaseUrl:i,setOllamaBaseUrl:a,getLiteLLMBaseUrl:s,setLiteLLMBaseUrl:o,getLiteLLMModelAlias:u,setLiteLLMModelAlias:c,getOpenRouterSelectedModels:d,setOpenRouterSelectedModels:f,getAzureBaseUrl:p,setAzureBaseUrl:m,getAnthropicBaseUrl:y,setAnthropicBaseUrl:v,getOpenAIBaseUrl:x,setOpenAIBaseUrl:_}=zx(),[S,w]=b.useState(""),[T,N]=b.useState(!1),[E,A]=b.useState(null),[I,M]=b.useState(!1),[$,O]=b.useState(""),[R,U]=b.useState(!1),[z,F]=b.useState(""),[D,W]=b.useState(""),[q,X]=b.useState(""),[L,Y]=b.useState(!1),[G,P]=b.useState(""),[V,K]=b.useState([]),[Q,oe]=b.useState(!1),[re,ee]=b.useState(""),[le,te]=b.useState(""),[Z,ne]=b.useState(""),J=[{id:"openai",name:"OpenAI",logo:"/openai_logo.png",logoAlt:"OpenAI",description:"GPT-4, GPT-4o, GPT-4o-mini, GPT-4.1, GPT-5",placeholder:"sk-...",getApiKeyUrl:"https://platform.openai.com/api-keys",defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",name:"Anthropic",logo:"/claude_logo.png",logoAlt:"Claude",description:"Claude 3.5, Claude 3.7, Claude Opus 4",placeholder:"sk-ant-...",getApiKeyUrl:"https://console.anthropic.com/",defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",name:"Google AI",logo:"/google_logo.png",logoAlt:"Google AI",description:"Gemini 2.5, Gemini 2.5 Flash",placeholder:"AI...",getApiKeyUrl:"https://aistudio.google.com/app/apikey"},{id:"deepseek",name:"DeepSeek",logo:"/deepseek_logo.svg",logoAlt:"DeepSeek",description:"DeepSeek Chat, DeepSeek Reasoner",placeholder:"sk-...",getApiKeyUrl:"https://platform.deepseek.com/api_keys"},{id:"mistral",name:"Mistral AI",logo:"/mistral_logo.png",logoAlt:"Mistral AI",description:"Mistral Large, Mistral Small, Codestral",placeholder:"...",getApiKeyUrl:"https://console.mistral.ai/api-keys/"},{id:"xai",name:"xAI",logo:"/xai_logo.png",logoAlt:"xAI Grok",description:"Grok 3, Grok 3 Mini",placeholder:"xai-...",getApiKeyUrl:"https://console.x.ai/"}],se=[{id:"ollama",name:"Ollama",logo:"/ollama_logo.svg",isConfigured:!!i(),configType:"base-url",onEdit:()=>{O(i()),M(!0)}},{id:"litellm",name:"LiteLLM",logo:"/litellm_logo.png",isConfigured:!!s(),configType:"base-url",onEdit:()=>{F(s()),W(e.litellm||""),X(u()),U(!0)}},{id:"openrouter",name:"OpenRouter",logo:"/openrouter_logo.png",isConfigured:!!e.openrouter,onEdit:()=>{P(e.openrouter||""),K(d()),Y(!0)}},{id:"azure",name:"Azure OpenAI",logo:"/azure_logo.png",isConfigured:!!p(),configType:"base-url",onEdit:()=>{ee(p()),te(e.azure||""),oe(!0)}}],ie=ue=>{switch(ue){case"anthropic":return y();case"openai":return x();default:return""}},he=(ue,fe)=>{switch(ue){case"anthropic":v(fe);break;case"openai":_(fe);break}},ye=ue=>{const fe=J.find(xe=>xe.id===ue);if(fe){A(fe);const xe=e[ue];w(Array.isArray(xe)?xe.join(", "):xe||""),ne(ie(ue)),N(!0)}},Ne=()=>{E&&(t(E.id,S),E.defaultBaseUrl&&he(E.id,Z),N(!1),A(null),w(""),ne(""))},ce=()=>{N(!1),A(null),w(""),ne("")},Te=()=>{a($),M(!1),O("")},we=()=>{M(!1),O("")},Oe=()=>{o(z),t("litellm",D),c(q),U(!1),F(""),W(""),X("")},Ue=()=>{U(!1),F(""),W(""),X("")},Me=(ue,fe)=>{t("openrouter",ue),f(fe),Y(!1)},be=()=>{Y(!1),P(""),K([])},je=()=>{m(re),t("azure",le),oe(!1),ee(""),te("")},Xe=()=>{oe(!1),ee(""),te("")};return l.jsx("div",{className:"h-full overflow-y-auto",children:l.jsxs("div",{className:"p-10 space-y-8 max-w-3xl",children:[l.jsx("h1",{className:"text-2xl font-semibold",children:"Settings"}),l.jsx(_me,{title:"About",children:l.jsx(nKt,{label:"Version",value:"v1.5.13"})}),l.jsxs(_me,{title:"LLM Providers",children:[J.map(ue=>l.jsx(wme,{logo:ue.logo,logoAlt:ue.logoAlt,name:ue.name,isConfigured:r(ue.id),onEdit:()=>ye(ue.id)},ue.id)),se.map(ue=>l.jsx(wme,{logo:ue.logo,logoAlt:ue.name,name:ue.name,isConfigured:ue.isConfigured,onEdit:ue.onEdit,configType:ue.configType},ue.id))]}),l.jsx(ZWt,{open:T,onOpenChange:N,provider:E,value:S,onValueChange:w,baseUrlValue:Z,onBaseUrlChange:ne,onSave:Ne,onCancel:ce,onRemove:()=>{E&&(n(E.id),N(!1),A(null),w(""),ne(""))},isConfigured:E?r(E.id):!1}),l.jsx(YWt,{open:I,onOpenChange:M,value:$,onValueChange:O,onSave:Te,onCancel:we}),l.jsx(XWt,{open:R,onOpenChange:U,baseUrl:z,apiKey:D,modelAlias:q,onBaseUrlChange:F,onApiKeyChange:W,onModelAliasChange:X,onSave:Oe,onCancel:Ue}),l.jsx(tKt,{open:Q,onOpenChange:oe,baseUrl:re,apiKey:le,onBaseUrlChange:ee,onApiKeyChange:te,onSave:je,onCancel:Xe}),l.jsx(eKt,{open:L,onOpenChange:Y,apiKey:G,selectedModels:V,onApiKeyChange:P,onSelectedModelsChange:K,onSave:Me,onCancel:be,onRemove:()=>{n("openrouter"),f([]),Y(!1)},isConfigured:!!e.openrouter})]})})}function iKt(){return l.jsx("div",{className:"flex flex-col h-full",children:l.jsx(QS,{})})}class Dj{constructor(t){this.serverUrl=t,sessionStorage.setItem("debug-oauth-server-url",t)}get redirectUrl(){return`${window.location.origin}/oauth/callback/debug`}get clientMetadata(){return{redirect_uris:[this.redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:"MCPJam",client_uri:"https://github.com/mcpjam/inspector"}}async clientInformation(){const t=`debug-client-info-${this.serverUrl}`,n=sessionStorage.getItem(t);if(n)return JSON.parse(n)}saveClientInformation(t){const n=`debug-client-info-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(t))}async tokens(){const t=`debug-tokens-${this.serverUrl}`,n=sessionStorage.getItem(t);if(n)return JSON.parse(n)}saveTokens(t){const n=`debug-tokens-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(t))}redirectToAuthorization(t){}saveCodeVerifier(t){const n=`debug-verifier-${this.serverUrl}`;sessionStorage.setItem(n,t)}codeVerifier(){const t=`debug-verifier-${this.serverUrl}`,n=sessionStorage.getItem(t);if(!n)throw new Error("No code verifier saved for debug session");return n}saveServerMetadata(t){const n=`debug-server-metadata-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(t))}getServerMetadata(){const t=`debug-server-metadata-${this.serverUrl}`,n=sessionStorage.getItem(t);return n?JSON.parse(n):null}clear(){[`debug-client-info-${this.serverUrl}`,`debug-tokens-${this.serverUrl}`,`debug-verifier-${this.serverUrl}`,`debug-server-metadata-${this.serverUrl}`].forEach(n=>sessionStorage.removeItem(n))}}const PN={isInitiatingAuth:!1,oauthTokens:null,oauthStep:"metadata_discovery",oauthMetadata:null,resourceMetadata:null,resourceMetadataError:null,resource:null,authServerUrl:null,oauthClientInfo:null,authorizationUrl:null,authorizationCode:"",latestError:null,statusMessage:null,validationError:null,protocolVersion:"2025-11-25",registrationMethod:null,discoveryType:null,discoveryEndpointUsed:null,pkceSupported:!1},O5e=({open:e,onOpenChange:t,authorizationUrl:n,onAuthorizationComplete:r})=>{const i=b.useRef(null),a=b.useRef(!1);return b.useEffect(()=>{const s=u=>{u.origin===window.location.origin&&u.data?.type==="OAUTH_CALLBACK"&&u.data?.code&&(r?.(),t(!1),a.current=!1)};let o=null;try{o=new BroadcastChannel("oauth_callback_channel"),o.onmessage=u=>{u.data?.type==="OAUTH_CALLBACK"&&u.data?.code&&(r?.(),t(!1),a.current=!1)}}catch(u){console.warn("[OAuth Popup] BroadcastChannel not supported:",u)}return window.addEventListener("message",s),()=>{window.removeEventListener("message",s),o?.close()}},[t,r]),b.useEffect(()=>{if(e&&!a.current){a.current=!0;const s=600,o=700,u=window.screenX+(window.outerWidth-s)/2,c=window.screenY+(window.outerHeight-o)/2,d=`oauth_authorization_${Date.now()}`;console.log("authorizationUrl",n),i.current=window.open(n,d,`width=${s},height=${o},left=${u},top=${c},toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes`);const f=setInterval(()=>{i.current?.closed&&(clearInterval(f),t(!1),a.current=!1)},500);return()=>{clearInterval(f)}}e||(a.current=!1)},[e,n,t]),null},V0=({label:e,isComplete:t,isCurrent:n,error:r,children:i})=>l.jsxs("div",{children:[l.jsxs("div",{className:`flex items-center p-2 rounded-md ${n?"bg-accent":""}`,children:[t?l.jsx(ko,{className:"h-5 w-5 text-success mr-2"}):l.jsx(zm,{className:"h-5 w-5 text-muted-foreground mr-2"}),l.jsx("span",{className:`${n?"font-medium":""}`,children:e})]}),(n||t)&&i&&l.jsx("div",{className:"ml-7 mt-1",children:i}),n&&r&&l.jsxs("div",{className:"ml-7 mt-2 p-3 border border-destructive/30 bg-destructive/10 rounded-md",children:[l.jsx("p",{className:"text-sm font-medium text-destructive",children:"Error:"}),l.jsx("p",{className:"text-xs text-destructive/80 mt-1",children:r.message})]})]}),$N=["metadata_discovery","client_registration","authorization_redirect","authorization_code","token_request","complete"],aKt=({serverUrl:e,flowState:t,updateFlowState:n,proceedToNextStep:r})=>{const i=b.useMemo(()=>new Dj(e),[e]),[a,s]=b.useState(null),[o,u]=b.useState(!1),c=$N.findIndex(f=>f===t.oauthStep);b.useEffect(()=>{const f=async()=>{if(t.oauthClientInfo)s(t.oauthClientInfo);else try{const p=await i.clientInformation();p&&s(p)}catch(p){console.error("Failed to fetch client information:",p)}};c>$N.indexOf("client_registration")&&f()},[i,t.oauthStep,t.oauthClientInfo,c]);const d=f=>({isComplete:c>$N.indexOf(f)||c===$N.length-1,isCurrent:t.oauthStep===f,error:t.oauthStep===f?t.latestError:null});return l.jsxs("div",{className:"rounded-md border p-6 space-y-4 mt-4",children:[l.jsx("h3",{className:"text-lg font-medium",children:"OAuth Flow Progress"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Follow these steps to complete OAuth authentication with the server."}),l.jsxs("div",{className:"space-y-3",children:[l.jsx(V0,{label:"Metadata Discovery",...d("metadata_discovery"),children:t.oauthMetadata&&l.jsxs("details",{className:"text-xs mt-2",children:[l.jsxs("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:["OAuth Metadata Sources",!t.resourceMetadata&&" ℹ️"]}),t.resourceMetadata&&l.jsxs("div",{className:"mt-2",children:[l.jsx("p",{className:"font-medium",children:"Resource Metadata:"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:["From"," ",new URL("/.well-known/oauth-protected-resource",e).href]}),l.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(t.resourceMetadata,null,2)})]}),t.resourceMetadataError&&l.jsxs("div",{className:"mt-2 p-3 border border-info/30 bg-info/10 rounded-md",children:[l.jsxs("p",{className:"text-sm font-medium text-info",children:["ℹ️ Problem with resource metadata from"," ",l.jsx("a",{href:new URL("/.well-known/oauth-protected-resource",e).href,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info/80",children:new URL("/.well-known/oauth-protected-resource",e).href})]}),l.jsxs("p",{className:"text-xs text-info/80 mt-1",children:["Resource metadata was added in the"," ",l.jsx("a",{href:"https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#authorization-server-location",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"2025-06-18 specification update"}),l.jsx("br",{}),t.resourceMetadataError.message,t.resourceMetadataError instanceof TypeError&&" (This could indicate the endpoint doesn't exist or does not have CORS configured)"]})]}),t.oauthMetadata&&l.jsxs("div",{className:"mt-2",children:[l.jsx("p",{className:"font-medium",children:"Authorization Server Metadata:"}),t.authServerUrl&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["From"," ",new URL("/.well-known/oauth-authorization-server",t.authServerUrl).href]}),l.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(t.oauthMetadata,null,2)})]})]})}),l.jsx(V0,{label:"Client Registration",...d("client_registration"),children:a&&l.jsxs("details",{className:"text-xs mt-2",children:[l.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Registered Client Information"}),l.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(a,null,2)})]})}),l.jsx(V0,{label:"Preparing Authorization",...d("authorization_redirect"),children:t.authorizationUrl&&l.jsxs("div",{className:"mt-2 p-3 border rounded-md bg-muted",children:[l.jsx("p",{className:"font-medium mb-2 text-sm",children:"Authorization URL:"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("p",{className:"text-xs break-all",children:String(t.authorizationUrl)}),l.jsx("button",{onClick:()=>{u(!0)},className:"flex items-center text-info hover:text-info/80","aria-label":"Open authorization URL",title:"Open authorization URL",children:l.jsx(Iu,{className:"h-4 w-4"})})]}),l.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Click the link to authorize in your browser. After authorization, you'll be redirected back to continue the flow."})]})}),l.jsx(V0,{label:"Request Authorization and acquire authorization code",...d("authorization_code"),children:l.jsxs("div",{className:"mt-3",children:[l.jsx("label",{htmlFor:"authCode",className:"block text-sm font-medium mb-1",children:"Authorization Code"}),l.jsx("div",{className:"flex gap-2",children:l.jsx("input",{id:"authCode",value:t.authorizationCode,onChange:f=>{n({authorizationCode:f.target.value,validationError:null})},placeholder:"Enter the code from the authorization server",className:`flex h-9 w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${t.validationError?"border-destructive":"border-input"}`})}),t.validationError&&l.jsx("p",{className:"text-xs text-destructive mt-1",children:t.validationError}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once you've completed authorization in the link, paste the code here."})]})}),l.jsx(V0,{label:"Token Request",...d("token_request"),children:t.oauthMetadata&&l.jsxs("details",{className:"text-xs mt-2",children:[l.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Token Request Details"}),l.jsxs("div",{className:"mt-2 p-2 bg-muted rounded-md",children:[l.jsx("p",{className:"font-medium",children:"Token Endpoint:"}),l.jsx("code",{className:"block mt-1 text-xs overflow-x-auto",children:t.oauthMetadata.token_endpoint})]})]})}),l.jsx(V0,{label:"Authentication Complete",...d("complete"),children:t.oauthTokens&&l.jsxs("details",{className:"text-xs mt-2",children:[l.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Access Tokens"}),l.jsx("p",{className:"mt-1 text-sm",children:"Authentication successful! You can now use the authenticated connection. These tokens will be used automatically for server requests."}),l.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(t.oauthTokens,null,2)})]})})]}),l.jsxs("div",{className:"flex gap-3 mt-4",children:[t.oauthStep!=="complete"&&l.jsx(l.Fragment,{children:l.jsx(Ee,{onClick:r,disabled:t.isInitiatingAuth,children:"Continue"})}),t.oauthStep==="authorization_redirect"&&t.authorizationUrl&&l.jsx(Ee,{variant:"outline",onClick:()=>{u(!0)},children:"Authorize"})]}),t.authorizationUrl&&l.jsx(O5e,{open:o,onOpenChange:u,authorizationUrl:String(t.authorizationUrl)})]})},sKt={metadata_discovery:{canTransition:async()=>!0,execute:async e=>{try{if(e.updateState({latestError:null}),!e.serverUrl)throw new Error("Server URL is required");let t;try{t=new URL(e.serverUrl).toString()}catch{throw new Error(`Invalid server URL: ${e.serverUrl}`)}let n;try{n=new URL("/",t)}catch{throw new Error(`Failed to create base URL from server URL: ${t}`)}let r=null,i=null;try{if(r=await d3(t),r?.authorization_servers?.length){const o=r.authorization_servers[0];try{n=new URL(o)}catch{}}}catch(o){i=o instanceof Error?o:new Error(String(o))}const a=await bct(n.toString());let s=null;try{s=await $Se(t,e.provider,r??void 0)??null}catch{}e.updateState({resourceMetadata:r,resourceMetadataError:i,resource:s,authServerUrl:n,oauthMetadata:a,oauthStep:"client_registration"})}catch(t){const n=t instanceof Error?t:new Error(String(t));e.updateState({latestError:n,statusMessage:{type:"error",message:`Metadata discovery failed: ${n.message}`}})}}},client_registration:{canTransition:async e=>!!e.state.oauthMetadata,execute:async e=>{try{if(e.updateState({latestError:null}),!e.state.oauthMetadata)throw new Error("OAuth metadata not available");let t;try{const n={...e.provider.clientMetadata},r=e.state.resourceMetadata?.scopes_supported||e.state.oauthMetadata.scopes_supported;r&&r.length>0&&(n.scope=r.join(" "));try{t=await zSe(e.serverUrl,{metadata:e.state.oauthMetadata,clientMetadata:n}),e.provider.saveClientInformation(t)}catch(i){if(t=await e.provider.clientInformation(),!t)throw i}}catch{const r=await e.provider.clientInformation();r?t=r:(t={client_id:`static_client_${Date.now()}`,...e.provider.clientMetadata},e.provider.saveClientInformation(t))}e.updateState({oauthClientInfo:t,oauthStep:"authorization_redirect",statusMessage:{type:"success",message:"Client registration completed successfully."}})}catch(t){const n=t instanceof Error?t:new Error(String(t));e.updateState({latestError:n,statusMessage:{type:"error",message:`Client registration failed: ${n.message}`}})}}},authorization_redirect:{canTransition:async e=>!!e.state.oauthMetadata&&!!e.state.oauthClientInfo,execute:async e=>{try{if(e.updateState({latestError:null}),!e.state.oauthMetadata||!e.state.oauthClientInfo)throw new Error("OAuth metadata or client info not available");const t=e.state.resourceMetadata?.scopes_supported||e.state.oauthMetadata.scopes_supported,n=t&&t.length>0?t.join(" "):void 0,r=new Uint8Array(32);crypto.getRandomValues(r);const i=Array.from(r,s=>s.toString(16).padStart(2,"0")).join(""),a=await DSe(e.serverUrl,{metadata:e.state.oauthMetadata,clientInformation:e.state.oauthClientInfo,redirectUrl:e.provider.redirectUrl,scope:n,state:i,resource:e.state.resource??void 0});e.provider.saveCodeVerifier(a.codeVerifier),e.updateState({authorizationUrl:a.authorizationUrl.toString(),oauthStep:"authorization_code",statusMessage:{type:"info",message:"Authorization URL generated. Please complete authorization in your browser."}})}catch(t){const n=t instanceof Error?t:new Error(String(t));e.updateState({latestError:n,statusMessage:{type:"error",message:`Authorization preparation failed: ${n.message}`}})}}},authorization_code:{canTransition:async e=>!!e.state.authorizationCode.trim(),execute:async e=>{try{if(e.updateState({latestError:null,validationError:null}),!e.state.authorizationCode.trim()){e.updateState({validationError:"Authorization code is required"});return}e.updateState({oauthStep:"token_request"})}catch(t){const n=t instanceof Error?t:new Error(String(t));e.updateState({latestError:n,validationError:n.message})}}},token_request:{canTransition:async e=>!!e.state.authorizationCode.trim()&&!!e.state.oauthMetadata,execute:async e=>{try{if(e.updateState({latestError:null}),!e.state.oauthMetadata||!e.state.authorizationCode.trim()||!e.state.oauthClientInfo)throw new Error("OAuth metadata, authorization code, or client info not available");const t=await Sct(e.serverUrl,{metadata:e.state.oauthMetadata,clientInformation:e.state.oauthClientInfo,authorizationCode:e.state.authorizationCode,codeVerifier:e.provider.codeVerifier(),redirectUri:e.provider.redirectUrl});e.updateState({oauthTokens:t,oauthStep:"complete",statusMessage:{type:"success",message:"OAuth authentication completed successfully!"}})}catch(t){const n=t instanceof Error?t:new Error(String(t));e.updateState({latestError:n,statusMessage:{type:"error",message:`Token exchange failed: ${n.message}`}})}}},complete:{canTransition:async()=>!1,execute:async()=>{}}};class oKt{constructor(t){this.context=t}async proceedToNextStep(){const t=this.context.state.oauthStep,n=sKt[t];if(!n)return!1;try{return this.context.updateState({isInitiatingAuth:!0}),await n.canTransition(this.context)?(await n.execute(this.context),!0):!1}catch(r){const i=r instanceof Error?r:new Error(String(r));return this.context.updateState({latestError:i,statusMessage:{type:"error",message:i.message}}),!1}finally{this.context.updateState({isInitiatingAuth:!1})}}reset(){this.context.updateState({isInitiatingAuth:!1,oauthTokens:null,oauthStep:"metadata_discovery",oauthMetadata:null,resourceMetadata:null,resourceMetadataError:null,resource:null,authServerUrl:null,oauthClientInfo:null,authorizationUrl:null,authorizationCode:"",latestError:null,statusMessage:null,validationError:null})}}const lKt=({message:e})=>{let t,n,r;switch(e.type){case"error":t="bg-red-50 dark:bg-red-950/50",n="text-red-700 dark:text-red-400",r="border-red-200 dark:border-red-800";break;case"success":t="bg-green-50 dark:bg-green-950/50",n="text-green-700 dark:text-green-400",r="border-green-200 dark:border-green-800";break;case"info":default:t="bg-blue-50 dark:bg-blue-950/50",n="text-blue-700 dark:text-blue-400",r="border-blue-200 dark:border-blue-800";break}return l.jsx("div",{className:`p-3 rounded-md border ${t} ${r} ${n} mb-4`,children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Gs,{className:"h-4 w-4"}),l.jsx("p",{className:"text-sm",children:e.message})]})})},uKt=({serverConfig:e,serverEntry:t,serverName:n})=>{const[r,i]=b.useState(koe),[a,s]=b.useState(PN),[o,u]=b.useState(!1),c=b.useCallback(A=>{i(I=>({...I,...A}))},[]),d=b.useCallback(A=>{s(I=>({...I,...A}))},[]),f=b.useCallback(()=>{if(u(!1),d(PN),r.serverUrl)try{new Dj(r.serverUrl).clear()}catch(A){console.warn("Failed to clear debug OAuth provider state:",A)}},[r.serverUrl,d]);b.useEffect(()=>{if(e&&e.url&&n){const A=e.url.toString(),I=La(n);c({serverUrl:A,tokens:I,error:null,statusMessage:null})}else c(koe)},[e,n,c]),b.useEffect(()=>{f()},[n,f]);const p=b.useCallback(async()=>{if(!e||!r.serverUrl||!n){c({statusMessage:{type:"error",message:"Please select a server before refreshing tokens"}});return}c({isAuthenticating:!0,error:null,statusMessage:null});try{let A;if(r.tokens)A=await HH(n);else{const I={serverName:n,serverUrl:r.serverUrl};A=await $w(I)}if(A.success){const I=La(n);c({tokens:I,isAuthenticating:!1,statusMessage:{type:"success",message:r.tokens?"Tokens refreshed successfully!":A.serverConfig?"OAuth authentication completed!":"OAuth flow initiated. You will be redirected to authorize access."}}),setTimeout(()=>{c({statusMessage:null})},3e3)}else c({isAuthenticating:!1,error:A.error||"OAuth operation failed",statusMessage:{type:"error",message:`Failed: ${A.error||"OAuth operation failed"}`}})}catch(A){c({isAuthenticating:!1,error:A instanceof Error?A.message:String(A),statusMessage:{type:"error",message:`Failed: ${A instanceof Error?A.message:String(A)}`}})}},[e,r.serverUrl,r.tokens,n,c]),m=b.useCallback(async()=>{if(!e||!r.serverUrl||!n){c({statusMessage:{type:"error",message:"Please select a server before starting OAuth"}});return}c({isAuthenticating:!0,error:null,statusMessage:null});try{uc(n);const A={serverName:n,serverUrl:r.serverUrl},I=await $w(A);if(I.success){const M=La(n);c({tokens:M,isAuthenticating:!1,statusMessage:{type:"success",message:I.serverConfig?"OAuth authentication completed!":"OAuth flow initiated. You will be redirected to authorize access."}}),setTimeout(()=>{c({statusMessage:null})},3e3)}else c({isAuthenticating:!1,error:I.error||"OAuth authentication failed",statusMessage:{type:"error",message:`Failed: ${I.error||"OAuth authentication failed"}`}})}catch(A){c({isAuthenticating:!1,error:A instanceof Error?A.message:String(A),statusMessage:{type:"error",message:`Failed: ${A instanceof Error?A.message:String(A)}`}})}},[e,r.serverUrl,n,c]),y=b.useMemo(()=>{if(!e||!n||!r.serverUrl)return null;const A=new Dj(r.serverUrl);return new oKt({state:a,serverUrl:r.serverUrl,serverName:n,provider:A,updateState:d})},[e,n,r.serverUrl,a,d]),v=b.useCallback(()=>{f(),u(!0),d(PN),y&&y.proceedToNextStep()},[y,d,f]),x=b.useCallback(async()=>{y&&await y.proceedToNextStep()},[y]),_=b.useCallback(()=>{if(u(!1),d(PN),n){const A=La(n);c({tokens:A})}},[n,c,d]),S=b.useCallback(()=>{e&&r.serverUrl&&n&&(uc(n),c({tokens:null,error:null,statusMessage:{type:"success",message:"OAuth tokens cleared successfully"}}),setTimeout(()=>{c({statusMessage:null})},3e3))},[e,r.serverUrl,n,c]),w=e&&"url"in e,T=w,N=n&&(t?.oauthTokens||La(n)||t?.connectionStatus==="oauth-flow"),E=l.jsxs("div",{className:"rounded-md border border-dashed border-primary/30 bg-primary/10 px-3 py-2 text-xs text-primary space-y-1",children:[l.jsxs("div",{children:[l.jsx("span",{className:"font-medium",children:"Help us improve this feature!"})," ","We're looking for contributors to polish up this feature."]}),l.jsx("a",{href:"https://discord.com/invite/JEnDtz8X6z",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs font-medium text-primary underline hover:text-primary/80",children:"Join our Discord"})]});return e?T?l.jsx("div",{className:"h-full flex flex-col",children:l.jsxs("div",{className:"h-full flex flex-col bg-background",children:[l.jsx("div",{className:"flex items-center justify-between px-6 py-5 border-b border-border bg-background",children:l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(wn,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Authentication"})]}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage OAuth authentication for the selected server"})]})}),l.jsx("div",{className:"flex-1 overflow-auto px-6 py-6",children:l.jsxs("div",{className:"space-y-6 max-w-2xl",children:[E,l.jsxs("div",{className:"rounded-md border p-4 space-y-2",children:[l.jsx("h3",{className:"text-sm font-medium",children:"Selected Server"}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:[l.jsxs("div",{children:["Name: ",t?.name||"Unknown"]}),w&&l.jsxs("div",{children:["URL: ",e.url.toString()]}),l.jsx("div",{children:"Type: HTTP Server"})]})]}),l.jsxs("div",{className:"rounded-md border p-6 space-y-6",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(wn,{className:"h-5 w-5"}),l.jsx("h3",{className:"text-lg font-medium",children:"OAuth Authentication"})]}),l.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:N?"Manage OAuth authentication for this server.":"This server supports OAuth authentication. Use Quick OAuth to authenticate and get tokens."}),r.statusMessage&&l.jsx(lKt,{message:r.statusMessage}),r.error&&!r.statusMessage&&l.jsx("div",{className:"p-3 rounded-md border border-red-200 bg-red-50 text-red-700 mb-4",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Gs,{className:"h-4 w-4"}),l.jsx("p",{className:"text-sm",children:r.error})]})}),l.jsxs("div",{className:"space-y-4",children:[r.tokens&&l.jsxs("div",{className:"space-y-2",children:[l.jsx("p",{className:"text-sm font-medium",children:"Current Tokens:"}),l.jsxs("div",{className:"bg-muted p-3 rounded-md space-y-2",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Access Token:"}),l.jsxs("div",{className:"text-xs font-mono overflow-x-auto",children:[r.tokens.access_token.substring(0,40),"..."]})]}),r.tokens.refresh_token&&l.jsxs("div",{children:[l.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Refresh Token:"}),l.jsxs("div",{className:"text-xs font-mono overflow-x-auto",children:[r.tokens.refresh_token.substring(0,40),"..."]})]}),l.jsxs("div",{className:"flex gap-4 text-xs text-muted-foreground",children:[l.jsxs("span",{children:["Type: ",r.tokens.token_type]}),r.tokens.expires_in&&l.jsxs("span",{children:["Expires in: ",r.tokens.expires_in,"s"]}),r.tokens.scope&&l.jsxs("span",{children:["Scope: ",r.tokens.scope]})]})]})]}),l.jsxs("div",{className:"flex gap-4",children:[l.jsx(Ee,{onClick:r.tokens?p:m,disabled:r.isAuthenticating||!e,className:"flex items-center gap-2",variant:r.tokens?"outline":"default",children:r.isAuthenticating?l.jsxs(l.Fragment,{children:[l.jsx(wn,{className:"h-4 w-4 animate-spin"}),r.tokens?"Refreshing...":"Authenticating..."]}):l.jsxs(l.Fragment,{children:[l.jsx(wn,{className:"h-4 w-4"}),r.tokens?"Quick Refresh":"Quick OAuth"]})}),r.tokens&&l.jsx(Ee,{onClick:m,disabled:r.isAuthenticating||!e,className:"flex items-center gap-2",variant:"default",children:r.isAuthenticating?l.jsxs(l.Fragment,{children:[l.jsx(wn,{className:"h-4 w-4 animate-spin"}),"Authenticating..."]}):l.jsxs(l.Fragment,{children:[l.jsx(wn,{className:"h-4 w-4"}),"Quick OAuth"]})}),l.jsx(Ee,{variant:"outline",onClick:S,disabled:!e||!r.tokens,children:"Clear Tokens"}),l.jsx(Ee,{variant:"secondary",onClick:v,disabled:r.isAuthenticating||!e,children:"Guided OAuth Flow"})]}),l.jsx("p",{className:"text-xs text-muted-foreground",children:e?r.tokens?"Use Quick Refresh to renew existing tokens, or Quick OAuth to start a fresh authentication flow.":"Use Quick OAuth to authenticate with the server and get tokens.":"Select a server to manage its OAuth authentication."})]}),o&&r.serverUrl&&l.jsx(aKt,{serverUrl:r.serverUrl,flowState:a,updateFlowState:d,proceedToNextStep:x}),o&&l.jsx("div",{className:"mt-4",children:l.jsx(Ee,{variant:"outline",onClick:_,children:"Exit Guided Flow"})})]})]})})]})}):l.jsx("div",{className:"h-full flex flex-col",children:l.jsxs("div",{className:"h-full flex flex-col bg-background",children:[l.jsx("div",{className:"flex items-center justify-between px-6 py-5 border-b border-border bg-background",children:l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(wn,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Authentication"})]}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage OAuth authentication for the selected server"})]})}),l.jsx("div",{className:"flex-1 overflow-auto px-6 py-6",children:l.jsxs("div",{className:"space-y-6 max-w-2xl",children:[E,l.jsxs("div",{className:"rounded-md border p-4 space-y-2",children:[l.jsx("h3",{className:"text-sm font-medium",children:"Selected Server"}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:[l.jsxs("div",{children:["Name: ",t?.name||"Unknown"]}),w&&l.jsxs("div",{children:["URL: ",e.url.toString()]}),!w&&l.jsxs("div",{children:["Command: ",e.command]}),l.jsxs("div",{children:["Type: ",w?"HTTP Server":"STDIO Server"]})]})]}),l.jsx(vx,{children:l.jsx(h9e,{className:"pt-6",children:l.jsxs("div",{className:"text-center space-y-4",children:[l.jsx("div",{className:"mx-auto w-12 h-12 bg-muted rounded-full flex items-center justify-center",children:l.jsx(wn,{className:"h-6 w-6 text-muted-foreground"})}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("h3",{className:"text-lg font-medium",children:w?"No Authentication Required":"No OAuth Support"}),l.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:w?`The HTTP server "${t?.name||"Unknown"}" is connected without OAuth authentication.`:"STDIO servers don't support OAuth authentication."}),w&&l.jsx("p",{className:"text-xs text-muted-foreground max-w-md mx-auto mt-2",children:"If this server supports OAuth, you can reconnect it with OAuth enabled from the Servers tab."})]})]})})})]})})]})}):l.jsx(Rc,{icon:lA,title:"No Server Selected",description:"Connect to an MCP server to manage authentication and OAuth settings."})},PZ={isInitiatingAuth:!1,currentStep:"idle",httpHistory:[],infoLogs:[],tokenEndpointAuthMethod:void 0},CC=PZ;function cKt(e,t){return[{id:"request_without_token",label:"MCP request without token",description:"Client makes initial request without authorization",from:"client",to:"mcpServer",details:e.serverUrl?[{label:"POST",value:e.serverUrl},{label:"method",value:"initialize"}]:void 0},{id:"received_401_unauthorized",label:"HTTP 401 Unauthorized with WWW-Authenticate header",description:"Server returns 401 with WWW-Authenticate header",from:"mcpServer",to:"client",details:e.resourceMetadataUrl?[{label:"Note",value:"Extract resource_metadata URL"}]:void 0},{id:"request_resource_metadata",label:"Request Protected Resource Metadata",description:"Client requests metadata from well-known URI",from:"client",to:"mcpServer",details:e.resourceMetadataUrl?[{label:"GET",value:new URL(e.resourceMetadataUrl).pathname}]:void 0},{id:"received_resource_metadata",label:"Return metadata",description:"Server returns OAuth protected resource metadata",from:"mcpServer",to:"client",details:e.resourceMetadata?.authorization_servers?[{label:"Auth Server",value:e.resourceMetadata.authorization_servers[0]}]:void 0},{id:"request_authorization_server_metadata",label:"GET Authorization server metadata endpoint",description:"Try RFC8414 path, then RFC8414 root (no OIDC support)",from:"client",to:"authServer",details:e.authorizationServerUrl?[{label:"URL",value:e.authorizationServerUrl},{label:"Protocol",value:"2025-06-18"}]:void 0},{id:"received_authorization_server_metadata",label:"Authorization server metadata response",description:"Authorization Server returns metadata",from:"authServer",to:"client",details:e.authorizationServerMetadata?[{label:"Token",value:new URL(e.authorizationServerMetadata.token_endpoint).pathname},{label:"Auth",value:new URL(e.authorizationServerMetadata.authorization_endpoint).pathname}]:void 0},...t==="dcr"?[{id:"request_client_registration",label:"POST /register (2025-06-18)",description:"Client registers dynamically with Authorization Server",from:"client",to:"authServer",details:[{label:"Note",value:"Dynamic client registration (DCR)"}]},{id:"received_client_credentials",label:"Client Credentials",description:"Authorization Server returns client ID and credentials",from:"authServer",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."}]:void 0}]:[{id:"received_client_credentials",label:"Use Pre-registered Client (2025-06-18)",description:"Client uses pre-configured credentials (skipped DCR)",from:"client",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."},{label:"Note",value:"Pre-registered (no DCR needed)"}]:[{label:"Note",value:"Pre-registered client credentials"}]}],{id:"generate_pkce_parameters",label:"Generate PKCE parameters",description:"Client generates code verifier and challenge (recommended), includes resource parameter",from:"client",to:"client",details:e.codeChallenge?[{label:"code_challenge",value:e.codeChallenge.substring(0,15)+"..."},{label:"method",value:e.codeChallengeMethod||"S256"},{label:"resource",value:e.serverUrl||"—"},{label:"Protocol",value:"2025-06-18"}]:void 0},{id:"authorization_request",label:"Open browser with authorization URL",description:"Client opens browser with authorization URL + code_challenge + resource",from:"client",to:"browser",details:e.authorizationUrl?[{label:"code_challenge",value:e.codeChallenge?.substring(0,12)+"..."||"S256"},{label:"resource",value:e.serverUrl||""}]:void 0},{id:"browser_to_auth_server",label:"Authorization request with resource parameter",description:"Browser navigates to authorization endpoint",from:"browser",to:"authServer",details:e.authorizationUrl?[{label:"Note",value:"User authorizes in browser"}]:void 0},{id:"auth_redirect_to_browser",label:"Redirect to callback with authorization code",description:"Authorization Server redirects browser back to callback URL",from:"authServer",to:"browser",details:e.authorizationCode?[{label:"code",value:e.authorizationCode.substring(0,20)+"..."}]:void 0},{id:"received_authorization_code",label:"Authorization code callback",description:"Browser redirects back to client with authorization code",from:"browser",to:"client",details:e.authorizationCode?[{label:"code",value:e.authorizationCode.substring(0,20)+"..."}]:void 0},{id:"token_request",label:"Token request + code_verifier + resource",description:"Client exchanges authorization code for access token",from:"client",to:"authServer",details:e.codeVerifier?[{label:"grant_type",value:"authorization_code"},{label:"resource",value:e.serverUrl||""}]:void 0},{id:"received_access_token",label:"Access token (+ refresh token)",description:"Authorization Server returns access token",from:"authServer",to:"client",details:e.accessToken?[{label:"token_type",value:e.tokenType||"Bearer"},{label:"expires_in",value:e.expiresIn?.toString()||"3600"}]:void 0},{id:"authenticated_mcp_request",label:"MCP request with access token",description:"Client makes authenticated request to MCP server",from:"client",to:"mcpServer",details:e.accessToken?[{label:"POST",value:"tools/list"},{label:"Authorization",value:"Bearer "+e.accessToken.substring(0,15)+"..."}]:void 0},{id:"complete",label:"MCP response",description:"MCP Server returns successful response",from:"mcpServer",to:"client",details:e.accessToken?[{label:"Status",value:"200 OK"},{label:"Content",value:"tools, resources, prompts"}]:void 0}]}function Sme(e){const t=new URL(e),n=[];if(t.pathname==="/"||t.pathname==="")n.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString());else{const r=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;n.push(new URL(`/.well-known/oauth-authorization-server${r}`,t.origin).toString()),n.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString())}return n}const dKt=e=>{const{state:t,getState:n,updateState:r,serverUrl:i,serverName:a,redirectUrl:s,fetchFn:o=fetch,customScopes:u,customHeaders:c,registrationStrategy:d="dcr"}=e,f=s||`${window.location.origin}/oauth/callback/debug`,p=(v={})=>({...c,...v}),m=()=>n?n():t,y={state:t,updateState:r,proceedToNextStep:async()=>{const v=m();r({isInitiatingAuth:!0});try{switch(v.currentStep){case"idle":const x=p({"Content-Type":"application/json"}),_={method:"POST",url:i,headers:x,body:{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:1}};r({currentStep:"request_without_token",serverUrl:i,lastRequest:_,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:_}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"request_without_token":if(!v.serverUrl)throw new Error("No server URL available");try{const Z=await ua(v.serverUrl,{method:"POST",headers:p({"Content-Type":"application/json"}),body:JSON.stringify({jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:1})}),ne={status:Z.status,statusText:Z.statusText,headers:Z.headers,body:Z.body},J=[...v.httpHistory||[]];if(J.length>0){const se=J[J.length-1];se.response=ne,se.duration=Date.now()-(se.timestamp||Date.now())}if(Z.status===401){const se=Z.headers["www-authenticate"],ie=se?yn(v,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:se,"Received from":v.serverUrl||"Unknown"}):v.infoLogs;r({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:se||void 0,lastResponse:ne,httpHistory:J,infoLogs:ie,isInitiatingAuth:!1})}else if(Z.status===200){const se=yn(v,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});r({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,lastResponse:ne,httpHistory:J,infoLogs:se,isInitiatingAuth:!1})}else throw r({lastResponse:ne,httpHistory:J}),new Error(`Expected 401 Unauthorized but got HTTP ${Z.status}: ${Z.body?.error?.message||Z.statusText}`)}catch(Z){throw new Error(`Failed to request MCP server: ${Z instanceof Error?Z.message:String(Z)}`)}break;case"received_401_unauthorized":let S;if(v.wwwAuthenticateHeader){const Z=v.wwwAuthenticateHeader.match(/resource_metadata="([^"]+)"/);Z&&(S=Z[1])}if(!S&&v.serverUrl&&(S=USe(v.serverUrl)),!S)throw new Error("Could not determine resource metadata URL");const w={method:"GET",url:S,headers:p({})};r({currentStep:"request_resource_metadata",resourceMetadataUrl:S,lastRequest:w,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:w}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"request_resource_metadata":if(!v.serverUrl)throw new Error("No server URL available");const T=[...v.httpHistory||[]];let N=T.length>0&&T[T.length-1]?.step==="request_resource_metadata"&&!T[T.length-1]?.response?T.pop():void 0;const E=[],A=Z=>Z?Z instanceof Headers?Object.fromEntries(Z.entries()):Array.isArray(Z)?Object.fromEntries(Z):Object.fromEntries(Object.entries(Z).map(([ne,J])=>[ne,String(J)])):{},I=async(Z,ne={})=>{const J=typeof Z=="string"?Z:Z.toString(),se=p(A(ne.headers)),ie=N?{...N,timestamp:Date.now(),request:{method:ne.method||"GET",url:J,headers:se,body:ne.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:ne.method||"GET",url:J,headers:se,body:ne.body}};N=void 0,E.push(ie);try{const he=await ua(J,{method:ne.method||"GET",headers:se,body:ne.body});ie.response={status:he.status,statusText:he.statusText,headers:he.headers,body:he.body},ie.duration=Date.now()-ie.timestamp;const ye={status:he.status,statusText:he.statusText,headers:he.headers},Ne=typeof he.body=="string"?he.body:JSON.stringify(he.body??{});return new Response(Ne,ye)}catch(he){throw ie.error=$d(he),ie.duration=Date.now()-ie.timestamp,he}};try{const Z=v.wwwAuthenticateHeader&&v.resourceMetadataUrl?{resourceMetadataUrl:v.resourceMetadataUrl}:void 0,ne=await d3(v.serverUrl,Z,I),J=[...T,...E],se=E[E.length-1],ie=ne.authorization_servers?.[0]||i,he=yn(v,"received_resource_metadata","authorization-servers","Authorization Servers",{Resource:ne.resource,"Authorization Servers":ne.authorization_servers});r({currentStep:"received_resource_metadata",resourceMetadata:ne,resourceMetadataUrl:se?.request?.url||v.resourceMetadataUrl,authorizationServerUrl:ie,lastRequest:se?.request,lastResponse:se?.response,httpHistory:J,infoLogs:he,isInitiatingAuth:!1})}catch(Z){const ne=Rw([...T,...E],$d(Z));throw r({lastResponse:E[E.length-1]?.response,httpHistory:ne}),new Error(`Failed to request resource metadata: ${Z instanceof Error?Z.message:String(Z)}`)}break;case"received_resource_metadata":if(!v.authorizationServerUrl)throw new Error("No authorization server URL available");const $={method:"GET",url:Sme(v.authorizationServerUrl)[0],headers:p({})};r({currentStep:"request_authorization_server_metadata",lastRequest:$,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:$}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"request_authorization_server_metadata":if(!v.authorizationServerUrl)throw new Error("No authorization server URL available");const O=Sme(v.authorizationServerUrl);let R=null,U=null,z="",F={},D={},W=null;for(const Z of O)try{const ne=p({}),J=[...v.httpHistory||[]];J.length>0&&(J[J.length-1].request={method:"GET",url:Z,headers:ne}),r({lastRequest:{method:"GET",url:Z,headers:ne},httpHistory:J});const se=await ua(Z,{method:"GET",headers:p({})});if(se.ok){R=se.body,z=Z,F=ne,D=se.headers,W=se;break}else{if(se.status>=400&&se.status<500)continue;U=new Error(`HTTP ${se.status} from ${Z}`)}}catch(ne){U=ne;continue}if(!R||!W)throw new Error(`Could not discover authorization server metadata. Last error: ${U instanceof Error?U.message:String(U)}`);if(!R.issuer)throw new Error("Authorization server metadata missing required 'issuer' field");if(!R.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!R.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!R.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const q={status:W.status,statusText:W.statusText,headers:D,body:R},X=[...v.httpHistory||[]];X.length>0&&(X[X.length-1].response=q);const L=R.code_challenge_methods_supported||[],Y={Issuer:R.issuer,"Authorization Endpoint":R.authorization_endpoint,"Token Endpoint":R.token_endpoint};R.registration_endpoint&&(Y["Registration Endpoint"]=R.registration_endpoint),R.code_challenge_methods_supported&&(Y["PKCE Methods"]=R.code_challenge_methods_supported),R.grant_types_supported&&(Y["Grant Types"]=R.grant_types_supported),R.response_types_supported&&(Y["Response Types"]=R.response_types_supported),R.scopes_supported&&(Y.Scopes=R.scopes_supported);const G=yn(m(),"received_authorization_server_metadata","as-metadata","Authorization Server Metadata",Y);L.includes("S256")?r({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:R,lastResponse:q,httpHistory:X,infoLogs:G,isInitiatingAuth:!1}):(console.warn("Authorization server may not support S256 PKCE method. Supported methods:",L),r({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:R,lastResponse:q,httpHistory:X,infoLogs:G,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1}));break;case"received_authorization_server_metadata":if(!v.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(d==="preregistered"){const{clientId:Z,clientSecret:ne}=FH(a);if(!Z){r({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const J={"Client ID":Z,"Client Secret":ne?"Configured":"Not provided (public client)","Token Auth Method":ne?"client_secret_post":"none",Note:"Using pre-registered client credentials from server config (skipped DCR)"},se=yn(m(),"received_client_credentials","dcr","Pre-registered Client",J);r({currentStep:"received_client_credentials",clientId:Z,clientSecret:ne||void 0,tokenEndpointAuthMethod:ne?"client_secret_post":"none",infoLogs:se,isInitiatingAuth:!1})}else if(v.authorizationServerMetadata.registration_endpoint){const Z=v.resourceMetadata?.scopes_supported||v.authorizationServerMetadata.scopes_supported,ne={client_name:"MCPJam Inspector Debug Client",redirect_uris:[f],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"};Z&&Z.length>0&&(ne.scope=Z.join(" "));const J={method:"POST",url:v.authorizationServerMetadata.registration_endpoint,headers:p({"Content-Type":"application/json"}),body:ne};r({currentStep:"request_client_registration",lastRequest:J,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:J}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return}else r({currentStep:"generate_pkce_parameters",clientId:"mock-client-id-for-demo",tokenEndpointAuthMethod:"none",isInitiatingAuth:!1});break;case"request_client_registration":if(!v.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!v.lastRequest?.body)throw new Error("No client metadata in request");try{const Z=await ua(v.authorizationServerMetadata.registration_endpoint,{method:"POST",headers:p({"Content-Type":"application/json"}),body:JSON.stringify(v.lastRequest.body)}),ne={status:Z.status,statusText:Z.statusText,headers:Z.headers,body:Z.body},J=[...v.httpHistory||[]];if(J.length>0){const se=J[J.length-1];se.response=ne,se.duration=Date.now()-(se.timestamp||Date.now())}if(!Z.ok)r({lastResponse:ne,httpHistory:J,error:`Dynamic Client Registration failed (${Z.status}). Using fallback client ID.`}),r({currentStep:"received_client_credentials",clientId:"preregistered-client-id",clientSecret:void 0,tokenEndpointAuthMethod:"none",isInitiatingAuth:!1});else{const se=Z.body,ie={"Client ID":se.client_id,"Client Name":se.client_name,"Token Auth Method":se.token_endpoint_auth_method||"none","Redirect URIs":se.redirect_uris,"Grant Types":se.grant_types,"Response Types":se.response_types};se.client_secret&&(ie["Client Secret"]=se.client_secret.substring(0,20)+"...",ie.Note="Server issued client_secret - this will be used in token requests");const he=yn(m(),"received_client_credentials","dcr","Dynamic Client Registration",ie);r({currentStep:"received_client_credentials",clientId:se.client_id,clientSecret:se.client_secret,tokenEndpointAuthMethod:se.token_endpoint_auth_method||"none",lastResponse:ne,httpHistory:J,infoLogs:he,error:void 0,isInitiatingAuth:!1})}}catch(Z){const ne={status:0,statusText:"Network Error",headers:p({}),body:{error:Z instanceof Error?Z.message:String(Z)}},J=[...v.httpHistory||[]];if(J.length>0){const ie=J[J.length-1];ie.response=ne,ie.duration=Date.now()-(ie.timestamp||Date.now())}r({lastResponse:ne,httpHistory:J,error:`Client registration failed: ${Z instanceof Error?Z.message:String(Z)}. Using fallback.`}),r({currentStep:"received_client_credentials",clientId:"preregistered-client-id",clientSecret:void 0,tokenEndpointAuthMethod:"none",isInitiatingAuth:!1})}break;case"received_client_credentials":const P=Vm(43),V=await UH(P),K=yn(m(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:V,method:"S256",resource:v.serverUrl||"Unknown"});r({currentStep:"generate_pkce_parameters",codeVerifier:P,codeChallenge:V,codeChallengeMethod:"S256",state:Vm(16),infoLogs:K,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!v.authorizationServerMetadata?.authorization_endpoint||!v.clientId)throw new Error("Missing authorization endpoint or client ID");const Q=new URL(v.authorizationServerMetadata.authorization_endpoint);if(Q.searchParams.set("response_type","code"),Q.searchParams.set("client_id",v.clientId),Q.searchParams.set("redirect_uri",f),Q.searchParams.set("code_challenge",v.codeChallenge||""),Q.searchParams.set("code_challenge_method","S256"),Q.searchParams.set("state",v.state||""),v.serverUrl&&Q.searchParams.set("resource",v.serverUrl),u)Q.searchParams.set("scope",u);else{const Z=v.resourceMetadata?.scopes_supported||v.authorizationServerMetadata.scopes_supported,ne=new Set;Z&&Z.length>0&&Z.forEach(J=>ne.add(J)),Z?.includes("offline_access")&&ne.add("offline_access"),ne.size>0&&Q.searchParams.set("scope",Array.from(ne).join(" "))}const oe=yn(m(),"authorization_request","auth-url","Authorization URL",{url:Q.toString()});r({currentStep:"authorization_request",authorizationUrl:Q.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:oe,isInitiatingAuth:!1});break;case"authorization_request":r({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":if(!v.authorizationCode||v.authorizationCode.trim()===""){r({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!v.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const re={grant_type:"authorization_code",code:v.authorizationCode,redirect_uri:f};v.clientId&&(re.client_id=v.clientId),v.clientSecret&&(re.client_secret=v.clientSecret),v.codeVerifier&&(re.code_verifier=v.codeVerifier),v.serverUrl&&(re.resource=v.serverUrl);const ee={method:"POST",url:v.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded"},body:re};r({currentStep:"token_request",lastRequest:ee,lastResponse:void 0,accessToken:void 0,refreshToken:void 0,httpHistory:[...v.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:ee}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"token_request":if(!v.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!v.authorizationCode)throw new Error("Missing authorization code");if(!v.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const Z=new URLSearchParams({grant_type:"authorization_code",code:v.authorizationCode,redirect_uri:f,client_id:v.clientId||"",code_verifier:v.codeVerifier||""});v.clientSecret&&Z.set("client_secret",v.clientSecret),v.serverUrl&&Z.set("resource",v.serverUrl);const ne=await ua(v.authorizationServerMetadata.token_endpoint,{method:"POST",headers:p({"Content-Type":"application/x-www-form-urlencoded"}),body:Z.toString()}),J={status:ne.status,statusText:ne.statusText,headers:ne.headers,body:ne.body},se=[...v.httpHistory||[]];if(se.length>0){const Ne=se[se.length-1];Ne.response=J,Ne.duration=Date.now()-(Ne.timestamp||Date.now())}if(!ne.ok){r({lastResponse:J,httpHistory:se,authorizationCode:void 0,error:`Token request failed: ${ne.body?.error||ne.statusText} - ${ne.body?.error_description||"Unknown error"}`,isInitiatingAuth:!1});return}const ie=ne.body;let ye=(m().infoLogs||[]).filter(Ne=>Ne.id!=="auth-code"&&Ne.id!=="oauth-tokens"&&Ne.id!=="token");if(v.authorizationCode&&(ye=[...ye,{id:"auth-code",step:"token_request",level:"info",label:"Authorization Code",data:{code:v.authorizationCode},timestamp:Date.now()}]),ie.access_token){const Ne={access_token:ie.access_token};ie.refresh_token&&(Ne.refresh_token=ie.refresh_token),ye=[...ye,{id:"oauth-tokens",step:"token_request",level:"info",label:"OAuth Tokens",data:Ne,timestamp:Date.now()}]}if(ie.access_token){const Ne=Gm(ie.access_token);if(Ne){const ce={...Ne};ce.exp&&(ce.exp=`${ce.exp} (${Ji(ce.exp)})`),ce.iat&&(ce.iat=`${ce.iat} (${Ji(ce.iat)})`),ce.nbf&&(ce.nbf=`${ce.nbf} (${Ji(ce.nbf)})`);const Te={...ce};if(ce.aud){const we=v.serverUrl,Ue=(Array.isArray(ce.aud)?ce.aud:[ce.aud]).some(Me=>Me===we);Te._validation={expected_audience:we,audience_matches:Ue,note:Ue?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Te._validation={note:"⚠ No audience claim found - server should validate token binding"};ye=[...ye,{id:"token",step:"token_request",level:"info",label:"Access Token (Decoded JWT)",data:Te,timestamp:Date.now()}]}}if(ie.id_token){const Ne=Gm(ie.id_token);if(Ne){const ce={...Ne};ce.exp&&(ce.exp=`${ce.exp} (${Ji(ce.exp)})`),ce.iat&&(ce.iat=`${ce.iat} (${Ji(ce.iat)})`),ce.nbf&&(ce.nbf=`${ce.nbf} (${Ji(ce.nbf)})`),ce.auth_time&&(ce.auth_time=`${ce.auth_time} (${Ji(ce.auth_time)})`),ce._note="OIDC ID Token - Used for user identity verification",ye=[...ye,{id:"id-token",step:"token_request",level:"info",label:"ID Token (OIDC - Decoded JWT)",data:ce,timestamp:Date.now()}]}}r({currentStep:"received_access_token",accessToken:ie.access_token,refreshToken:ie.refresh_token,tokenType:ie.token_type||"Bearer",expiresIn:ie.expires_in,lastResponse:J,httpHistory:se,infoLogs:ye,error:void 0,isInitiatingAuth:!1})}catch(Z){const ne={status:0,statusText:"Network Error",headers:p({}),body:{error:Z instanceof Error?Z.message:String(Z)}},J=[...v.httpHistory||[]];if(J.length>0){const se=J[J.length-1];se.response=ne,se.duration=Date.now()-(se.timestamp||Date.now())}r({lastResponse:ne,httpHistory:J,error:`Token exchange failed: ${Z instanceof Error?Z.message:String(Z)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!v.serverUrl||!v.accessToken)throw new Error("Missing server URL or access token");const le={method:"POST",url:v.serverUrl,headers:{Authorization:`Bearer ${v.accessToken}`,"Content-Type":"application/json","MCP-Protocol-Version":"2025-06-18"},body:{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:2}},te=yn(m(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-06-18",Client:"MCPJam Inspector v1.0.0",Endpoint:v.serverUrl});r({currentStep:"authenticated_mcp_request",lastRequest:le,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:le}],infoLogs:te,isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"authenticated_mcp_request":if(!v.serverUrl||!v.accessToken)throw new Error("Missing server URL or access token");try{const Z=await ua(v.serverUrl,{method:"POST",headers:p({Authorization:`Bearer ${v.accessToken}`,"Content-Type":"application/json"}),body:JSON.stringify({jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:2})}),ne={status:Z.status,statusText:Z.statusText,headers:Z.headers,body:Z.body},J=[...v.httpHistory||[]];if(J.length>0){const Ne=J[J.length-1];Ne.response=ne,Ne.duration=Date.now()-(Ne.timestamp||Date.now())}if(!Z.ok){r({lastResponse:ne,httpHistory:J,error:`Authenticated request failed: ${Z.status} ${Z.statusText}`,isInitiatingAuth:!1});return}let se=m().infoLogs||[];const ie=Z.headers["content-type"]||"",he=ie.includes("text/event-stream");let ye=null;if(he&&Z.body?.transport==="sse"?ye=Z.body.mcpResponse:ye=Z.body,he&&ye?.result?.protocolVersion){const Ne={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":ye.result.protocolVersion};ye.result.serverInfo&&(Ne["Server Name"]=ye.result.serverInfo.name,Ne["Server Version"]=ye.result.serverInfo.version),ye.result.capabilities&&(Ne.Capabilities=ye.result.capabilities),se=yn(m(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",Ne)}else if(he)se=yn(m(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":ie,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:Z.body?.events?`${Z.body.events.length} events parsed`:"No events parsed"});else if(ye?.result?.protocolVersion){const Ne={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":ye.result.protocolVersion};ye.result.serverInfo&&(Ne["Server Name"]=ye.result.serverInfo.name,Ne["Server Version"]=ye.result.serverInfo.version),ye.result.capabilities&&(Ne.Capabilities=ye.result.capabilities),se=yn(m(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",Ne)}r({currentStep:"complete",lastResponse:ne,httpHistory:J,infoLogs:se,error:void 0,isInitiatingAuth:!1})}catch(Z){const ne=$d(Z),J={status:0,statusText:"Network Error",headers:p({}),body:{error:ne.message,details:ne.details}},se=[...v.httpHistory||[]];if(se.length>0){const ye={...se[se.length-1],response:J,duration:Date.now()-(se[se.length-1]?.timestamp||Date.now()),error:ne};se[se.length-1]=ye}const ie=m(),he=yn(ie,"authenticated_mcp_request",`error-authenticated_mcp_request-${Date.now()}`,"Authenticated MCP request failed",{request:ie.lastRequest,error:ne},{level:"error",error:ne});r({lastResponse:J,httpHistory:se,infoLogs:he,error:`Authenticated MCP request failed: ${ne.message}`,isInitiatingAuth:!1})}break;case"complete":r({isInitiatingAuth:!1});break;default:r({isInitiatingAuth:!1});break}}catch(x){const _=m(),S=$d(x),w=yn(_,_.currentStep,`error-${_.currentStep}-${Date.now()}`,"Step failed",{step:_.currentStep,request:_.lastRequest,response:_.lastResponse,error:S},{level:"error",error:S}),T=Rw(_.httpHistory,S),N={error:S.message,infoLogs:w,isInitiatingAuth:!1};T&&(N.httpHistory=T),r(N)}},startGuidedFlow:async()=>{r({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{r({...CC,lastRequest:void 0,lastResponse:void 0,httpHistory:[],infoLogs:[],authorizationCode:void 0,authorizationUrl:void 0,accessToken:void 0,refreshToken:void 0,codeVerifier:void 0,codeChallenge:void 0,error:void 0})}};return y},fKt=PZ;function pKt(e,t){return[{id:"request_authorization_server_metadata",label:"GET /.well-known/oauth-authorization-server from MCP base URL",description:"Direct discovery from MCP server base URL with fallback to /authorize, /token, /register",from:"client",to:"authServer",details:e.authorizationServerUrl?[{label:"URL",value:e.authorizationServerUrl},{label:"Protocol",value:"2025-03-26"}]:void 0},{id:"received_authorization_server_metadata",label:"Authorization server metadata response",description:"Authorization Server returns metadata",from:"authServer",to:"client",details:e.authorizationServerMetadata?[{label:"Token",value:new URL(e.authorizationServerMetadata.token_endpoint).pathname},{label:"Auth",value:new URL(e.authorizationServerMetadata.authorization_endpoint).pathname}]:void 0},...t==="dcr"?[{id:"request_client_registration",label:"POST /register (2025-03-26)",description:"Client registers dynamically with Authorization Server",from:"client",to:"authServer",details:[{label:"Note",value:"Dynamic client registration (DCR)"}]},{id:"received_client_credentials",label:"Client Credentials",description:"Authorization Server returns client ID and credentials",from:"authServer",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."}]:void 0}]:[{id:"received_client_credentials",label:"Use Pre-registered Client (2025-03-26)",description:"Client uses pre-configured credentials (skipped DCR)",from:"client",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."},{label:"Note",value:"Pre-registered (no DCR needed)"}]:[{label:"Note",value:"Pre-registered client credentials"}]}],{id:"generate_pkce_parameters",label:"Generate PKCE parameters",description:"Client generates code verifier and challenge (recommended), includes resource parameter",from:"client",to:"client",details:e.codeChallenge?[{label:"code_challenge",value:e.codeChallenge.substring(0,15)+"..."},{label:"method",value:e.codeChallengeMethod||"S256"},{label:"resource",value:e.serverUrl||"—"},{label:"Protocol",value:"2025-03-26"}]:void 0},{id:"authorization_request",label:"Open browser with authorization URL",description:"Client opens browser with authorization URL + code_challenge + resource",from:"client",to:"browser",details:e.authorizationUrl?[{label:"code_challenge",value:e.codeChallenge?.substring(0,12)+"..."||"S256"},{label:"resource",value:e.serverUrl||""}]:void 0},{id:"browser_to_auth_server",label:"Authorization request with resource parameter",description:"Browser navigates to authorization endpoint",from:"browser",to:"authServer",details:e.authorizationUrl?[{label:"Note",value:"User authorizes in browser"}]:void 0},{id:"auth_redirect_to_browser",label:"Redirect to callback with authorization code",description:"Authorization Server redirects browser back to callback URL",from:"authServer",to:"browser",details:e.authorizationCode?[{label:"code",value:e.authorizationCode.substring(0,20)+"..."}]:void 0},{id:"received_authorization_code",label:"Authorization code callback",description:"Browser redirects back to client with authorization code",from:"browser",to:"client",details:e.authorizationCode?[{label:"code",value:e.authorizationCode.substring(0,20)+"..."}]:void 0},{id:"token_request",label:"Token request + code_verifier + resource",description:"Client exchanges authorization code for access token",from:"client",to:"authServer",details:e.codeVerifier?[{label:"grant_type",value:"authorization_code"},{label:"resource",value:e.serverUrl||""}]:void 0},{id:"received_access_token",label:"Access token (+ refresh token)",description:"Authorization Server returns access token",from:"authServer",to:"client",details:e.accessToken?[{label:"token_type",value:e.tokenType||"Bearer"},{label:"expires_in",value:e.expiresIn?.toString()||"3600"}]:void 0},{id:"authenticated_mcp_request",label:"MCP request with access token",description:"Client makes authenticated request to MCP server",from:"client",to:"mcpServer",details:e.accessToken?[{label:"POST",value:"tools/list"},{label:"Authorization",value:"Bearer "+e.accessToken.substring(0,15)+"..."}]:void 0},{id:"complete",label:"MCP response",description:"MCP Server returns successful response",from:"mcpServer",to:"client",details:e.accessToken?[{label:"Status",value:"200 OK"},{label:"Content",value:"tools, resources, prompts"}]:void 0}]}function hKt(e){return new URL(e).origin}function kme(e){const t=new URL(e),n=[];if(t.pathname==="/"||t.pathname==="")n.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString());else{const r=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;n.push(new URL(`/.well-known/oauth-authorization-server${r}`,t.origin).toString()),n.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString())}return n}const mKt=e=>{const{state:t,getState:n,updateState:r,serverUrl:i,serverName:a,redirectUrl:s,fetchFn:o=fetch,customScopes:u,customHeaders:c,registrationStrategy:d="dcr"}=e,f=s||`${window.location.origin}/oauth/callback/debug`,p=(v={})=>({...c,...v}),m=()=>n?n():t,y={state:t,updateState:r,proceedToNextStep:async()=>{const v=m();r({isInitiatingAuth:!0});try{switch(v.currentStep){case"idle":r({currentStep:"discovery_start",serverUrl:i,httpHistory:[],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"request_without_token":if(!v.serverUrl)throw new Error("No server URL available");try{const G=await ua(v.serverUrl,{method:"POST",headers:p({"Content-Type":"application/json"}),body:JSON.stringify({jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCP Inspector",version:"1.0.0"}},id:1})}),P={status:G.status,statusText:G.statusText,headers:G.headers,body:G.body},V=[...v.httpHistory||[]];if(V.length>0){const K=V[V.length-1];K.response=P,K.duration=Date.now()-(K.timestamp||Date.now())}if(G.status===401||G.status===200){const K=G.status===200?yn(v,"discovery_start","optional-auth","Optional Authentication",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"}):v.infoLogs;r({currentStep:"discovery_start",lastResponse:P,httpHistory:V,infoLogs:K,isInitiatingAuth:!1})}else throw r({lastResponse:P,httpHistory:V}),new Error(`Expected 401 or 200 but got HTTP ${G.status}: ${G.body?.error?.message||G.statusText}`)}catch(G){throw new Error(`Failed to request MCP server: ${G instanceof Error?G.message:String(G)}`)}break;case"discovery_start":const x=hKt(v.serverUrl),S={method:"GET",url:kme(x)[0],headers:p({})};r({currentStep:"request_authorization_server_metadata",authorizationServerUrl:x,lastRequest:S,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:S}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"request_authorization_server_metadata":if(!v.authorizationServerUrl)throw new Error("No authorization server URL available");const w=kme(v.authorizationServerUrl);let T=null,N=null,E="",A=null;for(const G of w)try{const P=p({}),V=[...v.httpHistory||[]];V.length>0&&(V[V.length-1].request={method:"GET",url:G,headers:P}),r({lastRequest:{method:"GET",url:G,headers:P},httpHistory:V});const K=await ua(G,{method:"GET",headers:p({"MCP-Protocol-Version":"2025-03-26"})});if(K.ok){T=K.body,E=G,A=K;break}else{if(K.status>=400&&K.status<500)continue;N=new Error(`HTTP ${K.status} from ${G}`)}}catch(P){N=P;continue}if(!T){const G=v.authorizationServerUrl;T={issuer:G,authorization_endpoint:`${G}/authorize`,token_endpoint:`${G}/token`,registration_endpoint:`${G}/register`,response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]};const P=yn(m(),"received_authorization_server_metadata","fallback-endpoints","Using Fallback Endpoints",{Note:"Metadata discovery failed, using default endpoints per 2025-03-26 spec","Authorization Endpoint":T.authorization_endpoint,"Token Endpoint":T.token_endpoint,"Registration Endpoint":T.registration_endpoint});r({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:T,infoLogs:P,isInitiatingAuth:!1});break}if(!T.issuer)throw new Error("Authorization server metadata missing required 'issuer' field");if(!T.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!T.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!T.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const I={status:A.status,statusText:A.statusText,headers:A.headers,body:T},M=[...v.httpHistory||[]];if(M.length>0){const G=M[M.length-1];G.response=I,G.duration=Date.now()-(G.timestamp||Date.now())}const $=T.code_challenge_methods_supported||[],O={Issuer:T.issuer,"Authorization Endpoint":T.authorization_endpoint,"Token Endpoint":T.token_endpoint};T.registration_endpoint&&(O["Registration Endpoint"]=T.registration_endpoint),T.code_challenge_methods_supported&&(O["PKCE Methods"]=T.code_challenge_methods_supported),T.grant_types_supported&&(O["Grant Types"]=T.grant_types_supported),T.response_types_supported&&(O["Response Types"]=T.response_types_supported),T.scopes_supported&&(O.Scopes=T.scopes_supported);const R=yn(m(),"received_authorization_server_metadata","as-metadata","Authorization Server Metadata",O);(!$||$.length===0||!$.includes("S256"))&&console.warn("Authorization server may not support PKCE S256 (REQUIRED for 2025-03-26 spec)"),r({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:T,lastResponse:I,httpHistory:M,infoLogs:R,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!v.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(d==="preregistered"){const{clientId:G,clientSecret:P}=FH(a);if(!G){r({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const V={"Client ID":G,"Client Secret":P?"Configured":"Not provided (public client)","Token Auth Method":P?"client_secret_post":"none",Note:"Using pre-registered client credentials (skipped DCR)"},K=yn(m(),"received_client_credentials","dcr","Pre-registered Client",V);r({currentStep:"received_client_credentials",clientId:G,clientSecret:P||void 0,tokenEndpointAuthMethod:P?"client_secret_post":"none",infoLogs:K,isInitiatingAuth:!1})}else if(v.authorizationServerMetadata.registration_endpoint){const G=v.authorizationServerMetadata.scopes_supported,P={client_name:"MCP Inspector Debug Client",redirect_uris:[f],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"};G&&G.length>0&&(P.scope=G.join(" "));const V={method:"POST",url:v.authorizationServerMetadata.registration_endpoint,headers:p({"Content-Type":"application/json"}),body:P};r({currentStep:"request_client_registration",lastRequest:V,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:V}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return}else r({currentStep:"generate_pkce_parameters",clientId:"mock-client-id-for-demo",tokenEndpointAuthMethod:"none",isInitiatingAuth:!1});break;case"request_client_registration":if(!v.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!v.lastRequest?.body)throw new Error("No client metadata in request");try{const G=await ua(v.authorizationServerMetadata.registration_endpoint,{method:"POST",headers:p({"Content-Type":"application/json"}),body:JSON.stringify(v.lastRequest.body)}),P={status:G.status,statusText:G.statusText,headers:G.headers,body:G.body},V=[...v.httpHistory||[]];if(V.length>0){const K=V[V.length-1];K.response=P,K.duration=Date.now()-(K.timestamp||Date.now())}if(!G.ok)r({lastResponse:P,httpHistory:V,error:`Dynamic Client Registration failed (${G.status}). Using fallback client ID.`}),r({currentStep:"received_client_credentials",clientId:"preregistered-client-id",clientSecret:void 0,tokenEndpointAuthMethod:"none",isInitiatingAuth:!1});else{const K=G.body,Q={"Client ID":K.client_id,"Client Name":K.client_name,"Token Auth Method":K.token_endpoint_auth_method||"none","Redirect URIs":K.redirect_uris,"Grant Types":K.grant_types,"Response Types":K.response_types};K.client_secret&&(Q["Client Secret"]=K.client_secret.substring(0,20)+"...",Q.Note="Server issued client_secret - this will be used in token requests");const oe=yn(m(),"received_client_credentials","dcr","Dynamic Client Registration",Q);r({currentStep:"received_client_credentials",clientId:K.client_id,clientSecret:K.client_secret,tokenEndpointAuthMethod:K.token_endpoint_auth_method||"none",lastResponse:P,httpHistory:V,infoLogs:oe,error:void 0,isInitiatingAuth:!1})}}catch(G){const P={status:0,statusText:"Network Error",headers:p({}),body:{error:G instanceof Error?G.message:String(G)}},V=[...v.httpHistory||[]];if(V.length>0){const Q=V[V.length-1];Q.response=P,Q.duration=Date.now()-(Q.timestamp||Date.now())}r({lastResponse:P,httpHistory:V,error:`Client registration failed: ${G instanceof Error?G.message:String(G)}. Using fallback.`}),r({currentStep:"received_client_credentials",clientId:"preregistered-client-id",clientSecret:void 0,tokenEndpointAuthMethod:"none",isInitiatingAuth:!1})}break;case"received_client_credentials":const U=Vm(43),z=await UH(U),F=yn(m(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters (REQUIRED)",{code_challenge:z,method:"S256",resource:v.serverUrl||"Unknown",note:"PKCE is REQUIRED for all clients in 2025-03-26 spec"});r({currentStep:"generate_pkce_parameters",codeVerifier:U,codeChallenge:z,codeChallengeMethod:"S256",state:Vm(16),infoLogs:F,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!v.authorizationServerMetadata?.authorization_endpoint||!v.clientId)throw new Error("Missing authorization endpoint or client ID");const D=new URL(v.authorizationServerMetadata.authorization_endpoint);if(D.searchParams.set("response_type","code"),D.searchParams.set("client_id",v.clientId),D.searchParams.set("redirect_uri",f),D.searchParams.set("code_challenge",v.codeChallenge||""),D.searchParams.set("code_challenge_method","S256"),D.searchParams.set("state",v.state||""),v.serverUrl&&D.searchParams.set("resource",v.serverUrl),u)D.searchParams.set("scope",u);else{const G=v.authorizationServerMetadata.scopes_supported,P=new Set;G&&G.length>0&&G.forEach(V=>P.add(V)),G?.includes("offline_access")&&P.add("offline_access"),P.size>0&&D.searchParams.set("scope",Array.from(P).join(" "))}const W=yn(m(),"authorization_request","auth-url","Authorization URL",{url:D.toString()});r({currentStep:"authorization_request",authorizationUrl:D.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:W,isInitiatingAuth:!1});break;case"authorization_request":r({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":if(!v.authorizationCode||v.authorizationCode.trim()===""){r({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!v.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const q={grant_type:"authorization_code",code:v.authorizationCode,redirect_uri:f};v.clientId&&(q.client_id=v.clientId),v.clientSecret&&(q.client_secret=v.clientSecret),v.codeVerifier&&(q.code_verifier=v.codeVerifier),v.serverUrl&&(q.resource=v.serverUrl);const X={method:"POST",url:v.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded"},body:q};r({currentStep:"token_request",lastRequest:X,lastResponse:void 0,accessToken:void 0,refreshToken:void 0,httpHistory:[...v.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:X}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"token_request":if(!v.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!v.authorizationCode)throw new Error("Missing authorization code");if(!v.codeVerifier)throw new Error("PKCE code_verifier is missing - REQUIRED by 2025-03-26 spec for token exchange");try{const G=new URLSearchParams({grant_type:"authorization_code",code:v.authorizationCode,redirect_uri:f,client_id:v.clientId||"",code_verifier:v.codeVerifier||""});v.clientSecret&&G.set("client_secret",v.clientSecret),v.serverUrl&&G.set("resource",v.serverUrl);const P=await ua(v.authorizationServerMetadata.token_endpoint,{method:"POST",headers:p({"Content-Type":"application/x-www-form-urlencoded"}),body:G.toString()}),V={status:P.status,statusText:P.statusText,headers:P.headers,body:P.body},K=[...v.httpHistory||[]];if(K.length>0){const ee=K[K.length-1];ee.response=V,ee.duration=Date.now()-(ee.timestamp||Date.now())}if(!P.ok){r({lastResponse:V,httpHistory:K,authorizationCode:void 0,error:`Token request failed: ${P.body?.error||P.statusText} - ${P.body?.error_description||"Unknown error"}`,isInitiatingAuth:!1});return}const Q=P.body;let re=(m().infoLogs||[]).filter(ee=>ee.id!=="auth-code"&&ee.id!=="oauth-tokens"&&ee.id!=="token");if(v.authorizationCode&&(re=[...re,{id:"auth-code",level:"info",step:"received_authorization_code",label:"Authorization Code",data:{code:v.authorizationCode},timestamp:Date.now()}]),Q.access_token){const ee={access_token:Q.access_token};Q.refresh_token&&(ee.refresh_token=Q.refresh_token),re=[...re,{id:"oauth-tokens",level:"info",step:"received_access_token",label:"OAuth Tokens",data:ee,timestamp:Date.now()}]}if(Q.access_token){const ee=Gm(Q.access_token);if(ee){const le={...ee};le.exp&&(le.exp=`${le.exp} (${Ji(le.exp)})`),le.iat&&(le.iat=`${le.iat} (${Ji(le.iat)})`),le.nbf&&(le.nbf=`${le.nbf} (${Ji(le.nbf)})`);const te={...le};if(le.aud){const Z=v.serverUrl,J=(Array.isArray(le.aud)?le.aud:[le.aud]).some(se=>se===Z);te._validation={expected_audience:Z,audience_matches:J,note:J?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else te._validation={note:"⚠ No audience claim found - server should validate token binding"};re=[...re,{id:"token",step:"received_access_token",level:"info",label:"Access Token (Decoded JWT)",data:te,timestamp:Date.now()}]}}if(Q.id_token){const ee=Gm(Q.id_token);if(ee){const le={...ee};le.exp&&(le.exp=`${le.exp} (${Ji(le.exp)})`),le.iat&&(le.iat=`${le.iat} (${Ji(le.iat)})`),le.nbf&&(le.nbf=`${le.nbf} (${Ji(le.nbf)})`),le.auth_time&&(le.auth_time=`${le.auth_time} (${Ji(le.auth_time)})`),le._note="OIDC ID Token - Used for user identity verification",re=[...re,{id:"id-token",step:"received_access_token",level:"info",label:"ID Token (OIDC - Decoded JWT)",data:le,timestamp:Date.now()}]}}r({currentStep:"received_access_token",accessToken:Q.access_token,refreshToken:Q.refresh_token,tokenType:Q.token_type||"Bearer",expiresIn:Q.expires_in,lastResponse:V,httpHistory:K,infoLogs:re,error:void 0,isInitiatingAuth:!1})}catch(G){const P={status:0,statusText:"Network Error",headers:p({}),body:{error:G instanceof Error?G.message:String(G)}},V=[...v.httpHistory||[]];if(V.length>0){const K=V[V.length-1];K.response=P,K.duration=Date.now()-(K.timestamp||Date.now())}r({lastResponse:P,httpHistory:V,error:`Token exchange failed: ${G instanceof Error?G.message:String(G)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!v.serverUrl||!v.accessToken)throw new Error("Missing server URL or access token");const L={method:"POST",url:v.serverUrl,headers:{Authorization:`Bearer ${v.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCP Inspector",version:"1.0.0"}},id:2}},Y=yn(m(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-03-26",Client:"MCP Inspector v1.0.0",Endpoint:v.serverUrl});r({currentStep:"authenticated_mcp_request",lastRequest:L,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:L}],infoLogs:Y,isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"authenticated_mcp_request":if(!v.serverUrl||!v.accessToken)throw new Error("Missing server URL or access token");try{const G=await ua(v.serverUrl,{method:"POST",headers:p({Authorization:`Bearer ${v.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify({jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCP Inspector",version:"1.0.0"}},id:2})}),P={status:G.status,statusText:G.statusText,headers:G.headers,body:G.body},V=[...v.httpHistory||[]];if(V.length>0){const ee=V[V.length-1];ee.response=P,ee.duration=Date.now()-(ee.timestamp||Date.now())}if(!G.ok){if(G.status>=400&&G.status<500)try{const ee={method:"GET",url:v.serverUrl,headers:{Authorization:`Bearer ${v.accessToken}`,Accept:"text/event-stream"}},le={step:"complete",timestamp:Date.now(),request:ee};V.push(le);const te=await ua(v.serverUrl,{method:"GET",headers:{Authorization:`Bearer ${v.accessToken}`,Accept:"text/event-stream"}});le.response={status:te.status,statusText:te.statusText,headers:te.headers,body:te.body},le.duration=Date.now()-le.timestamp;const Z=te.body;if(Z&&typeof Z=="object"&&Z.isOldTransport&&Z.endpoint){const ne=Z.endpoint,J=new URL(ne,v.serverUrl).toString(),se=yn(m(),"authenticated_mcp_request","http-sse-detected","HTTP+SSE Transport Detected (2024-11-05)",{Transport:"HTTP+SSE (2024-11-05 - Deprecated)","SSE Stream URL":v.serverUrl,"POST Endpoint":J,"First Event":Z.events?.[0],"Migration Note":"This transport is deprecated. Please update your server to use the 2025-03-26 Streamable HTTP transport.","How It Works":"Client connected via GET for SSE stream. Subsequent requests use POST to: "+J});r({currentStep:"complete",lastResponse:{status:te.status,statusText:"OK - HTTP+SSE Transport",headers:te.headers,body:{transport:"HTTP+SSE (2024-11-05)",sseStreamUrl:v.serverUrl,postEndpoint:J,events:Z.events}},httpHistory:V,infoLogs:se,error:void 0,isInitiatingAuth:!1});return}}catch(ee){console.error("GET fallback failed:",ee)}r({lastResponse:P,httpHistory:V,error:`Authenticated request failed: ${G.status} ${G.statusText}`,isInitiatingAuth:!1});return}let K=m().infoLogs||[];const Q=G.headers["content-type"]||"",oe=Q.includes("text/event-stream");let re=null;if(oe&&G.body?.transport==="sse"?re=G.body.mcpResponse:re=G.body,oe&&re?.result?.protocolVersion){const ee={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":re.result.protocolVersion};re.result.serverInfo&&(ee["Server Name"]=re.result.serverInfo.name,ee["Server Version"]=re.result.serverInfo.version),re.result.capabilities&&(ee.Capabilities=re.result.capabilities),K=yn(m(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",ee)}else if(oe)K=yn(m(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":Q,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:G.body?.events?`${G.body.events.length} events parsed`:"No events parsed"});else if(re?.result?.protocolVersion){const ee={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":re.result.protocolVersion};re.result.serverInfo&&(ee["Server Name"]=re.result.serverInfo.name,ee["Server Version"]=re.result.serverInfo.version),re.result.capabilities&&(ee.Capabilities=re.result.capabilities),K=yn(m(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",ee)}r({currentStep:"complete",lastResponse:P,httpHistory:V,infoLogs:K,error:void 0,isInitiatingAuth:!1})}catch(G){const P=$d(G),V={status:0,statusText:"Network Error",headers:p({}),body:{error:P.message,details:P.details}},K=[...v.httpHistory||[]];if(K.length>0){const re={...K[K.length-1],response:V,duration:Date.now()-(K[K.length-1]?.timestamp||Date.now()),error:P};K[K.length-1]=re}const Q=m(),oe=yn(Q,"authenticated_mcp_request",`error-authenticated_mcp_request-${Date.now()}`,"Authenticated MCP request failed",{request:Q.lastRequest,error:P},{level:"error",error:P});r({lastResponse:V,httpHistory:K,infoLogs:oe,error:`Authenticated MCP request failed: ${P.message}`,isInitiatingAuth:!1})}break;case"complete":r({isInitiatingAuth:!1});break;default:r({isInitiatingAuth:!1});break}}catch(x){const _=m(),S=$d(x),w=yn(_,_.currentStep,`error-${_.currentStep}-${Date.now()}`,"Step failed",{step:_.currentStep,request:_.lastRequest,response:_.lastResponse,error:S},{level:"error",error:S}),T=Rw(_.httpHistory,S),N={error:S.message,infoLogs:w,isInitiatingAuth:!1};T&&(N.httpHistory=T),r(N)}},startGuidedFlow:async()=>{r({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{r({...fKt,lastRequest:void 0,lastResponse:void 0,httpHistory:[],infoLogs:[],authorizationCode:void 0,authorizationUrl:void 0,accessToken:void 0,refreshToken:void 0,codeVerifier:void 0,codeChallenge:void 0,error:void 0})}};return y},G0="https://www.mcpjam.com/.well-known/oauth/client-metadata.json";function AC(e){try{const t=new URL(e);return t.protocol=t.protocol.toLowerCase(),t.hostname=t.hostname.toLowerCase(),t.hash="",t.pathname!=="/"&&t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),t.toString()}catch(t){return console.warn("Failed to canonicalize resource URL:",e,t),e}}const gKt=PZ;function Eme(e,t){return[{id:"request_without_token",label:"MCP request without token",description:"Client makes initial request without authorization",from:"client",to:"mcpServer",details:e.serverUrl?[{label:"POST",value:e.serverUrl},{label:"method",value:"initialize"}]:void 0},{id:"received_401_unauthorized",label:"HTTP 401 Unauthorized with WWW-Authenticate header",description:"Server returns 401 with WWW-Authenticate header",from:"mcpServer",to:"client",details:e.resourceMetadataUrl?[{label:"Note",value:"Extract resource_metadata URL"}]:void 0},{id:"request_resource_metadata",label:"Request Protected Resource Metadata",description:"Client requests metadata from well-known URI",from:"client",to:"mcpServer",details:e.resourceMetadataUrl?[{label:"GET",value:new URL(e.resourceMetadataUrl).pathname}]:void 0},{id:"received_resource_metadata",label:"Return metadata",description:"Server returns OAuth protected resource metadata",from:"mcpServer",to:"client",details:e.resourceMetadata?.authorization_servers?[{label:"Auth Server",value:e.resourceMetadata.authorization_servers[0]}]:void 0},{id:"request_authorization_server_metadata",label:"GET Authorization server metadata endpoint",description:"Try OAuth path insertion, OIDC path insertion, OIDC path appending",from:"client",to:"authServer",details:e.authorizationServerUrl?[{label:"URL",value:e.authorizationServerUrl},{label:"Protocol",value:"2025-11-25"}]:void 0},{id:"received_authorization_server_metadata",label:"Authorization server metadata response",description:"Authorization Server returns metadata",from:"authServer",to:"client",details:e.authorizationServerMetadata?[{label:"Token",value:new URL(e.authorizationServerMetadata.token_endpoint).pathname},{label:"Auth",value:new URL(e.authorizationServerMetadata.authorization_endpoint).pathname}]:void 0},...t==="cimd"?[{id:"cimd_prepare",label:"Client uses HTTPS URL as client_id",description:"Client prepares to use URL-based client identification",from:"client",to:"client",details:e.clientId?[{label:"client_id (URL)",value:e.clientId.includes("http")?e.clientId:"https://www.mcpjam.com/.well-known/oauth/client-metadata.json"},{label:"Method",value:"Client ID Metadata Document (CIMD)"}]:[{label:"Note",value:"HTTPS URL points to metadata document"}]},{id:"cimd_fetch_request",label:"Fetch metadata from client_id URL",description:"Authorization Server fetches client metadata from the URL",from:"authServer",to:"client",details:[{label:"Action",value:"GET client_id URL"},{label:"Note",value:"Server initiates metadata fetch during authorization"}]},{id:"cimd_metadata_response",label:"JSON metadata document",description:"Client hosting returns metadata with redirect_uris and client info",from:"client",to:"authServer",details:[{label:"Content-Type",value:"application/json"},{label:"Contains",value:"client_id, client_name, redirect_uris, etc."}]},{id:"received_client_credentials",label:"Validate metadata and redirect_uris",description:"Authorization Server validates fetched metadata",from:"authServer",to:"authServer",details:[{label:"Validates",value:"client_id matches URL, redirect_uris are valid"},{label:"Security",value:"SSRF protection, domain trust policies"}]}]:t==="dcr"?[{id:"request_client_registration",label:"POST /register (2025-11-25)",description:"Client registers dynamically with Authorization Server",from:"client",to:"authServer",details:[{label:"Note",value:"Dynamic client registration (DCR)"}]},{id:"received_client_credentials",label:"Client Credentials",description:"Authorization Server returns client ID and credentials",from:"authServer",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."}]:void 0}]:[{id:"received_client_credentials",label:"Use Pre-registered Client (2025-11-25)",description:"Client uses pre-configured credentials (skipped DCR)",from:"client",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."},{label:"Note",value:"Pre-registered (no DCR needed)"}]:[{label:"Note",value:"Pre-registered client credentials"}]}],{id:"generate_pkce_parameters",label:`Generate PKCE (REQUIRED)
|
|
1840
|
+
`)}}):null},Fd=rc;function AZ({active:e,payload:t,className:n,indicator:r="dot",hideLabel:i=!1,hideIndicator:a=!1,label:s,labelFormatter:o,labelClassName:u,formatter:c,color:d,nameKey:f,labelKey:p}){const{config:m}=CGt(),y=b.useMemo(()=>{if(i||!t?.length)return null;const[x]=t,_=`${p||x?.dataKey||x?.name||"value"}`,S=sme(m,x,_),w=!p&&typeof s=="string"?m[s]?.label||s:S?.label;return o?l.jsx("div",{className:Ie("font-medium",u),children:o(w,t)}):w?l.jsx("div",{className:Ie("font-medium",u),children:w}):null},[s,o,t,i,u,m,p]);if(!e||!t?.length)return null;const v=t.length===1&&r!=="dot";return l.jsxs("div",{className:Ie("border-border/50 bg-background grid min-w-[8rem] items-start gap-1.5 rounded-lg border px-2.5 py-1.5 text-xs shadow-xl",n),children:[v?null:y,l.jsx("div",{className:"grid gap-1.5",children:t.map((x,_)=>{const S=`${f||x.name||x.dataKey||"value"}`,w=sme(m,x,S),T=d||x.payload.fill||x.color;return l.jsx("div",{className:Ie("[&>svg]:text-muted-foreground flex w-full flex-wrap items-stretch gap-2 [&>svg]:h-2.5 [&>svg]:w-2.5",r==="dot"&&"items-center"),children:c&&x?.value!==void 0&&x.name?c(x.value,x.name,x,_,x.payload):l.jsxs(l.Fragment,{children:[w?.icon?l.jsx(w.icon,{}):!a&&l.jsx("div",{className:Ie("shrink-0 rounded-[2px] border-(--color-border) bg-(--color-bg)",{"h-2.5 w-2.5":r==="dot","w-1":r==="line","w-0 border-[1.5px] border-dashed bg-transparent":r==="dashed","my-0.5":v&&r==="dashed"}),style:{"--color-bg":T,"--color-border":T}}),l.jsxs("div",{className:Ie("flex flex-1 justify-between leading-none",v?"items-end":"items-center"),children:[l.jsxs("div",{className:"grid gap-1.5",children:[v?y:null,l.jsx("span",{className:"text-muted-foreground",children:w?.label||x.name})]}),x.value&&l.jsx("span",{className:"text-foreground font-mono font-medium tabular-nums",children:x.value.toLocaleString()})]})]})},x.dataKey)})})]})}function sme(e,t,n){if(typeof t!="object"||t===null)return;const r="payload"in t&&typeof t.payload=="object"&&t.payload!==null?t.payload:void 0;let i=n;return n in t&&typeof t[n]=="string"?i=t[n]:r&&n in r&&typeof r[n]=="string"&&(i=r[n]),i in e?e[i]:e[n]}function IGt({suite:e,viewMode:t,selectedRunDetails:n,isEditMode:r,onRerun:i,onDelete:a,onCancelRun:s,onDeleteRun:o,onViewModeChange:u,connectedServerNames:c,rerunningSuiteId:d,cancellingRunId:f,deletingSuiteId:p,deletingRunId:m,showRunSummarySidebar:y,setShowRunSummarySidebar:v,runsViewMode:x="runs",runs:_=[],allIterations:S=[],aggregate:w=null,testCases:T=[],availableModels:N=[],onUpdateModels:E}){const[A,I]=b.useState(!1),[M,$]=b.useState(e.name),[O,R]=b.useState(!1),U=_n("testSuites:updateTestSuite"),z=b.useMemo(()=>{if(!T||T.length===0)return[];const ee=new Map;return T.forEach(le=>{le.models&&Array.isArray(le.models)&&le.models.forEach(te=>{const Z=`${te.provider}:${te.model}`;if(!ee.has(Z)){const ne=N.find(J=>J.id===te.model);ee.set(Z,{model:te.model,provider:te.provider,displayName:ne?.name||te.model})}})}),Array.from(ee.values())},[T,N]),F=b.useMemo(()=>{const ee=new Map;return N.forEach(le=>{const te=le.provider;ee.has(te)||ee.set(te,[]),ee.get(te).push(le)}),ee},[N]),D=b.useMemo(()=>Array.from(F.entries()).filter(([ee,le])=>le.some(te=>_r(te.id))).sort(([ee],[le])=>ee.localeCompare(le)),[F]),W=b.useMemo(()=>Array.from(F.entries()).filter(([ee,le])=>le.some(te=>!_r(te.id))).sort(([ee],[le])=>ee.localeCompare(le)),[F]),q=b.useCallback(async ee=>{if(!E)return;if(z.some(Z=>Z.model===ee.id)){R(!1);return}const le={model:ee.id,provider:ee.provider,displayName:ee.name},te=[...z,le];await E(te),R(!1)},[z,E]),X=b.useCallback(async ee=>{if(!E)return;const le=z.filter(te=>te.model!==ee);await E(le)},[z,E]),L=b.useMemo(()=>{if(!_||!S||_.length===0)return null;const ee=_.filter(he=>he.isActive!==!1);if(ee.length===0)return null;const le=new Set(ee.map(he=>he._id)),te=S.filter(he=>he.suiteRunId&&le.has(he.suiteRunId));if(te.length===0)return null;const Z=te.map(he=>Fl(he)),ne=Z.filter(he=>he==="passed").length,J=Z.filter(he=>he==="failed").length,se=ne+J;if(se===0)return null;const ie=[];return ne>0&&ie.push({name:"passed",value:ne,fill:"hsl(142.1 76.2% 36.3%)"}),J>0&&ie.push({name:"failed",value:J,fill:"hsl(0 84.2% 60.2%)"}),{donutData:ie,total:se,accuracy:Math.round(ne/se*100)}},[_,S]);b.useEffect(()=>{$(e.name)},[e.name]);const Y=b.useCallback(()=>{I(!0),$(e.name)},[e.name]),G=b.useCallback(async()=>{if(I(!1),M&&M.trim()&&M!==e.name)try{await U({suiteId:e._id,name:M.trim()}),Pe.success("Suite name updated")}catch(ee){Pe.error("Failed to update suite name"),console.error("Failed to update suite name:",ee),$(e.name)}else $(e.name)},[M,e.name,e._id,U]),P=b.useCallback(ee=>{ee.key==="Enter"?G():ee.key==="Escape"&&(I(!1),$(e.name))},[G,e.name]),K=(e.environment?.servers||[]).filter(ee=>!c.has(ee)),Q=K.length===0,oe=d===e._id,re=p===e._id;if(r)return l.jsx("div",{className:"flex items-center justify-between gap-4 mb-2 px-6 pt-6 max-w-5xl mx-auto w-full",children:A?l.jsx("input",{type:"text",value:M,onChange:ee=>$(ee.target.value),onBlur:G,onKeyDown:P,autoFocus:!0,className:"px-4 py-2 text-xl font-bold border border-input rounded-lg focus:outline-none focus:ring-2 focus:ring-ring bg-background"}):l.jsx(Ee,{variant:"ghost",onClick:Y,className:"px-4 py-2 h-auto text-xl font-bold hover:bg-accent/50 -ml-4 rounded-lg",children:e.name})});if(t==="run-detail"&&n){const ee=f===n._id,le=n.status==="running"||n.status==="pending",te=oe||le;return l.jsxs("div",{className:"flex items-center justify-between gap-4 mb-4",children:[l.jsxs("h2",{className:"text-lg font-semibold",children:["Run ",r2(n._id)]}),l.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[l.jsxs(Ee,{variant:"outline",size:"sm",onClick:()=>v(!y),className:"gap-2",children:[l.jsx(T1e,{className:"h-4 w-4"}),"View run summary"]}),le?l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:"outline",size:"sm",onClick:()=>s(n._id),disabled:ee,className:"gap-2",children:ee?l.jsxs(l.Fragment,{children:[l.jsx(Pn,{className:"h-4 w-4 animate-spin"}),"Cancelling..."]}):l.jsxs(l.Fragment,{children:[l.jsx(Yn,{className:"h-4 w-4"}),"Cancel run"]})})}),l.jsx(zt,{children:"Cancel the current evaluation run"})]}):l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsxs(Ee,{variant:"outline",size:"sm",onClick:()=>i(e),disabled:!Q||te,className:"gap-2",children:[l.jsx(bU,{className:`h-4 w-4 ${te?"animate-spin":""}`}),te?"Running...":"Rerun"]})})}),l.jsx(zt,{children:Q?"Run all tests":`Connect the following servers: ${K.join(", ")}`})]}),l.jsxs(Ee,{variant:"outline",size:"sm",onClick:()=>o(n._id),disabled:m===n._id,className:"gap-2",children:[l.jsx(Ll,{className:"h-4 w-4"}),m===n._id?"Deleting...":"Delete"]}),l.jsx(Ee,{variant:"outline",size:"icon",onClick:()=>u("overview"),children:l.jsx(Yn,{className:"h-4 w-4"})})]})]})}return t==="test-detail"||t==="test-edit"?null:l.jsxs("div",{className:"flex items-center justify-between gap-4 mb-4",children:[l.jsxs("div",{className:"flex items-center gap-4 flex-1",children:[A?l.jsx("input",{type:"text",value:M,onChange:ee=>$(ee.target.value),onBlur:G,onKeyDown:P,autoFocus:!0,className:"px-3 py-2 text-lg font-semibold border border-input rounded-md focus:outline-none focus:ring-2 focus:ring-ring"}):l.jsx(Ee,{variant:"ghost",onClick:Y,className:"px-3 py-2 h-auto text-lg font-semibold hover:bg-accent",children:e.name}),L&&L.donutData.length>0&&l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-sm font-medium text-foreground",children:"Accuracy:"}),l.jsx(Ud,{config:{passed:{label:"Passed",color:"hsl(142.1 76.2% 36.3%)"},failed:{label:"Failed",color:"hsl(0 84.2% 60.2%)"},pending:{label:"Pending",color:"hsl(45.4 93.4% 47.5%)"},cancelled:{label:"Cancelled",color:"hsl(240 3.7% 15.9%)"}},className:"h-12 w-12",children:l.jsxs(u5e,{children:[l.jsx(Fd,{content:l.jsx(AZ,{hideLabel:!0})}),l.jsx(Wc,{data:L.donutData,dataKey:"value",nameKey:"name",innerRadius:15,outerRadius:22,strokeWidth:1,children:l.jsx(da,{content:({viewBox:ee})=>{if(ee&&"cx"in ee&&"cy"in ee)return l.jsx("text",{x:ee.cx,y:ee.cy,textAnchor:"middle",dominantBaseline:"middle",children:l.jsxs("tspan",{x:ee.cx,y:ee.cy,className:"fill-foreground text-[10px] font-bold",children:[L.accuracy,"%"]})})}})})]})})]})]}),l.jsxs("div",{className:"flex items-center gap-2 shrink-0",children:[E&&l.jsxs(Ic,{open:O,onOpenChange:R,children:[l.jsx(jc,{asChild:!0,children:l.jsxs(Ee,{size:"sm",variant:"outline",className:`gap-1.5 ${z.length===0?"text-destructive border-destructive/50":""}`,children:["Models",l.jsx(Cn,{variant:z.length===0?"destructive":"secondary",className:"px-1.5 py-0 text-[10px] min-w-[18px] justify-center",children:z.length})]})}),l.jsxs(Oc,{align:"end",side:"bottom",sideOffset:4,className:"w-[280px]",children:[z.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"px-2 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground",children:"Active Models"}),z.map(ee=>l.jsxs("div",{className:"flex items-center justify-between px-2 py-1.5 text-sm",children:[l.jsx("span",{className:"truncate",children:ee.displayName}),l.jsx("button",{onClick:()=>X(ee.model),className:"ml-2 p-0.5 text-muted-foreground hover:text-destructive rounded",title:"Remove model",children:l.jsx(Yn,{className:"h-3.5 w-3.5"})})]},ee.model)),l.jsx("div",{className:"my-1 h-px bg-border"})]}),D.length>0&&l.jsx("div",{className:"px-2 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground",children:"MCPJam Free Models"}),D.map(([ee,le])=>{const te=le.filter(ne=>_r(ne.id)),Z=te.length;return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:ee}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:ee}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[Z," model",Z!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[200px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:te.map(ne=>{const J=z.some(se=>se.model===ne.id);return l.jsxs(Oi,{onSelect:()=>q(ne),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:J,children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:ne.name})}),J&&l.jsx("div",{className:"ml-auto w-2 h-2 bg-primary rounded-full"})]},ne.id)})})]},`free-${ee}`)}),D.length>0&&W.length>0&&l.jsx("div",{className:"my-1 h-px bg-muted/50"}),W.length>0&&l.jsx("div",{className:"px-2 py-1.5 text-[10px] uppercase tracking-wide text-muted-foreground",children:"Your Providers"}),W.map(([ee,le])=>{const te=le.filter(ne=>!_r(ne.id)),Z=te.length;return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:ee}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:ee}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[Z," model",Z!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[200px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:te.map(ne=>{const J=z.some(se=>se.model===ne.id);return l.jsxs(Oi,{onSelect:()=>q(ne),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:J,children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:ne.name})}),J&&l.jsx("div",{className:"ml-auto w-2 h-2 bg-primary rounded-full"})]},ne.id)})})]},`user-${ee}`)})]})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsxs(Ee,{variant:"outline",size:"sm",onClick:()=>i(e),disabled:!Q||oe,className:"gap-2",children:[l.jsx(bU,{className:`h-4 w-4 ${oe?"animate-spin":""}`}),"Run"]})})}),l.jsx(zt,{children:Q?"Run all tests":`Connect the following servers: ${K.join(", ")}`})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsxs(Ee,{variant:"outline",size:"sm",onClick:()=>a(e),disabled:re,className:"gap-2",children:[l.jsx(Ll,{className:"h-4 w-4"}),re?"Deleting...":"Delete"]})}),l.jsx(zt,{children:"Delete this test suite"})]})]})]})}function IZ({data:e,isLoading:t=!1,title:n,height:r="h-32",onClick:i,showLabel:a=!1}){return t?l.jsx(nI,{className:`${r} w-full`}):e.length===0?l.jsx("p",{className:"text-xs text-muted-foreground",children:"No completed runs yet."}):l.jsx(Ud,{config:{passRate:{label:"Accuracy",color:"var(--chart-1)"}},className:`aspect-auto ${r} w-full`,children:l.jsxs(TGt,{data:e,width:void 0,height:void 0,onClick:i?s=>{s?.activePayload?.[0]?.payload?.runId&&i(s.activePayload[0].payload.runId)}:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"runIdDisplay",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:a?11:12},label:a?{value:"Run",position:"insideBottom",offset:-5,fontSize:11}:void 0}),l.jsx(Nu,{domain:[0,100],tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:a?11:12},tickFormatter:s=>`${s}%`}),l.jsx(Fd,{cursor:!1,content:l.jsx(AZ,{})}),l.jsx(mh,{type:"monotone",dataKey:"passRate",stroke:"var(--color-passRate)",fill:"var(--color-passRate)",fillOpacity:.15,strokeWidth:2,isAnimationActive:!1,dot:e.length>1?i?{cursor:"pointer"}:!0:!1,activeDot:i?{cursor:"pointer",r:6}:void 0})]})})}function jGt({suite:e,runs:t,runsLoading:n,allIterations:r,runTrendData:i,modelStats:a,onRunClick:s,onDirectDeleteRun:o,runsViewMode:u,onViewModeChange:c}){const[d,f]=b.useState(new Set),[p,m]=b.useState(!1),[y,v]=b.useState(null),x=b.useCallback(T=>{f(N=>{const E=new Set(N);return E.has(T)?E.delete(T):E.add(T),E})},[]),_=b.useCallback(()=>{f(T=>T.size===t.length?new Set:new Set(t.map(N=>N._id)))},[t]),S=b.useCallback(()=>{const T=Array.from(d);T.length!==0&&(v("batch"),Promise.all(T.map(N=>o(N))).then(()=>{f(new Set),m(!1),Pe.success(`Deleted ${T.length} run(s) successfully`)}).catch(N=>{console.error("Failed to delete runs:",N),Pe.error("Failed to delete some runs")}).finally(()=>{v(null),m(!1)}))},[d,o]),w={passRate:{label:"Pass Rate",color:"var(--chart-1)"}};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Accuracy"})}),l.jsx("div",{className:"px-4 pb-4",children:l.jsx(IZ,{data:i,isLoading:n,height:"h-32",onClick:s})})]}),l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Performance by model"})}),l.jsx("div",{className:"px-4 pb-4",children:a.length>0?l.jsx(Ud,{config:w,className:"aspect-auto h-32 w-full",children:l.jsxs(Xv,{data:a,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"model",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:11},interval:0,height:40,tickFormatter:T=>T.length>15?T.substring(0,12)+"...":T}),l.jsx(Nu,{domain:[0,100],tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:T=>`${T}%`}),l.jsx(Fd,{cursor:!1,content:({active:T,payload:N})=>{if(!T||!N||N.length===0)return null;const E=N[0].payload;return l.jsx("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:l.jsxs("div",{className:"grid gap-2",children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"text-xs font-semibold",children:E.model}),l.jsxs("span",{className:"text-xs text-muted-foreground mt-0.5",children:[E.passed," passed · ",E.failed," failed"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"h-2 w-2 rounded-full",style:{backgroundColor:"var(--color-passRate)"}}),l.jsxs("span",{className:"text-sm font-semibold",children:[E.passRate,"%"]})]})]})})}}),l.jsx(Ml,{dataKey:"passRate",fill:"var(--color-passRate)",radius:[4,4,0,0],isAnimationActive:!1,minPointSize:8})]})}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"No model data available."})})]})]}),l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground flex flex-col max-h-[600px]",children:[d.size>0?l.jsxs("div",{className:"border-b px-4 py-2 shrink-0 bg-muted/50 flex items-center justify-between",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(Hw,{checked:d.size===t.length,onCheckedChange:_,"aria-label":"Select all runs"}),l.jsxs("span",{className:"text-xs font-medium",children:[d.size," ",d.size===1?"item":"items"," selected"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ee,{variant:"outline",size:"sm",onClick:()=>f(new Set),children:"Cancel"}),l.jsx(Ee,{variant:"destructive",size:"sm",onClick:()=>m(!0),disabled:y!==null,children:"Delete"})]})]}):l.jsxs("div",{className:"border-b px-4 py-2 shrink-0 flex items-center justify-between",children:[l.jsx("div",{children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Click on a run to view its test breakdown and results."})}),l.jsxs("select",{value:u,onChange:T=>c(T.target.value),className:"text-xs border rounded px-2 py-1 bg-background",children:[l.jsx("option",{value:"runs",children:"Runs"}),l.jsx("option",{value:"test-cases",children:"Test Cases"})]})]}),t.length>0&&l.jsxs("div",{className:"flex items-center gap-6 w-full px-4 py-1.5 bg-muted/30 border-b text-xs font-medium text-muted-foreground",children:[l.jsx("div",{className:"w-4"}),l.jsx("div",{className:"min-w-[120px]",children:"Run ID"}),l.jsx("div",{className:"min-w-[140px]",children:"Start time"}),l.jsx("div",{className:"min-w-[60px]",children:"Duration"}),l.jsx("div",{className:"min-w-[60px] text-right",children:"Passed"}),l.jsx("div",{className:"min-w-[60px] text-right",children:"Failed"}),l.jsx("div",{className:"min-w-[70px] text-right",children:"Accuracy"}),l.jsx("div",{className:"min-w-[70px] text-right",children:"Tokens"})]}),l.jsx("div",{className:"divide-y overflow-y-auto",children:t.length===0?l.jsx("div",{className:"px-4 py-12 text-center text-sm text-muted-foreground",children:"No runs found."}):t.map(T=>{const N=r.filter(G=>G.suiteRunId===T._id),E=N.map(G=>Fl(G)),A=E.filter(G=>G==="passed").length,I=E.filter(G=>G==="failed").length,M=A+I,$=N.reduce((G,P)=>G+(P.tokensUsed||0),0),O=A>0?A:T.summary?.passed??0,R=I>0?I:T.summary?.failed??0,U=M>0?M:T.summary?.total??0,z=U>0?Math.round(O/U*100):null,F=OGt(T.completedAt??T.createdAt),D=T.completedAt&&T.createdAt?ome(T.completedAt-T.createdAt):T.createdAt&&T.status==="running"?ome(Date.now()-T.createdAt):"—",W=T.isActive===!1,q=T.result||(T.status==="completed"&&z!==null?z>=(T.passCriteria?.minimumPassRate??100)?"passed":"failed":T.status==="cancelled"?"cancelled":"pending"),X=SK(q),L=d.has(T._id),Y=l.jsxs("div",{className:"flex items-center gap-6 w-full",children:[l.jsx("div",{className:"pl-3",children:l.jsx(Hw,{checked:L,onCheckedChange:()=>x(T._id),onClick:G=>G.stopPropagation(),"aria-label":`Select run ${r2(T._id)}`})}),l.jsxs("button",{onClick:()=>s(T._id),className:"flex flex-1 items-center gap-6 py-2.5 pr-3 text-left transition-colors hover:bg-muted/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:[l.jsxs("span",{className:"text-xs font-medium min-w-[120px]",children:["Run ",r2(T._id)]}),l.jsx("span",{className:"text-xs text-muted-foreground min-w-[140px]",children:F}),l.jsx("span",{className:"text-xs text-muted-foreground font-mono min-w-[60px]",children:D}),l.jsx("span",{className:"text-xs font-mono text-muted-foreground min-w-[60px] text-right",children:O}),l.jsx("span",{className:"text-xs font-mono text-muted-foreground min-w-[60px] text-right",children:R}),l.jsx("span",{className:"text-xs font-mono text-muted-foreground min-w-[70px] text-right",children:z!==null?`${z}%`:"—"}),l.jsx("span",{className:"text-xs font-mono text-muted-foreground min-w-[70px] text-right",children:$>0?$.toLocaleString():"—"})]})]});return l.jsxs("div",{className:Ie("relative overflow-hidden",W&&"opacity-50"),children:[l.jsx("div",{className:`absolute left-0 top-0 h-full w-1 ${X}`}),W?l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:Y}),l.jsx(zt,{children:l.jsx("p",{className:"text-xs",children:"Run is inactive since test cases were updated"})})]}):Y]},T._id)})})]}),l.jsx(si,{open:p,onOpenChange:m,children:l.jsxs(oi,{children:[l.jsxs(vi,{children:[l.jsxs(yi,{className:"flex items-center gap-2",children:[l.jsx(Ll,{className:"h-5 w-5 text-destructive"}),"Delete ",d.size," Run",d.size!==1?"s":""]}),l.jsxs(us,{children:["Are you sure you want to delete ",d.size," run",d.size!==1?"s":"","?",l.jsx("br",{}),l.jsx("br",{}),"This will permanently delete all iterations and results associated with ",d.size===1?"this run":"these runs",". This action cannot be undone."]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:()=>m(!1),disabled:y!==null,children:"Cancel"}),l.jsx(Ee,{variant:"destructive",onClick:S,disabled:y!==null,children:y?"Deleting...":"Delete"})]})]})})]})}function OGt(e){return e?new Date(e).toLocaleString():"—"}function ome(e){if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;if(n<60)return r?`${n}m ${r}s`:`${n}m`;const i=Math.floor(n/60),a=n%60;return a?`${i}h ${a}m`:`${i}h`}function RGt({run:e,variant:t="compact"}){const n=e.passCriteria?.minimumPassRate??100,r=e.result??"pending",i=e.status??"pending",s=(e.summary?.passRate??0)*100,o=r==="passed";return i==="running"||i==="pending"?null:t==="compact"?l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsxs(Cn,{variant:"outline",className:o?"gap-1 bg-success/50 text-success-foreground border-success/50 hover:bg-success/70":"gap-1 bg-destructive/50 text-destructive-foreground border-destructive/50 hover:bg-destructive/70",children:[o?l.jsx(ko,{className:"h-3 w-3"}):l.jsx(qd,{className:"h-3 w-3"}),o?"Passed":"Failed"]})}),l.jsx(zt,{className:"max-w-xs",children:l.jsxs("div",{className:"space-y-1 text-xs",children:[l.jsx("div",{className:"font-medium text-white",children:o?"✓ Suite Passed":"✗ Suite Failed"}),l.jsxs("div",{className:"text-white",children:["Required: ",n,"% Accuracy"]})]})})]}):l.jsxs("div",{className:"space-y-3 rounded-lg border bg-muted/30 p-4",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[o?l.jsx(ko,{className:"h-5 w-5 text-success"}):l.jsx(qd,{className:"h-5 w-5 text-destructive"}),l.jsx("h3",{className:"text-sm font-medium",children:o?"Suite Passed":"Suite Failed"})]}),l.jsxs("div",{className:"space-y-2 text-xs",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-muted-foreground",children:"Criteria:"}),l.jsxs(Cn,{variant:"outline",className:"text-xs",children:["Min ",n,"% Accuracy"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("span",{className:"text-muted-foreground",children:"Accuracy:"}),l.jsxs("span",{className:"font-mono",children:[s.toFixed(1),"%"]}),l.jsxs("span",{className:"text-muted-foreground",children:["(threshold: ",n,"%)"]})]}),!o&&s<n&&l.jsxs("div",{className:"mt-2 rounded border-l-2 border-destructive bg-destructive/10 p-2 text-xs",children:["Accuracy ",s.toFixed(1),"% below threshold ",n,"%"]})]})]})}const d5e=(e,t)=>{switch(e){case"anthropic":return sPe;case"openai":return oPe;case"deepseek":return lPe;case"google":return uPe;case"mistral":return dPe;case"ollama":return t==="dark"||t==="system"&&typeof document<"u"&&document.documentElement.classList.contains("dark")?jI:II;case"meta":case"meta-llama":return cPe;case"x-ai":case"xai":return t==="dark"||t==="system"&&typeof document<"u"&&document.documentElement.classList.contains("dark")?RI:OI;case"litellm":return fPe;case"openrouter":return pPe;case"moonshotai":return t==="dark"||t==="system"&&typeof document<"u"&&document.documentElement.classList.contains("dark")?$I:PI;case"z-ai":return hPe;default:return null}};function PGt({trace:e,modelProvider:t="openai",toolsMetadata:n={},toolServerMap:r={}}){const[i,a]=b.useState("formatted");if(!e)return l.jsx("div",{className:"text-xs text-muted-foreground",children:"No trace data available"});let s=[];if(Array.isArray(e)?s=e:typeof e=="object"&&"messages"in e&&Array.isArray(e.messages)?s=e.messages:typeof e=="object"&&"role"in e&&(s=[e]),s.length===0)return l.jsx("div",{className:"text-xs text-muted-foreground",children:"No messages in trace"});const o=[];for(let u=0;u<s.length;u++){const c=s[u];if(c.role==="assistant"){const d=s[u+1];d&&d.role==="tool"?(o.push({type:"tool-group",messages:[c,d]}),u++):o.push({type:"assistant",messages:[c]})}else c.role==="user"?o.push({type:"user",messages:[c]}):o.push({type:"tool-group",messages:[c]})}return l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"flex items-center justify-between border-b border-border/40 pb-2",children:[l.jsxs("div",{className:"text-xs font-medium text-muted-foreground",children:[s.length," message",s.length!==1?"s":""]}),l.jsxs("div",{className:"flex items-center gap-1 rounded-md border border-border/40 bg-background p-0.5",children:[l.jsxs("button",{type:"button",onClick:()=>a("formatted"),className:`inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition-colors ${i==="formatted"?"bg-primary/10 text-foreground font-medium":"text-muted-foreground hover:text-foreground"}`,title:"Formatted view",children:[l.jsx(kw,{className:"h-3 w-3"}),"Formatted"]}),l.jsxs("button",{type:"button",onClick:()=>a("raw"),className:`inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition-colors ${i==="raw"?"bg-primary/10 text-foreground font-medium":"text-muted-foreground hover:text-foreground"}`,title:"Raw JSON view",children:[l.jsx(N1e,{className:"h-3 w-3"}),"Raw"]})]})]}),i==="raw"?l.jsx(zn,{viewOnly:!0,value:e}):l.jsx("div",{className:"space-y-6",children:o.map((u,c)=>u.type==="user"?l.jsx(lme,{message:u.messages[0],modelProvider:t},c):u.type==="tool-group"?l.jsx($Gt,{messages:u.messages,modelProvider:t,toolsMetadata:n,toolServerMap:r},c):l.jsx(lme,{message:u.messages[0],modelProvider:t},c))})]})}function lme({message:e,modelProvider:t}){const n=eo(s=>s.themeMode),r=d5e(t,n);if(e.role==="user"){const s=typeof e.content=="string"?e.content:e.content?.[0]?.text||"";return l.jsx("div",{className:"flex justify-end",children:l.jsx("div",{className:"max-w-3xl rounded-lg bg-primary px-4 py-3 text-sm text-primary-foreground shadow-sm",children:l.jsx("div",{className:"whitespace-pre-wrap break-words leading-6",children:s})})})}const a=Array.isArray(e.content)?e.content:[];return l.jsxs("article",{className:"flex gap-4 w-full",children:[l.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border/40 bg-muted/40",children:r?l.jsx("img",{src:r,alt:"Model logo",className:"h-4 w-4 object-contain"}):l.jsx(Bm,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx("div",{className:"flex-1 min-w-0 space-y-3 text-sm leading-6",children:a.map((s,o)=>l.jsx(f5e,{part:s},o))})]})}function $Gt({messages:e,modelProvider:t,toolsMetadata:n={},toolServerMap:r={}}){const i=eo(d=>d.themeMode),a=d5e(t,i),s=[],o=[],u=[];for(const d of e){const f=Array.isArray(d.content)?d.content:[];for(const p of f)p.type==="tool-call"?s.push(p):p.type==="tool-result"?o.push(p):u.push(p)}const c=s.map(d=>{const f=o.find(p=>p.toolCallId===d.toolCallId);return{toolCall:d,toolResult:f}});return l.jsxs("article",{className:"flex gap-4 w-full",children:[l.jsx("div",{className:"mt-1 flex h-8 w-8 shrink-0 items-center justify-center rounded-full border border-border/40 bg-muted/40",children:a?l.jsx("img",{src:a,alt:"Model logo",className:"h-4 w-4 object-contain"}):l.jsx(Bm,{className:"h-4 w-4 text-muted-foreground"})}),l.jsxs("div",{className:"flex-1 min-w-0 space-y-3 text-sm leading-6",children:[u.map((d,f)=>l.jsx(f5e,{part:d},`other-${f}`)),c.map((d,f)=>l.jsx(MGt,{toolCall:d.toolCall,toolResult:d.toolResult,toolsMetadata:n,toolServerMap:r},`tool-${f}`))]})]})}function f5e({part:e}){return e.type==="text"&&e.text?l.jsx("div",{className:"text-sm whitespace-pre-wrap break-words text-foreground",children:e.text}):e.type==="reasoning"?e.text?l.jsxs("div",{className:"rounded-lg border border-purple-500/20 bg-purple-500/5 p-3 text-xs",children:[l.jsxs("div",{className:"flex items-center gap-2 mb-2",children:[l.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-purple-500/60"}),l.jsx("span",{className:"text-[10px] font-semibold uppercase tracking-wide text-purple-700 dark:text-purple-400",children:"Reasoning"})]}),l.jsx("pre",{className:"whitespace-pre-wrap break-words text-muted-foreground leading-relaxed",children:e.text})]}):l.jsxs("div",{className:"rounded-lg border border-border/30 bg-muted/10 px-3 py-2 text-xs text-muted-foreground italic flex items-center gap-2",children:[l.jsx("span",{className:"inline-block h-2 w-2 rounded-full bg-purple-500/60 animate-pulse"}),"Model used internal reasoning (content not visible)"]}):l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/20 p-2",children:[l.jsxs("div",{className:"text-xs font-semibold text-muted-foreground mb-1",children:["Unknown part type: ",e.type]}),l.jsx(zn,{viewOnly:!0,value:e})]})}function MGt({toolCall:e,toolResult:t,toolsMetadata:n={},toolServerMap:r={}}){const[i,a]=b.useState(!1),o=eo(w=>w.themeMode)==="dark"?"h-3 w-3 filter invert":"h-3 w-3",u=e?.toolName||t?.toolName||"Unknown tool",c=e?.input!==void 0&&e?.input!==null,d=t?.output!==void 0&&t?.output!==null,f=t?.isError===!0,p=n[u],m=!!p?.["openai/outputTemplate"],y=!!p?.ui?.resourceUri,v=p?.ui?.resourceUri,x=JU(u,r),_=t?.output&&typeof t.output=="object"&&"type"in t.output&&"value"in t.output?t.output.value:t?.output;let S=_;if(d&&typeof t?.output=="object"&&t?.output!==null&&"content"in t.output&&Array.isArray(t.output.content)){const w=t.output.content.find(T=>T.type==="text");w?.text&&(S=w.text)}return l.jsxs("div",{className:"rounded-lg border border-border/50 bg-background/70 text-xs",children:[l.jsxs("button",{type:"button",className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left text-[11px] font-semibold uppercase tracking-wide text-muted-foreground cursor-pointer",onClick:()=>a(w=>!w),"aria-expanded":i,children:[l.jsx("span",{className:"inline-flex items-center gap-2 font-medium normal-case text-foreground",children:l.jsxs("span",{className:"inline-flex items-center gap-2",children:[l.jsx("img",{src:"/mcp.svg",alt:"",role:"presentation","aria-hidden":"true",className:o}),l.jsx("span",{className:"font-mono text-xs tracking-tight text-muted-foreground/80",children:u})]})}),l.jsxs("span",{className:"inline-flex items-center gap-2 text-muted-foreground",children:[l.jsx("span",{className:"inline-flex h-5 w-5 items-center justify-center",children:f?l.jsx(wo,{className:"h-4 w-4 text-destructive"}):t?l.jsx(ko,{className:"h-4 w-4 text-success"}):l.jsx(ko,{className:"h-4 w-4 text-muted-foreground"})}),l.jsx(Wr,{className:`h-4 w-4 transition-transform duration-150 ${i?"rotate-180":""}`})]})]}),i&&l.jsxs("div",{className:"space-y-4 border-t border-border/40 px-3 py-3",children:[c&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:"Input"}),l.jsx(zn,{viewOnly:!0,value:e.input})]}),d&&l.jsxs("div",{className:"space-y-1",children:[l.jsx("div",{className:"text-[10px] font-semibold uppercase tracking-wide text-muted-foreground/70",children:f?"Error":"Result"}),typeof S=="string"?l.jsx("pre",{className:`whitespace-pre-wrap break-words rounded-md border p-2 text-[11px] leading-relaxed ${f?"border-destructive/40 bg-destructive/10 text-destructive":"border-border/30 bg-muted/20"}`,children:S}):l.jsx("div",{className:f?"[&_.rounded-lg]:border-destructive/40 [&_.rounded-lg]:bg-destructive/10 [&_.rounded-lg]:text-destructive":"",children:l.jsx(zn,{viewOnly:!0,value:S})})]}),!c&&!d&&l.jsx("div",{className:"text-muted-foreground/70",children:"No tool details available."})]}),y&&x&&v&&d&&!f&&l.jsx(yK,{serverId:x,toolCallId:e?.toolCallId??`evals-${u}-${Date.now()}`,toolName:u,toolState:"output-available",toolInput:e?.input,toolOutput:_,resourceUri:v,toolMetadata:p,onSendFollowUp:void 0,onCallTool:void 0}),m&&!y&&x&&d&&!f&&l.jsx(vK,{serverId:x,toolCallId:e?.toolCallId,toolName:u,toolState:"output-available",toolInput:e?.input??null,toolOutput:_??null,toolMetadata:p,onSendFollowUp:void 0,onCallTool:void 0})]})}function jZ({iteration:e,testCase:t,serverNames:n=[]}){const r=$9("testSuites:getTestIterationBlob"),[i,a]=b.useState(null),[s,o]=b.useState(!1),[u,c]=b.useState(null),[d,f]=b.useState("formatted"),[p,m]=b.useState({}),[y,v]=b.useState({}),[x,_]=b.useState({});b.useEffect(()=>{let O=!1;async function R(){if(!e.blob){a(null),o(!1),c(null);return}o(!0),c(null);try{const U=await r({blobId:e.blob});O||a(U)}catch(U){O||(c(U?.message||"Failed to load blob"),console.error("Blob load error:",U))}finally{O||o(!1)}}return R(),()=>{O=!0}},[e.blob,r]),b.useEffect(()=>{(async()=>{if(n.length===0){m({}),v({}),_({});return}try{const R={},U={},z={};await Promise.all(n.map(async F=>{try{const D=await _g({serverId:F});if(D.tools)for(const q of D.tools)R[q.name]={name:q.name,inputSchema:q.inputSchema},z[q.name]=F;const W=D.toolsMetadata??{};for(const[q,X]of Object.entries(W))U[q]=X}catch(D){console.warn(`Failed to fetch tools for server ${F}:`,D)}})),_(R),m(U),v(z)}catch{m({}),v({}),_({})}})()},[n]);const S=e.testCaseSnapshot?.expectedToolCalls||t?.expectedToolCalls||[],w=e.actualToolCalls||[],T=O=>Array.isArray(O)?O.join(" | "):typeof O=="string"?O:String(O),N=(O,R)=>{const U=x[O];return U?.inputSchema?.properties?U.inputSchema.properties[R]:null},E=(O,R)=>{const U=Object.entries(O);return U.length===0?l.jsx("span",{className:"text-muted-foreground italic",children:"No arguments"}):l.jsx("div",{className:"space-y-1",children:U.map(([z,F])=>{const D=R?N(R,z):null;return l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsxs("span",{className:"font-medium text-foreground",children:[z,":"]}),D?.type&&l.jsx("span",{className:"text-[10px] font-normal text-muted-foreground bg-background/50 px-1.5 py-0.5 rounded border border-border/40",children:T(D.type)})]}),l.jsx("span",{className:"font-mono text-muted-foreground",children:typeof F=="object"?JSON.stringify(F):String(F)})]},z)})})},I=(O=>{if(!O)return null;try{return JSON.parse(O)}catch{return null}})(e.errorDetails),[M,$]=b.useState(!1);return l.jsxs("div",{className:"space-y-4 py-2",children:[e.error&&l.jsxs("div",{className:"rounded-md border border-destructive/50 bg-destructive/10 p-3 space-y-2",children:[l.jsx("div",{className:"text-xs font-semibold text-destructive uppercase tracking-wide",children:"Error"}),l.jsx("div",{className:"text-xs text-destructive whitespace-pre-wrap font-mono",children:e.error}),e.errorDetails&&l.jsxs(qR,{open:M,onOpenChange:$,children:[l.jsxs(HR,{className:"flex items-center gap-1.5 text-xs text-destructive hover:text-destructive/80 transition-colors",children:[l.jsx("span",{children:"More details"}),M?l.jsx(Wr,{className:"h-3 w-3"}):l.jsx(wr,{className:"h-3 w-3"})]}),l.jsx(VR,{className:"mt-2",children:l.jsx("div",{className:"rounded border border-destructive/30 bg-background/50 p-2",children:I?l.jsx(zn,{value:I,readOnly:!0,showToolbar:!1}):l.jsx("pre",{className:"text-xs font-mono text-destructive whitespace-pre-wrap overflow-x-auto",children:e.errorDetails})})})]})]}),(S.length>0||w.length>0)&&l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between border-b border-border/40 pb-2",children:[l.jsx("div",{className:"text-xs font-semibold",children:"Tool Calls"}),l.jsxs("div",{className:"flex items-center gap-1 rounded-md border border-border/40 bg-background p-0.5",children:[l.jsxs("button",{type:"button",onClick:()=>f("formatted"),className:`inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition-colors ${d==="formatted"?"bg-primary/10 text-foreground font-medium":"text-muted-foreground hover:text-foreground"}`,title:"Formatted view",children:[l.jsx(kw,{className:"h-3 w-3"}),"Formatted"]}),l.jsxs("button",{type:"button",onClick:()=>f("raw"),className:`inline-flex items-center gap-1.5 rounded px-2 py-1 text-xs transition-colors ${d==="raw"?"bg-primary/10 text-foreground font-medium":"text-muted-foreground hover:text-foreground"}`,title:"Raw JSON view",children:[l.jsx(N1e,{className:"h-3 w-3"}),"Raw"]})]})]}),d==="raw"?l.jsxs("div",{className:"grid gap-3 md:grid-cols-2",children:[l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/10 p-3 space-y-2",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Expected"}),S.length===0?l.jsx("div",{className:"text-xs text-muted-foreground italic",children:"No expected tool calls"}):l.jsx("pre",{className:"text-xs font-mono bg-background/50 rounded p-2 overflow-x-auto",children:JSON.stringify(S,null,2)})]}),l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/10 p-3 space-y-2",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground uppercase",children:"Actual"}),w.length===0?l.jsx("div",{className:"text-xs text-muted-foreground italic",children:"No tool calls made"}):l.jsx("pre",{className:"text-xs font-mono bg-background/50 rounded p-2 overflow-x-auto",children:JSON.stringify(w,null,2)})]})]}):l.jsxs("div",{className:"grid gap-2 md:grid-cols-2",children:[l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/10 p-2 space-y-2",children:[l.jsx("div",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wide",children:"Expected"}),S.length===0?l.jsx("div",{className:"text-xs text-muted-foreground italic",children:"No expected tool calls"}):l.jsx("div",{className:"space-y-1.5",children:S.map((O,R)=>l.jsxs("div",{className:"rounded border border-border/30 bg-background/50 p-1.5 space-y-1",children:[l.jsx("div",{className:"font-mono text-xs font-medium",children:O.toolName}),Object.keys(O.arguments||{}).length>0&&l.jsx("div",{className:"text-xs bg-muted/30 rounded p-1.5",children:E(O.arguments||{},O.toolName)})]},`expected-${R}`))})]}),l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/10 p-2 space-y-2",children:[l.jsx("div",{className:"text-[10px] font-semibold text-muted-foreground uppercase tracking-wide",children:"Actual"}),w.length===0?l.jsx("div",{className:"text-xs text-muted-foreground italic",children:"No tool calls made"}):l.jsx("div",{className:"space-y-1.5",children:w.map((O,R)=>l.jsxs("div",{className:"rounded border border-border/30 bg-background/50 p-1.5 space-y-1",children:[l.jsx("div",{className:"font-mono text-xs font-medium",children:O.toolName}),Object.keys(O.arguments||{}).length>0&&l.jsx("div",{className:"text-xs bg-muted/30 rounded p-1.5",children:E(O.arguments||{},O.toolName)})]},`actual-${R}`))})]})]})]}),e.blob&&l.jsxs("div",{className:"space-y-1.5",children:[l.jsx("div",{className:"text-xs font-semibold",children:"Trace"}),l.jsx("div",{className:"rounded-md bg-muted/20 p-3 max-h-[480px] overflow-y-auto",children:s?l.jsx("div",{className:"text-xs text-muted-foreground",children:"Loading trace"}):u?l.jsx("div",{className:"text-xs text-destructive",children:u}):l.jsx(PGt,{trace:i,modelProvider:t?.models[0]?.provider||e.testCaseSnapshot?.provider||"openai",toolsMetadata:p,toolServerMap:y})})]})]})}function DGt({selectedRunDetails:e,caseGroupsForSelectedRun:t,selectedRunChartData:n,runDetailSortBy:r,onSortChange:i,showRunSummarySidebar:a,setShowRunSummarySidebar:s,serverNames:o=[]}){const[u,c]=b.useState(null),d=b.useMemo(()=>{if(t.length===0)return e.summary??{passed:0,failed:0,total:0,passRate:0};const f=t.filter(v=>MI(v)).length,p=t.filter(v=>!MI(v)).length,m=t.length,y=m>0?f/m:0;return{passed:f,failed:p,total:m,passRate:y}},[t,e.summary]);return l.jsxs("div",{className:"relative",children:[l.jsx("div",{className:"rounded-lg border bg-background/80 px-3 py-2",children:l.jsxs("div",{className:"flex items-center gap-6",children:[l.jsxs("div",{className:"flex gap-6 flex-1",children:[l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"text-xs text-muted-foreground",children:"Accuracy"}),l.jsx("div",{className:"text-sm font-semibold",children:d.total>0?`${Math.round(d.passRate*100)}%`:"—"})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"text-xs text-muted-foreground",children:"Passed"}),l.jsx("div",{className:"text-sm font-semibold",children:d.passed.toLocaleString()})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"text-xs text-muted-foreground",children:"Failed"}),l.jsx("div",{className:"text-sm font-semibold",children:d.failed.toLocaleString()})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"text-xs text-muted-foreground",children:"Total"}),l.jsx("div",{className:"text-sm font-semibold",children:d.total.toLocaleString()})]}),l.jsxs("div",{className:"space-y-0.5",children:[l.jsx("div",{className:"text-xs text-muted-foreground",children:"Duration"}),l.jsx("div",{className:"text-sm font-semibold",children:e.completedAt&&e.createdAt?p5e(e.completedAt-e.createdAt):"—"})]})]}),n.donutData.length>0&&l.jsx("div",{className:"flex items-center gap-2",children:l.jsx(Ud,{config:{passed:{label:"Passed",color:"hsl(142.1 76.2% 36.3%)"},failed:{label:"Failed",color:"hsl(0 84.2% 60.2%)"},pending:{label:"Pending",color:"hsl(45.4 93.4% 47.5%)"},cancelled:{label:"Cancelled",color:"hsl(240 3.7% 15.9%)"}},className:"h-12 w-12",children:l.jsxs(u5e,{children:[l.jsx(Fd,{content:l.jsx(AZ,{hideLabel:!0})}),l.jsx(Wc,{data:n.donutData,dataKey:"value",nameKey:"name",innerRadius:15,outerRadius:22,strokeWidth:1,children:l.jsx(da,{content:({viewBox:f})=>{if(f&&"cx"in f&&"cy"in f){const p=n.donutData.reduce((m,y)=>m+y.value,0);return l.jsxs("text",{x:f.cx,y:f.cy,textAnchor:"middle",dominantBaseline:"middle",children:[l.jsx("tspan",{x:f.cx,y:f.cy,className:"fill-foreground text-xs font-bold",children:p}),l.jsx("tspan",{x:f.cx,y:(f.cy||0)+8,className:"fill-muted-foreground text-[8px]",children:"Total"})]})}}})})]})})}),l.jsx("span",{className:"text-xs font-medium text-foreground capitalize",children:e.status}),l.jsx(RGt,{run:e,variant:"compact"})]})}),l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground mt-4",children:[l.jsxs("div",{className:"border-b px-4 py-2 shrink-0 flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("div",{className:"text-xs font-semibold",children:"All Iterations"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"All test iterations from this run"})]}),l.jsxs("select",{value:r,onChange:f=>i(f.target.value),className:"text-xs border rounded px-2 py-1 bg-background",children:[l.jsx("option",{value:"model",children:"Sort by Model"}),l.jsx("option",{value:"test",children:"Sort by Test"}),l.jsx("option",{value:"result",children:"Sort by Result"})]})]}),t.length>0&&l.jsxs("div",{className:"flex items-center gap-4 w-full px-4 py-1.5 bg-muted/30 border-b text-xs font-medium text-muted-foreground pl-7",children:[l.jsx("div",{className:"flex-1",children:"Test"}),l.jsxs("div",{className:"flex items-center gap-4 shrink-0",children:[l.jsx("div",{className:"min-w-[120px]",children:"Model"}),l.jsx("div",{className:"min-w-[50px]",children:"Tools"}),l.jsx("div",{className:"min-w-[60px]",children:"Tokens"}),l.jsx("div",{className:"min-w-[40px] text-right",children:"Duration"})]})]}),l.jsx("div",{className:"divide-y",children:t.length===0?l.jsx("div",{className:"px-4 py-12 text-center text-sm text-muted-foreground",children:"No test cases found for this run."}):t.map(f=>l.jsx(LGt,{iteration:f,isOpen:u===f._id,onToggle:()=>c(u===f._id?null:f._id),showModelInfo:!0,serverNames:o},f._id))})]}),a&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"fixed inset-0 bg-black/50 z-40 animate-in fade-in duration-200",onClick:()=>s(!1)}),l.jsxs("div",{className:"fixed right-0 top-0 bottom-0 w-[500px] bg-background border-l z-50 overflow-y-auto animate-in slide-in-from-right duration-300",children:[l.jsxs("div",{className:"sticky top-0 bg-background border-b px-4 py-3 flex items-center justify-between z-10",children:[l.jsx("div",{className:"text-sm font-semibold",children:"Run Summary"}),l.jsx(Ee,{variant:"ghost",size:"icon",onClick:()=>s(!1),children:l.jsx(Yn,{className:"h-4 w-4"})})]}),l.jsx("div",{className:"p-4 space-y-4",children:(n.durationData.length>0||n.tokensData.length>0||n.modelData.length>0)&&l.jsxs("div",{className:"space-y-4",children:[n.durationData.length>0&&l.jsxs("div",{className:"rounded-lg border bg-background/50 p-4",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-3",children:"Duration per Test"}),l.jsx(Ud,{config:{duration:{label:"Duration",color:"var(--chart-1)"}},className:"aspect-auto h-64 w-full",children:l.jsxs(Xv,{data:n.durationData,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"name",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:10,angle:-45,textAnchor:"end"},interval:0,height:80,tickFormatter:f=>f.length>20?f.substring(0,17)+"...":f}),l.jsx(Nu,{tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:f=>`${f.toFixed(1)}s`}),l.jsx(Fd,{cursor:!1,content:({active:f,payload:p})=>{if(!f||!p||p.length===0)return null;const m=p[0].payload;return l.jsxs("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:[l.jsx("div",{className:"text-xs font-semibold",children:m.name}),l.jsxs("div",{className:"text-sm font-medium mt-1",children:[m.durationSeconds.toFixed(2),"s"]})]})}}),l.jsx(Ml,{dataKey:"durationSeconds",fill:"var(--color-duration)",radius:[4,4,0,0],isAnimationActive:!1})]})})]}),n.tokensData.length>0&&l.jsxs("div",{className:"rounded-lg border bg-background/50 p-4",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-3",children:"Tokens per Test"}),l.jsx(Ud,{config:{tokens:{label:"Tokens",color:"var(--chart-2)"}},className:"aspect-auto h-64 w-full",children:l.jsxs(Xv,{data:n.tokensData,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"name",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:10,angle:-45,textAnchor:"end"},interval:0,height:80,tickFormatter:f=>f.length>20?f.substring(0,17)+"...":f}),l.jsx(Nu,{tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:f=>f.toLocaleString()}),l.jsx(Fd,{cursor:!1,content:({active:f,payload:p})=>{if(!f||!p||p.length===0)return null;const m=p[0].payload;return l.jsxs("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:[l.jsx("div",{className:"text-xs font-semibold",children:m.name}),l.jsxs("div",{className:"text-sm font-medium mt-1",children:[Math.round(m.tokens).toLocaleString()," ","tokens"]})]})}}),l.jsx(Ml,{dataKey:"tokens",fill:"var(--color-tokens)",radius:[4,4,0,0],isAnimationActive:!1})]})})]}),n.modelData.length>0&&l.jsxs("div",{className:"rounded-lg border bg-background/50 p-4",children:[l.jsx("div",{className:"text-xs font-medium text-muted-foreground mb-3",children:"Performance by model"}),l.jsx(Ud,{config:{passRate:{label:"Accuracy",color:"var(--chart-1)"}},className:"aspect-auto h-48 w-full",children:l.jsxs(Xv,{data:n.modelData,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"model",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:11},interval:0,height:40,tickFormatter:f=>f.length>15?f.substring(0,12)+"...":f}),l.jsx(Nu,{domain:[0,100],tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:f=>`${f}%`}),l.jsx(Fd,{cursor:!1,content:({active:f,payload:p})=>{if(!f||!p||p.length===0)return null;const m=p[0].payload;return l.jsx("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:l.jsxs("div",{className:"grid gap-2",children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"text-xs font-semibold",children:m.model}),l.jsxs("span",{className:"text-xs text-muted-foreground mt-0.5",children:[m.passed," passed · ",m.failed," ","failed"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"h-2 w-2 rounded-full",style:{backgroundColor:"var(--color-passRate)"}}),l.jsxs("span",{className:"text-sm font-semibold",children:[m.passRate,"%"]})]})]})})}}),l.jsx(Ml,{dataKey:"passRate",fill:"var(--color-passRate)",radius:[4,4,0,0],isAnimationActive:!1,minPointSize:8})]})})]})]})})]})]})]})}function LGt({iteration:e,isOpen:t,onToggle:n,showModelInfo:r=!1,serverNames:i=[]}){const a=e.startedAt??e.createdAt,s=e.updatedAt??e.createdAt,o=a&&s?Math.max(s-a,0):null,u=e.status==="pending"||e.status==="running",c=e.testCaseSnapshot,d=e.actualToolCalls||[],f=c?.model||"—",p=Fl(e);return l.jsxs("div",{className:`relative ${u?"opacity-60":""}`,children:[l.jsx("div",{className:`absolute left-0 top-0 h-full w-1 ${SK(p)}`}),l.jsxs("button",{onClick:n,className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 cursor-pointer hover:bg-muted/50",children:[l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3 pl-2",children:[l.jsx("div",{className:"text-muted-foreground shrink-0",children:t?l.jsx(Wr,{className:"h-3.5 w-3.5"}):l.jsx(wr,{className:"h-3.5 w-3.5"})}),l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:[l.jsx("span",{className:"text-xs font-medium truncate",children:c?.title||"Iteration"}),c?.isNegativeTest&&l.jsx("span",{className:"text-[10px] text-orange-500 shrink-0",title:"Negative test",children:"NEG"})]})]}),l.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground shrink-0",children:[r&&l.jsx("div",{className:"min-w-[120px] text-left truncate",children:l.jsx("span",{className:"font-mono text-xs",children:f})}),l.jsx("div",{className:"min-w-[50px] text-center",children:l.jsx("span",{className:"font-mono",children:u?"—":d.length})}),l.jsx("div",{className:"min-w-[60px] text-center",children:l.jsx("span",{className:"font-mono",children:u?"—":Number(e.tokensUsed||0).toLocaleString()})}),l.jsx("div",{className:"font-mono min-w-[40px] text-right",children:u?"—":o!==null?p5e(o):"—"}),u&&l.jsx("div",{className:"w-3.5 flex items-center justify-center",children:l.jsx(Pn,{className:"h-3.5 w-3.5 animate-spin text-warning"})})]})]}),t?l.jsx("div",{className:"border-t bg-muted/20 px-4 pb-4 pt-3 pl-8",children:l.jsx(jZ,{iteration:e,testCase:null,serverNames:i})}):null]})}function p5e(e){if(e<1e3)return`${e}ms`;const t=Math.round(e/1e3);if(t<60)return`${t}s`;const n=Math.floor(t/60),r=t%60;if(n<60)return r?`${n}m ${r}s`:`${n}m`;const i=Math.floor(n/60),a=n%60;return a?`${i}h ${a}m`:`${i}h`}function zGt({suite:e,testCases:t,onUpdate:n,availableModels:r}){const[i,a]=b.useState(!1),s=b.useMemo(()=>{if(!t||t.length===0)return[];const v=new Map;return t.forEach(x=>{x.models&&Array.isArray(x.models)&&x.models.forEach(_=>{const S=`${_.provider}:${_.model}`;if(!v.has(S)){const w=r.find(T=>T.id===_.model);v.set(S,{model:_.model,provider:_.provider,displayName:w?.name||_.model})}})}),Array.from(v.values())},[t,r]),[o,u]=b.useState(s);b.useEffect(()=>{u(s)},[s]);const c=async v=>{await n(v)},d=async v=>{const x=o.filter(_=>_.model!==v);u(x),await c(x)},f=async v=>{if(o.some(S=>S.model===v.id)){a(!1);return}const x={model:v.id,provider:v.provider,displayName:v.name},_=[...o,x];u(_),await c(_),a(!1)},p=b.useMemo(()=>{const v=new Map;return r.forEach(x=>{const _=x.provider;v.has(_)||v.set(_,[]),v.get(_).push(x)}),v},[r]),m=b.useMemo(()=>Array.from(p.entries()).filter(([v,x])=>x.some(_=>_r(_.id))).sort(([v],[x])=>v.localeCompare(x)),[p]),y=b.useMemo(()=>Array.from(p.entries()).filter(([v,x])=>x.some(_=>!_r(_.id))).sort(([v],[x])=>v.localeCompare(x)),[p]);return l.jsx("div",{className:"space-y-3",children:l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"flex items-start justify-between gap-4",children:[l.jsxs("div",{className:"flex-1",children:[l.jsx("h2",{className:"text-base font-semibold text-foreground",children:"Models"}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Select at least one model to run the evaluation."})]}),l.jsxs(Ic,{open:i,onOpenChange:a,children:[l.jsx(jc,{asChild:!0,children:l.jsxs(Ee,{size:"sm",variant:"outline",className:"shrink-0",children:[l.jsx(_o,{className:"h-4 w-4 mr-2"}),"Add model"]})}),l.jsxs(Oc,{align:"end",side:"bottom",sideOffset:4,className:"w-[300px]",children:[m.length>0&&l.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"MCPJam Free Models"}),m.map(([v,x])=>{const _=x.filter(S=>_r(S.id));return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:v}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:v}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.length," model",_.length!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:_.map(S=>l.jsxs(Oi,{onSelect:()=>f(S),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:o.some(w=>w.model===S.id),children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:S.name})}),o.some(w=>w.model===S.id)&&l.jsx(Cn,{variant:"secondary",className:"text-xs",children:"Added"})]},S.id))})]},v)}),m.length>0&&y.length>0&&l.jsx("div",{className:"my-1 h-px bg-muted/50"}),y.length>0&&l.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"Your Providers"}),y.map(([v,x])=>{const _=x.filter(S=>!_r(S.id));return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:v}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:v}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.length," model",_.length!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:_.map(S=>l.jsxs(Oi,{onSelect:()=>f(S),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:o.some(w=>w.model===S.id),children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:S.name})}),o.some(w=>w.model===S.id)&&l.jsx(Cn,{variant:"secondary",className:"text-xs",children:"Added"})]},S.id))})]},v)})]})]})]}),o.length===0?l.jsxs(vx,{className:"p-6 text-center",children:[l.jsx("p",{className:"text-sm text-muted-foreground",children:"No models configured"}),l.jsxs(Ic,{open:i,onOpenChange:a,children:[l.jsx(jc,{asChild:!0,children:l.jsxs(Ee,{className:"mt-4",variant:"outline",children:[l.jsx(_o,{className:"h-4 w-4 mr-2"}),"Add your first model"]})}),l.jsxs(Oc,{align:"center",side:"bottom",sideOffset:4,className:"w-[300px]",children:[m.length>0&&l.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"MCPJam Free Models"}),m.map(([v,x])=>{const _=x.filter(S=>_r(S.id));return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:v}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:v}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.length," model",_.length!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:_.map(S=>l.jsxs(Oi,{onSelect:()=>f(S),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:o.some(w=>w.model===S.id),children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:S.name})}),o.some(w=>w.model===S.id)&&l.jsx(Cn,{variant:"secondary",className:"text-xs",children:"Added"})]},S.id))})]},v)}),m.length>0&&y.length>0&&l.jsx("div",{className:"my-1 h-px bg-muted/50"}),y.length>0&&l.jsx("div",{className:"px-2 py-1 text-[10px] uppercase tracking-wide text-muted-foreground",children:"Your Providers"}),y.map(([v,x])=>{const _=x.filter(S=>!_r(S.id));return l.jsxs(_p,{children:[l.jsxs(wp,{className:"flex items-center gap-3 text-sm cursor-pointer",children:[l.jsx(Md,{provider:v}),l.jsxs("div",{className:"flex flex-col flex-1",children:[l.jsx("span",{className:"font-medium capitalize",children:v}),l.jsxs("span",{className:"text-xs text-muted-foreground",children:[_.length," model",_.length!==1?"s":""]})]})]}),l.jsx(Sp,{className:"min-w-[200px] max-h-[180px] overflow-y-auto",avoidCollisions:!0,collisionPadding:8,children:_.map(S=>l.jsxs(Oi,{onSelect:()=>f(S),className:"flex items-center gap-3 text-sm cursor-pointer",disabled:o.some(w=>w.model===S.id),children:[l.jsx("div",{className:"flex flex-col flex-1",children:l.jsx("span",{className:"font-medium",children:S.name})}),o.some(w=>w.model===S.id)&&l.jsx(Cn,{variant:"secondary",className:"text-xs",children:"Added"})]},S.id))})]},v)})]})]})]}):l.jsx("div",{className:"flex flex-wrap gap-2",children:o.map(v=>l.jsxs(Cn,{variant:"secondary",className:"px-3 py-1.5",children:[l.jsx("span",{className:"mr-2",children:v.displayName}),l.jsx("button",{onClick:()=>d(v.model),className:"text-muted-foreground hover:text-destructive",disabled:o.length===1,title:o.length===1?"Cannot remove last model":"Remove model",children:l.jsx(Yn,{className:"h-3 w-3"})})]},v.model))})]})})}var ume=1,UGt=.9,FGt=.8,BGt=.17,y8=.1,x8=.999,qGt=.9999,HGt=.99,VGt=/[\\\/_+.#"@\[\(\{&]/,GGt=/[\\\/_+.#"@\[\(\{&]/g,WGt=/[\s-]/,h5e=/[\s-]/g;function UB(e,t,n,r,i,a,s){if(a===t.length)return i===e.length?ume:HGt;var o=`${i},${a}`;if(s[o]!==void 0)return s[o];for(var u=r.charAt(a),c=n.indexOf(u,i),d=0,f,p,m,y;c>=0;)f=UB(e,t,n,r,c+1,a+1,s),f>d&&(c===i?f*=ume:VGt.test(e.charAt(c-1))?(f*=FGt,m=e.slice(i,c-1).match(GGt),m&&i>0&&(f*=Math.pow(x8,m.length))):WGt.test(e.charAt(c-1))?(f*=UGt,y=e.slice(i,c-1).match(h5e),y&&i>0&&(f*=Math.pow(x8,y.length))):(f*=BGt,i>0&&(f*=Math.pow(x8,c-i))),e.charAt(c)!==t.charAt(a)&&(f*=qGt)),(f<y8&&n.charAt(c-1)===r.charAt(a+1)||r.charAt(a+1)===r.charAt(a)&&n.charAt(c-1)!==r.charAt(a))&&(p=UB(e,t,n,r,c+1,a+2,s),p*y8>f&&(f=p*y8)),f>d&&(d=f),c=n.indexOf(u,c+1);return s[o]=d,d}function cme(e){return e.toLowerCase().replace(h5e," ")}function KGt(e,t,n){return e=n&&n.length>0?`${e+" "+n.join(" ")}`:e,UB(e,t,cme(e),cme(t),0,0,{})}var ZGt=Symbol.for("react.lazy"),Mj=dO[" use ".trim().toString()];function YGt(e){return typeof e=="object"&&e!==null&&"then"in e}function m5e(e){return e!=null&&typeof e=="object"&&"$$typeof"in e&&e.$$typeof===ZGt&&"_payload"in e&&YGt(e._payload)}function XGt(e){const t=JGt(e),n=b.forwardRef((r,i)=>{let{children:a,...s}=r;m5e(a)&&typeof Mj=="function"&&(a=Mj(a._payload));const o=b.Children.toArray(a),u=o.find(eWt);if(u){const c=u.props.children,d=o.map(f=>f===u?b.Children.count(c)>1?b.Children.only(null):b.isValidElement(c)?c.props.children:null:f);return l.jsx(t,{...s,ref:i,children:b.isValidElement(c)?b.cloneElement(c,void 0,d):null})}return l.jsx(t,{...s,ref:i,children:a})});return n.displayName=`${e}.Slot`,n}function JGt(e){const t=b.forwardRef((n,r)=>{let{children:i,...a}=n;if(m5e(i)&&typeof Mj=="function"&&(i=Mj(i._payload)),b.isValidElement(i)){const s=nWt(i),o=tWt(a,i.props);return i.type!==b.Fragment&&(o.ref=r?Cc(r,s):s),b.cloneElement(i,o)}return b.Children.count(i)>1?b.Children.only(null):null});return t.displayName=`${e}.SlotClone`,t}var QGt=Symbol("radix.slottable");function eWt(e){return b.isValidElement(e)&&typeof e.type=="function"&&"__radixId"in e.type&&e.type.__radixId===QGt}function tWt(e,t){const n={...t};for(const r in t){const i=e[r],a=t[r];/^on[A-Z]/.test(r)?i&&a?n[r]=(...o)=>{const u=a(...o);return i(...o),u}:i&&(n[r]=i):r==="style"?n[r]={...i,...a}:r==="className"&&(n[r]=[i,a].filter(Boolean).join(" "))}return{...e,...n}}function nWt(e){let t=Object.getOwnPropertyDescriptor(e.props,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning;return n?e.ref:(t=Object.getOwnPropertyDescriptor(e,"ref")?.get,n=t&&"isReactWarning"in t&&t.isReactWarning,n?e.props.ref:e.props.ref||e.ref)}var rWt=["a","button","div","form","h2","h3","img","input","label","li","nav","ol","p","select","span","svg","ul"],gh=rWt.reduce((e,t)=>{const n=XGt(`Primitive.${t}`),r=b.forwardRef((i,a)=>{const{asChild:s,...o}=i,u=s?n:t;return typeof window<"u"&&(window[Symbol.for("radix-ui")]=!0),l.jsx(u,{...o,ref:a})});return r.displayName=`Primitive.${t}`,{...e,[t]:r}},{}),z_='[cmdk-group=""]',b8='[cmdk-group-items=""]',iWt='[cmdk-group-heading=""]',g5e='[cmdk-item=""]',dme=`${g5e}:not([aria-disabled="true"])`,FB="cmdk-item-select",uv="data-value",aWt=(e,t,n)=>KGt(e,t,n),v5e=b.createContext(void 0),vk=()=>b.useContext(v5e),y5e=b.createContext(void 0),OZ=()=>b.useContext(y5e),x5e=b.createContext(void 0),b5e=b.forwardRef((e,t)=>{let n=cv(()=>{var G,P;return{search:"",value:(P=(G=e.value)!=null?G:e.defaultValue)!=null?P:"",selectedItemId:void 0,filtered:{count:0,items:new Map,groups:new Set}}}),r=cv(()=>new Set),i=cv(()=>new Map),a=cv(()=>new Map),s=cv(()=>new Set),o=_5e(e),{label:u,children:c,value:d,onValueChange:f,filter:p,shouldFilter:m,loop:y,disablePointerSelection:v=!1,vimBindings:x=!0,..._}=e,S=Ui(),w=Ui(),T=Ui(),N=b.useRef(null),E=gWt();dg(()=>{if(d!==void 0){let G=d.trim();n.current.value=G,A.emit()}},[d]),dg(()=>{E(6,U)},[]);let A=b.useMemo(()=>({subscribe:G=>(s.current.add(G),()=>s.current.delete(G)),snapshot:()=>n.current,setState:(G,P,V)=>{var K,Q,oe,re;if(!Object.is(n.current[G],P)){if(n.current[G]=P,G==="search")R(),$(),E(1,O);else if(G==="value"){if(document.activeElement.hasAttribute("cmdk-input")||document.activeElement.hasAttribute("cmdk-root")){let ee=document.getElementById(T);ee?ee.focus():(K=document.getElementById(S))==null||K.focus()}if(E(7,()=>{var ee;n.current.selectedItemId=(ee=z())==null?void 0:ee.id,A.emit()}),V||E(5,U),((Q=o.current)==null?void 0:Q.value)!==void 0){let ee=P??"";(re=(oe=o.current).onValueChange)==null||re.call(oe,ee);return}}A.emit()}},emit:()=>{s.current.forEach(G=>G())}}),[]),I=b.useMemo(()=>({value:(G,P,V)=>{var K;P!==((K=a.current.get(G))==null?void 0:K.value)&&(a.current.set(G,{value:P,keywords:V}),n.current.filtered.items.set(G,M(P,V)),E(2,()=>{$(),A.emit()}))},item:(G,P)=>(r.current.add(G),P&&(i.current.has(P)?i.current.get(P).add(G):i.current.set(P,new Set([G]))),E(3,()=>{R(),$(),n.current.value||O(),A.emit()}),()=>{a.current.delete(G),r.current.delete(G),n.current.filtered.items.delete(G);let V=z();E(4,()=>{R(),V?.getAttribute("id")===G&&O(),A.emit()})}),group:G=>(i.current.has(G)||i.current.set(G,new Set),()=>{a.current.delete(G),i.current.delete(G)}),filter:()=>o.current.shouldFilter,label:u||e["aria-label"],getDisablePointerSelection:()=>o.current.disablePointerSelection,listId:S,inputId:T,labelId:w,listInnerRef:N}),[]);function M(G,P){var V,K;let Q=(K=(V=o.current)==null?void 0:V.filter)!=null?K:aWt;return G?Q(G,n.current.search,P):0}function $(){if(!n.current.search||o.current.shouldFilter===!1)return;let G=n.current.filtered.items,P=[];n.current.filtered.groups.forEach(K=>{let Q=i.current.get(K),oe=0;Q.forEach(re=>{let ee=G.get(re);oe=Math.max(ee,oe)}),P.push([K,oe])});let V=N.current;F().sort((K,Q)=>{var oe,re;let ee=K.getAttribute("id"),le=Q.getAttribute("id");return((oe=G.get(le))!=null?oe:0)-((re=G.get(ee))!=null?re:0)}).forEach(K=>{let Q=K.closest(b8);Q?Q.appendChild(K.parentElement===Q?K:K.closest(`${b8} > *`)):V.appendChild(K.parentElement===V?K:K.closest(`${b8} > *`))}),P.sort((K,Q)=>Q[1]-K[1]).forEach(K=>{var Q;let oe=(Q=N.current)==null?void 0:Q.querySelector(`${z_}[${uv}="${encodeURIComponent(K[0])}"]`);oe?.parentElement.appendChild(oe)})}function O(){let G=F().find(V=>V.getAttribute("aria-disabled")!=="true"),P=G?.getAttribute(uv);A.setState("value",P||void 0)}function R(){var G,P,V,K;if(!n.current.search||o.current.shouldFilter===!1){n.current.filtered.count=r.current.size;return}n.current.filtered.groups=new Set;let Q=0;for(let oe of r.current){let re=(P=(G=a.current.get(oe))==null?void 0:G.value)!=null?P:"",ee=(K=(V=a.current.get(oe))==null?void 0:V.keywords)!=null?K:[],le=M(re,ee);n.current.filtered.items.set(oe,le),le>0&&Q++}for(let[oe,re]of i.current)for(let ee of re)if(n.current.filtered.items.get(ee)>0){n.current.filtered.groups.add(oe);break}n.current.filtered.count=Q}function U(){var G,P,V;let K=z();K&&(((G=K.parentElement)==null?void 0:G.firstChild)===K&&((V=(P=K.closest(z_))==null?void 0:P.querySelector(iWt))==null||V.scrollIntoView({block:"nearest"})),K.scrollIntoView({block:"nearest"}))}function z(){var G;return(G=N.current)==null?void 0:G.querySelector(`${g5e}[aria-selected="true"]`)}function F(){var G;return Array.from(((G=N.current)==null?void 0:G.querySelectorAll(dme))||[])}function D(G){let P=F()[G];P&&A.setState("value",P.getAttribute(uv))}function W(G){var P;let V=z(),K=F(),Q=K.findIndex(re=>re===V),oe=K[Q+G];(P=o.current)!=null&&P.loop&&(oe=Q+G<0?K[K.length-1]:Q+G===K.length?K[0]:K[Q+G]),oe&&A.setState("value",oe.getAttribute(uv))}function q(G){let P=z(),V=P?.closest(z_),K;for(;V&&!K;)V=G>0?hWt(V,z_):mWt(V,z_),K=V?.querySelector(dme);K?A.setState("value",K.getAttribute(uv)):W(G)}let X=()=>D(F().length-1),L=G=>{G.preventDefault(),G.metaKey?X():G.altKey?q(1):W(1)},Y=G=>{G.preventDefault(),G.metaKey?D(0):G.altKey?q(-1):W(-1)};return b.createElement(gh.div,{ref:t,tabIndex:-1,..._,"cmdk-root":"",onKeyDown:G=>{var P;(P=_.onKeyDown)==null||P.call(_,G);let V=G.nativeEvent.isComposing||G.keyCode===229;if(!(G.defaultPrevented||V))switch(G.key){case"n":case"j":{x&&G.ctrlKey&&L(G);break}case"ArrowDown":{L(G);break}case"p":case"k":{x&&G.ctrlKey&&Y(G);break}case"ArrowUp":{Y(G);break}case"Home":{G.preventDefault(),D(0);break}case"End":{G.preventDefault(),X();break}case"Enter":{G.preventDefault();let K=z();if(K){let Q=new Event(FB);K.dispatchEvent(Q)}}}}},b.createElement("label",{"cmdk-label":"",htmlFor:I.inputId,id:I.labelId,style:yWt},u),AP(e,G=>b.createElement(y5e.Provider,{value:A},b.createElement(v5e.Provider,{value:I},G))))}),sWt=b.forwardRef((e,t)=>{var n,r;let i=Ui(),a=b.useRef(null),s=b.useContext(x5e),o=vk(),u=_5e(e),c=(r=(n=u.current)==null?void 0:n.forceMount)!=null?r:s?.forceMount;dg(()=>{if(!c)return o.item(i,s?.id)},[c]);let d=w5e(i,a,[e.value,e.children,a],e.keywords),f=OZ(),p=Kp(E=>E.value&&E.value===d.current),m=Kp(E=>c||o.filter()===!1?!0:E.search?E.filtered.items.get(i)>0:!0);b.useEffect(()=>{let E=a.current;if(!(!E||e.disabled))return E.addEventListener(FB,y),()=>E.removeEventListener(FB,y)},[m,e.onSelect,e.disabled]);function y(){var E,A;v(),(A=(E=u.current).onSelect)==null||A.call(E,d.current)}function v(){f.setState("value",d.current,!0)}if(!m)return null;let{disabled:x,value:_,onSelect:S,forceMount:w,keywords:T,...N}=e;return b.createElement(gh.div,{ref:Cc(a,t),...N,id:i,"cmdk-item":"",role:"option","aria-disabled":!!x,"aria-selected":!!p,"data-disabled":!!x,"data-selected":!!p,onPointerMove:x||o.getDisablePointerSelection()?void 0:v,onClick:x?void 0:y},e.children)}),oWt=b.forwardRef((e,t)=>{let{heading:n,children:r,forceMount:i,...a}=e,s=Ui(),o=b.useRef(null),u=b.useRef(null),c=Ui(),d=vk(),f=Kp(m=>i||d.filter()===!1?!0:m.search?m.filtered.groups.has(s):!0);dg(()=>d.group(s),[]),w5e(s,o,[e.value,e.heading,u]);let p=b.useMemo(()=>({id:s,forceMount:i}),[i]);return b.createElement(gh.div,{ref:Cc(o,t),...a,"cmdk-group":"",role:"presentation",hidden:f?void 0:!0},n&&b.createElement("div",{ref:u,"cmdk-group-heading":"","aria-hidden":!0,id:c},n),AP(e,m=>b.createElement("div",{"cmdk-group-items":"",role:"group","aria-labelledby":n?c:void 0},b.createElement(x5e.Provider,{value:p},m))))}),lWt=b.forwardRef((e,t)=>{let{alwaysRender:n,...r}=e,i=b.useRef(null),a=Kp(s=>!s.search);return!n&&!a?null:b.createElement(gh.div,{ref:Cc(i,t),...r,"cmdk-separator":"",role:"separator"})}),uWt=b.forwardRef((e,t)=>{let{onValueChange:n,...r}=e,i=e.value!=null,a=OZ(),s=Kp(c=>c.search),o=Kp(c=>c.selectedItemId),u=vk();return b.useEffect(()=>{e.value!=null&&a.setState("search",e.value)},[e.value]),b.createElement(gh.input,{ref:t,...r,"cmdk-input":"",autoComplete:"off",autoCorrect:"off",spellCheck:!1,"aria-autocomplete":"list",role:"combobox","aria-expanded":!0,"aria-controls":u.listId,"aria-labelledby":u.labelId,"aria-activedescendant":o,id:u.inputId,type:"text",value:i?e.value:s,onChange:c=>{i||a.setState("search",c.target.value),n?.(c.target.value)}})}),cWt=b.forwardRef((e,t)=>{let{children:n,label:r="Suggestions",...i}=e,a=b.useRef(null),s=b.useRef(null),o=Kp(c=>c.selectedItemId),u=vk();return b.useEffect(()=>{if(s.current&&a.current){let c=s.current,d=a.current,f,p=new ResizeObserver(()=>{f=requestAnimationFrame(()=>{let m=c.offsetHeight;d.style.setProperty("--cmdk-list-height",m.toFixed(1)+"px")})});return p.observe(c),()=>{cancelAnimationFrame(f),p.unobserve(c)}}},[]),b.createElement(gh.div,{ref:Cc(a,t),...i,"cmdk-list":"",role:"listbox",tabIndex:-1,"aria-activedescendant":o,"aria-label":r,id:u.listId},AP(e,c=>b.createElement("div",{ref:Cc(s,u.listInnerRef),"cmdk-list-sizer":""},c)))}),dWt=b.forwardRef((e,t)=>{let{open:n,onOpenChange:r,overlayClassName:i,contentClassName:a,container:s,...o}=e;return b.createElement(bO,{open:n,onOpenChange:r},b.createElement(_O,{container:s},b.createElement(wO,{"cmdk-overlay":"",className:i}),b.createElement(SO,{"aria-label":e.label,"cmdk-dialog":"",className:a},b.createElement(b5e,{ref:t,...o}))))}),fWt=b.forwardRef((e,t)=>Kp(n=>n.filtered.count===0)?b.createElement(gh.div,{ref:t,...e,"cmdk-empty":"",role:"presentation"}):null),pWt=b.forwardRef((e,t)=>{let{progress:n,children:r,label:i="Loading...",...a}=e;return b.createElement(gh.div,{ref:t,...a,"cmdk-loading":"",role:"progressbar","aria-valuenow":n,"aria-valuemin":0,"aria-valuemax":100,"aria-label":i},AP(e,s=>b.createElement("div",{"aria-hidden":!0},s)))}),yk=Object.assign(b5e,{List:cWt,Item:sWt,Input:uWt,Group:oWt,Separator:lWt,Dialog:dWt,Empty:fWt,Loading:pWt});function hWt(e,t){let n=e.nextElementSibling;for(;n;){if(n.matches(t))return n;n=n.nextElementSibling}}function mWt(e,t){let n=e.previousElementSibling;for(;n;){if(n.matches(t))return n;n=n.previousElementSibling}}function _5e(e){let t=b.useRef(e);return dg(()=>{t.current=e}),t}var dg=typeof window>"u"?b.useEffect:b.useLayoutEffect;function cv(e){let t=b.useRef();return t.current===void 0&&(t.current=e()),t}function Kp(e){let t=OZ(),n=()=>e(t.snapshot());return b.useSyncExternalStore(t.subscribe,n,n)}function w5e(e,t,n,r=[]){let i=b.useRef(),a=vk();return dg(()=>{var s;let o=(()=>{var c;for(let d of n){if(typeof d=="string")return d.trim();if(typeof d=="object"&&"current"in d)return d.current?(c=d.current.textContent)==null?void 0:c.trim():i.current}})(),u=r.map(c=>c.trim());a.value(e,o,u),(s=t.current)==null||s.setAttribute(uv,o),i.current=o}),i}var gWt=()=>{let[e,t]=b.useState(),n=cv(()=>new Map);return dg(()=>{n.current.forEach(r=>r()),n.current=new Map},[e]),(r,i)=>{n.current.set(r,i),t({})}};function vWt(e){let t=e.type;return typeof t=="function"?t(e.props):"render"in t?t.render(e.props):e}function AP({asChild:e,children:t},n){return e&&b.isValidElement(t)?b.cloneElement(vWt(t),{ref:t.ref},n(t.props.children)):n(t)}var yWt={position:"absolute",width:"1px",height:"1px",padding:"0",margin:"-1px",overflow:"hidden",clip:"rect(0, 0, 0, 0)",whiteSpace:"nowrap",borderWidth:"0"};function S5e({className:e,...t}){return l.jsx(yk,{"data-slot":"command",className:Ie("bg-popover text-popover-foreground flex h-full w-full flex-col overflow-hidden rounded-md",e),...t})}function k5e({className:e,...t}){return l.jsxs("div",{"data-slot":"command-input-wrapper",className:"flex h-9 items-center gap-2 border-b px-3",children:[l.jsx(Bq,{className:"size-4 shrink-0 opacity-50"}),l.jsx(yk.Input,{"data-slot":"command-input",className:Ie("placeholder:text-muted-foreground flex h-10 w-full rounded-md bg-transparent py-3 text-sm outline-hidden disabled:cursor-not-allowed disabled:opacity-50",e),...t})]})}function E5e({...e}){return l.jsx(yk.Empty,{"data-slot":"command-empty",className:"py-6 text-center text-sm",...e})}function T5e({className:e,...t}){return l.jsx(yk.Group,{"data-slot":"command-group",className:Ie("text-foreground [&_[cmdk-group-heading]]:text-muted-foreground overflow-hidden p-1 [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:py-1.5 [&_[cmdk-group-heading]]:text-xs [&_[cmdk-group-heading]]:font-medium",e),...t})}function N5e({className:e,...t}){return l.jsx(yk.Item,{"data-slot":"command-item",className:Ie("data-[selected=true]:bg-accent data-[selected=true]:text-accent-foreground [&_svg:not([class*='text-'])]:text-muted-foreground relative flex cursor-default items-center gap-2 rounded-sm px-2 py-1.5 text-sm outline-hidden select-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0 [&_svg:not([class*='size-'])]:size-4",e),...t})}function fme({items:e,placeholder:t="Select item...",searchPlaceholder:n="Search...",emptyMessage:r="No item found.",className:i,value:a,onValueChange:s}){const[o,u]=b.useState(!1),[c,d]=b.useState(""),f=a!==void 0?a:c,p=y=>{s?s(y):d(y)},m=()=>{if(f){const y=e.find(v=>v.value===f);return y?y.label:f}return t};return l.jsxs(qo,{open:o,onOpenChange:u,modal:!0,children:[l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"outline",role:"combobox","aria-expanded":o,className:Ie("w-[200px] justify-between bg-background",i),children:[l.jsx("span",{className:"truncate",children:m()}),l.jsx(Lq,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),l.jsx(Ho,{className:"w-96 p-0",align:"start",children:l.jsxs(S5e,{children:[l.jsx(k5e,{placeholder:n,className:"h-9"}),l.jsx(E5e,{children:r}),l.jsx(T5e,{className:"max-h-48 overflow-auto",children:e.map(y=>{const v=f===y.value;return l.jsxs(N5e,{value:y.value,onSelect:x=>{p(y.value),u(!1)},children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{children:y.label}),y.description&&l.jsx("span",{className:"text-xs text-muted-foreground",children:y.description})]}),l.jsx(xi,{className:Ie("ml-auto h-4 w-4",v?"opacity-100":"opacity-0")})]},y.value)})})]})})]})}function C5e({toolCalls:e,onChange:t,availableTools:n=[]}){const r=()=>{t([...e,{toolName:"",arguments:{}}])},i=y=>{t(e.filter((v,x)=>x!==y))},a=(y,v)=>{const x=[...e];x[y]={...x[y],toolName:v,arguments:{}},t(x)},s=(y,v)=>{const x=[...e],_=x[y].arguments||{};let S="arg";{let w=1;for(;_[S]!==void 0;)S=`arg${w}`,w++}x[y]={...x[y],arguments:{..._,[S]:""}},t(x)},o=(y,v)=>{const x=[...e],_={...x[y].arguments||{}};delete _[v],x[y]={...x[y],arguments:_},t(x)},u=(y,v,x)=>{if(!x||v===x)return;const _=[...e],S=_[y].arguments||{},T=Object.entries(S).map(([N,E])=>N===v?[x,E]:[N,E]);_[y]={..._[y],arguments:Object.fromEntries(T)},t(_)},c=(y,v,x)=>{const _=[...e],S={..._[y].arguments||{}};let w=x;if(x.trim()!=="")try{/^-?\d+\.?\d*$/.test(x)?w=parseFloat(x):x==="true"||x==="false"?w=x==="true":(x.startsWith("[")||x.startsWith("{"))&&(w=JSON.parse(x))}catch{w=x}S[v]=w,_[y]={..._[y],arguments:S},t(_)},d=(y,v)=>{const x=e[y],_=n.find(S=>S.name===x.toolName);return _?.inputSchema?.properties?_.inputSchema.properties[v]:null},f=y=>{const v=e[y],x=n.find(S=>S.name===v.toolName);if(!x?.inputSchema?.properties)return[];const _=x.inputSchema.properties;return Object.keys(_).map(S=>({key:S,schema:_[S]}))},p=y=>y==="",m=y=>!y||y.trim()==="";return l.jsxs("div",{className:"space-y-4",children:[e.map((y,v)=>l.jsxs("div",{className:"rounded-md border border-border/40 bg-muted/10 p-4 space-y-3",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsxs("div",{className:"flex-1",children:[l.jsx("label",{className:"text-xs font-medium text-muted-foreground mb-1 block",children:"Tool name"}),n.length>0?l.jsx(fme,{items:n.map(x=>({value:x.name,label:x.name,description:x.description})),value:y.toolName,onValueChange:x=>a(v,x),placeholder:"Select tool...",searchPlaceholder:"Search tools...",className:Ie("w-full justify-between font-mono text-sm h-9",m(y.toolName)&&"border-destructive focus-visible:ring-destructive")}):l.jsx(Ct,{value:y.toolName,onChange:x=>a(v,x.target.value),placeholder:"e.g. get_transactions",className:Ie("font-mono text-sm",m(y.toolName)&&"border-destructive focus-visible:ring-destructive")})]}),l.jsx(Ee,{variant:"ghost",size:"icon",onClick:()=>i(v),className:"mt-5 h-8 w-8 text-muted-foreground hover:text-destructive",children:l.jsx(Yn,{className:"h-4 w-4"})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-xs font-medium text-muted-foreground",children:"Arguments"}),l.jsx("div",{className:"space-y-2",children:Object.entries(y.arguments||{}).map(([x,_])=>{const S=d(v,x),w=f(v).filter(E=>!y.arguments.hasOwnProperty(E.key)||E.key===x),T=/^arg\d*$/.test(x)&&!f(v).some(E=>E.key===x),N=w.map(E=>{let A=E.schema?.description||"";return E.schema?.type&&(A+=A?` (Type: ${E.schema.type})`:`Type: ${E.schema.type}`),{value:E.key,label:E.key,description:A}});return l.jsxs("div",{className:"flex items-start gap-2",children:[l.jsxs("div",{className:"flex-1",children:[l.jsx(fme,{items:N,value:T?"":x,onValueChange:E=>u(v,x,E),placeholder:"Select argument...",searchPlaceholder:"Search arguments...",className:"w-full justify-between font-mono text-sm h-9"}),S?.description&&l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:S.description})]}),l.jsx("div",{className:"flex-[2]",children:l.jsx(So,{value:typeof _=="string"?_:JSON.stringify(_),onChange:E=>c(v,x,E.target.value),placeholder:S?.type?`${S.type}`:"Value",className:Ie("font-mono text-sm resize-none min-h-[36px]",p(_)&&"border-destructive focus-visible:ring-destructive"),rows:1})}),l.jsx(Ee,{variant:"ghost",size:"icon",onClick:()=>o(v,x),className:"h-8 w-8 text-muted-foreground hover:text-destructive",children:l.jsx(Yn,{className:"h-4 w-4"})})]},x)})}),y.toolName&&l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 text-xs",onClick:()=>s(v),children:[l.jsx(_o,{className:"h-3 w-3 mr-1"}),"Add argument"]})]})]},v)),l.jsxs(Ee,{variant:"outline",onClick:r,className:"w-full",children:[l.jsx(_o,{className:"h-4 w-4 mr-2"}),"Add expected tool call"]})]})}function xWt({iteration:e,testCase:t,loading:n=!1,onClear:r,serverNames:i=[]}){const a=e!==null,s=e?Fl(e):null,o=s==="passed",u=s==="failed",c=s==="pending",d=e?.testCaseSnapshot?.model||"Unknown",f=e?.startedAt??e?.createdAt,p=e?.updatedAt??e?.createdAt,m=f&&p?Math.max(p-f,0):null;return l.jsxs("div",{className:"h-full flex flex-col bg-muted/20",children:[a&&!n&&l.jsxs("div",{className:"flex items-center justify-between px-3 py-2 border-b",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[o&&l.jsx(ko,{className:"h-5 w-5",style:{color:cle.CHART_COLORS.PASSED}}),u&&l.jsx(qd,{className:"h-5 w-5",style:{color:cle.CHART_COLORS.FAILED}}),c&&l.jsx(Pn,{className:"h-5 w-5 animate-spin text-muted-foreground"}),l.jsxs("div",{className:"flex items-center gap-3 text-xs text-muted-foreground",children:[l.jsx("span",{className:"font-mono font-medium text-foreground",children:d}),l.jsxs("span",{children:[e.actualToolCalls?.length||0," tools"]}),l.jsxs("span",{children:[e.tokensUsed?.toLocaleString()||0," tokens"]}),m!==null&&l.jsx("span",{children:zPt(m)})]})]}),r&&l.jsx("button",{onClick:r,className:"text-xs text-muted-foreground hover:text-foreground transition-colors",children:"Clear"})]}),l.jsx("div",{className:"flex-1 overflow-hidden h-0",children:n?l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsxs("div",{className:"text-center",children:[l.jsx(Pn,{className:"h-6 w-6 animate-spin text-muted-foreground mx-auto mb-2"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Running test..."})]})}):a?l.jsx(Es,{className:"h-full",children:l.jsx("div",{className:"p-3",children:l.jsx(jZ,{iteration:e,testCase:t,serverNames:i})})}):l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Click Run to execute this test"})})})]})}const pme=(e,t)=>{if(t)return!0;if(e.length===0)return!1;for(const n of e){if(!n.toolName||n.toolName.trim()==="")return!1;if(n.arguments){for(const r of Object.values(n.arguments))if(r==="")return!1}}return!0},Nv=e=>e==null?null:Array.isArray(e)?e.map(t=>Nv(t)):typeof e=="object"?Object.keys(e).sort().reduce((t,n)=>(t[n]=Nv(e[n]),t),{}):e;function bWt({suiteId:e,selectedTestCaseId:t,connectedServerNames:n}){const{getAccessToken:r}=Aa(),{getToken:i,hasToken:a}=zx(),[s,o]=b.useState(null),[u,c]=b.useState(!1),[d,f]=b.useState([]),[p,m]=b.useState(""),[y,v]=b.useState(!1),[x,_]=b.useState(null),[S,w]=b.useState(null),T=Ua("testSuites:listTestCases",{suiteId:e}),N=_n("testSuites:updateTestCase"),E=b.useMemo(()=>T&&T.find(P=>P._id===t)||null,[T,t]),A=E?.lastMessageRun,I=Ua("testSuites:getTestIteration",A?{iterationId:A}:"skip");b.useEffect(()=>{w(null),_(null)},[t]),b.useEffect(()=>{I&&w(I)},[I]),b.useEffect(()=>{E&&o({title:E.title,query:E.query,runs:E.runs,expectedToolCalls:E.expectedToolCalls||[],isNegativeTest:E.isNegativeTest,scenario:E.scenario,expectedOutput:E.expectedOutput,advancedConfig:E.advancedConfig})},[t,E?._id]);const M=Ua("testSuites:getTestSuitesOverview",{}),$=b.useMemo(()=>M?M.find(P=>P.suite._id===e)?.suite:null,[M,e]),O=b.useMemo(()=>$?($.environment?.servers||[]).filter(V=>!n.has(V)):[],[$,n]),R=O.length===0;b.useEffect(()=>{async function P(){if(!$)return;const V=$.environment?.servers||[];if(V.length===0){f([]);return}try{const K=await Yt("/api/mcp/list-tools",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:V})});if(K.ok){const Q=await K.json();f(Q.tools||[])}}catch(K){console.error("Failed to fetch tools:",K)}}P()},[$]);const U=()=>{c(!0)},z=()=>{c(!1)},F=P=>{P.key==="Enter"?(P.preventDefault(),z()):P.key==="Escape"&&(s&&E&&o({...s,title:E.title}),c(!1))},D=b.useMemo(()=>{if(!s||!E)return!1;const P=JSON.stringify(Nv(s.expectedToolCalls||[])),V=JSON.stringify(Nv(E.expectedToolCalls||[])),K=JSON.stringify(Nv(s.advancedConfig||{})),Q=JSON.stringify(Nv(E.advancedConfig||{}));return s.title!==E.title||s.query!==E.query||s.runs!==E.runs||P!==V||K!==Q||(s.scenario||"")!==(E.scenario||"")||(s.expectedOutput||"")!==(E.expectedOutput||"")},[s,E]),W=b.useMemo(()=>s?pme(s.expectedToolCalls||[],E?.isNegativeTest):!0,[s,E?.isNegativeTest]),q=async()=>{if(!(!s||!E)){if(!pme(s.expectedToolCalls||[],E.isNegativeTest)){Pe.error("Cannot save: All tool names must be specified and argument values cannot be empty.");return}try{await N({testCaseId:E._id,title:s.title,query:s.query,runs:s.runs,expectedToolCalls:s.expectedToolCalls,scenario:s.scenario,expectedOutput:s.expectedOutput,advancedConfig:s.advancedConfig}),Pe.success("Changes saved")}catch(P){throw console.error("Failed to save:",P),Pe.error("Failed to save changes"),P}}},X=async()=>{if(!p||!E||!$)return;const[P,...V]=p.split("/"),K=V.join("/");if(!P||!K){Pe.error("Invalid model selection");return}if(!_r(K)){const Q=P.toLowerCase();if(!a(Q)){Pe.error(`Please add your ${P} API key in Settings before running this test`);return}}w(null),v(!0),Tr.capture("eval_test_case_run_started",{location:"test_template_editor",platform:Et(),environment:void 0,suite_id:e,test_case_id:E._id,model:p});try{const Q=await r(),oe=$.environment?.servers||[],re={};if(!_r(K)){const te=P.toLowerCase(),Z=i(te);Z&&(re[P]=Z)}const ee=await Yt("/api/mcp/evals/run-test-case",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({testCaseId:E._id,model:K,provider:P,serverIds:oe,modelApiKeys:Object.keys(re).length>0?re:void 0,convexAuthToken:Q,testCaseOverrides:s?{query:s.query,expectedToolCalls:s.expectedToolCalls,runs:s.runs}:void 0})});if(!ee.ok){const te=await ee.text();throw new Error(te||"Failed to run test case")}const le=await ee.json();if(le.iteration){w(le.iteration);const te=le.iteration,Z=te.startedAt??te.createdAt,ne=te.updatedAt??te.createdAt,J=Z&&ne?Math.max(ne-Z,0):0;Tr.capture("eval_test_case_run_completed",{location:"test_template_editor",platform:Et(),environment:void 0,suite_id:e,test_case_id:E._id,model:p,result:te.result||"unknown",duration_ms:J})}Pe.success("Test completed successfully!")}catch(Q){console.error("Failed to run test case:",Q),Pe.error(Q instanceof Error?Q.message:"Failed to run test case")}finally{v(!1)}},L=async()=>{if(E)try{await N({testCaseId:E._id,lastMessageRun:null}),w(null),Pe.success("Result cleared")}catch(P){console.error("Failed to clear result:",P),Pe.error("Failed to clear result")}},Y=async()=>{if(!E)return;const P=!E.isNegativeTest;_(P);try{await N({testCaseId:E._id,isNegativeTest:P,...P&&{expectedToolCalls:[]}}),_(null)}catch(V){console.error("Failed to toggle negative test:",V),Pe.error("Failed to update test type"),_(null)}},G=b.useMemo(()=>E?(E.models||[]).map(V=>({value:`${V.provider}/${V.model}`,label:V.model,provider:V.provider})):[],[E]);return b.useEffect(()=>{G.length>0&&!p&&m(G[0].value)},[G,p]),E?l.jsxs(Bc,{direction:"vertical",className:"h-full",children:[l.jsx(ta,{defaultSize:40,minSize:20,children:l.jsx("div",{className:"h-full overflow-auto",children:l.jsxs("div",{className:"p-2 space-y-2",children:[l.jsxs("div",{className:"flex items-center justify-between gap-4 px-1 pb-3 border-b",children:[l.jsx("div",{className:"flex-1 min-w-0",children:u?l.jsx("input",{type:"text",value:s?.title||"",onChange:P=>s&&o({...s,title:P.target.value}),onBlur:z,onKeyDown:F,autoFocus:!0,className:"px-0 py-0 text-lg font-semibold border-none focus:outline-none focus:ring-0 bg-transparent w-full"}):l.jsx("h2",{className:"text-lg font-semibold cursor-pointer hover:opacity-60 transition-opacity truncate",onClick:U,children:s?.title||E.title})}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsxs("div",{className:"flex items-center gap-1.5 shrink-0",children:[l.jsx(JO,{checked:x??E.isNegativeTest??!1,onCheckedChange:Y,className:"scale-75 data-[state=checked]:bg-orange-500"}),l.jsx("span",{className:`text-[10px] ${x??E.isNegativeTest?"text-orange-500":"text-muted-foreground"}`,children:"NEG"})]})}),l.jsx(zt,{children:l.jsx("p",{className:"text-xs",children:x??E.isNegativeTest?"Negative test: passes when no tools are called":"Click to mark as negative test"})})]}),l.jsxs("div",{className:"flex items-center gap-3 shrink-0",children:[l.jsxs(ju,{value:p,onValueChange:m,disabled:y||G.length===0,children:[l.jsx(Ru,{className:"h-9 text-xs border-0 bg-muted/50 hover:bg-muted transition-colors w-[180px]",children:l.jsx(Ou,{placeholder:"Select model"})}),l.jsx(Pu,{children:G.length===0?l.jsx("div",{className:"px-2 py-1.5 text-xs text-muted-foreground",children:"No models available"}):G.map(P=>l.jsx(Ea,{value:P.value,children:P.label},P.value))})]}),D&&l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsxs(Ee,{onClick:q,disabled:y||!W,variant:"outline",size:"sm",className:"h-9 px-4 text-xs font-medium",children:[l.jsx(vS,{className:"h-3.5 w-3.5 mr-2"}),"Save"]})})}),l.jsx(zt,{children:W?"Save changes to this test case":"All tool names must be specified and argument values cannot be empty"})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsx(Ee,{onClick:X,disabled:!p||y||!s?.query?.trim()||!R,size:"sm",className:"h-9 px-5 text-xs font-medium shadow-sm",children:y?l.jsxs(l.Fragment,{children:[l.jsx(Pn,{className:"h-3.5 w-3.5 animate-spin mr-2"}),"Running..."]}):l.jsxs(l.Fragment,{children:[l.jsx(Tx,{className:"h-3.5 w-3.5 mr-2 fill-current"}),"Run"]})})})}),l.jsx(zt,{children:R?p?s?.query?.trim()?"Run this test":"Enter a query to run":"Select a model to run":`Connect the following servers: ${O.join(", ")}`})]})]})]}),s?l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"px-1 pt-2",children:[l.jsx(Zn,{className:"text-xs text-muted-foreground font-medium",children:"Scenario"}),l.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:E?.isNegativeTest?"Describe the scenario where your app should not trigger":"Describe the use case to test"}),l.jsx(So,{value:s.scenario||"",onChange:P=>o({...s,scenario:P.target.value}),rows:2,placeholder:E?.isNegativeTest?"e.g., User asks about unrelated topic...":"e.g., Check current time display...",className:"text-sm resize-none border-0 bg-muted/30 focus-visible:bg-muted/50 transition-colors px-3 py-2"})]}),l.jsxs("div",{className:"px-1 pt-3",children:[l.jsx(Zn,{className:"text-xs text-muted-foreground font-medium",children:"User Prompt"}),l.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:E?.isNegativeTest?"Example prompt where your app should not trigger":"The exact prompt or interaction to begin the test"}),l.jsx(So,{value:s.query,onChange:P=>o({...s,query:P.target.value}),rows:4,placeholder:"Enter your test prompt here...",className:"font-mono text-sm resize-none border-0 bg-muted/30 focus-visible:bg-muted/50 transition-colors px-3 py-2.5"})]}),!E?.isNegativeTest&&l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"px-1 pt-3",children:[l.jsx(Zn,{className:"text-xs text-muted-foreground font-medium",children:"Tool Triggered"}),l.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"Which tools should be called?"}),l.jsx(C5e,{toolCalls:s.expectedToolCalls||[],onChange:P=>o({...s,expectedToolCalls:P}),availableTools:d})]}),l.jsxs("div",{className:"px-1 pt-3",children:[l.jsx(Zn,{className:"text-xs text-muted-foreground font-medium",children:"Expected Output"}),l.jsx("p",{className:"text-[10px] text-muted-foreground mb-1.5",children:"The output or experience we should expect to receive back from the MCP server"}),l.jsx(So,{value:s.expectedOutput||"",onChange:P=>o({...s,expectedOutput:P.target.value}),rows:2,placeholder:"e.g., Should return pokemon data with name, type, and stats...",className:"text-sm resize-none border-0 bg-muted/30 focus-visible:bg-muted/50 transition-colors px-3 py-2"})]})]})]}):l.jsx("div",{className:"py-8 text-center text-xs text-muted-foreground",children:"Loading..."})]})})}),l.jsx($u,{withHandle:!0}),l.jsx(ta,{defaultSize:60,minSize:20,maxSize:80,children:l.jsx(xWt,{iteration:S,testCase:E,loading:y,onClear:L,serverNames:($?.environment?.servers||[]).filter(P=>n.has(P))})})]}):l.jsx("div",{className:"flex items-center justify-center h-full",children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Loading test case..."})})}function A5e({minimumPassRate:e,onMinimumPassRateChange:t}){const[n,r]=b.useState(e.toString()),i=()=>{const s=Number(n);if(isNaN(s))r(e.toString());else{const o=Math.max(0,Math.min(100,s));t(o),r(o.toString())}},a=s=>{s.key==="Enter"?(i(),s.target.blur()):s.key==="Escape"&&(r(e.toString()),s.target.blur())};return l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Zn,{htmlFor:"pass-criteria",className:"text-sm text-muted-foreground",children:"Minimum accuracy:"}),l.jsx(Ct,{id:"pass-criteria",type:"number",min:0,max:100,value:n,onChange:s=>r(s.target.value),onBlur:i,onKeyDown:a,className:"w-16 text-center [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),l.jsx("span",{className:"text-sm text-muted-foreground",children:"%"})]})}function _Wt({suite:e,cases:t,allIterations:n,runs:r,runsViewMode:i,onViewModeChange:a,onTestCaseClick:s,runTrendData:o,modelStats:u,runsLoading:c,onRunClick:d}){const f=b.useMemo(()=>{const y=new Set(r.filter(v=>v.isActive===!1).map(v=>v._id));return t.map(v=>{const x=n.filter(I=>I.testCaseId===v._id&&(!I.suiteRunId||!y.has(I.suiteRunId))),_=x.map(I=>Fl(I)),S=_.filter(I=>I==="passed").length,w=_.filter(I=>I==="passed"||I==="failed").length,T=w>0?Math.round(S/w*100):0,N=x.filter(I=>I.startedAt&&I.updatedAt&&I.result!=="pending"),E=N.reduce((I,M)=>{const $=(M.updatedAt??0)-(M.startedAt??0);return I+$},0),A=N.length>0?E/N.length:0;return{testCase:v,iterations:w,avgAccuracy:T,avgDuration:A}})},[t,n,r]),p=y=>{if(y<1e3)return`${y}ms`;const v=Math.round(y/1e3);if(v<60)return`${v}s`;const x=Math.floor(v/60),_=v%60;return _?`${x}m ${_}s`:`${x}m`},m={passRate:{label:"Pass Rate",color:"var(--chart-1)"}};return l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Accuracy"})}),l.jsx("div",{className:"px-4 pb-4",children:l.jsx(IZ,{data:o,isLoading:c,height:"h-32",onClick:d})})]}),l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Performance by model"})}),l.jsx("div",{className:"px-4 pb-4",children:u.length>0?l.jsx(Ud,{config:m,className:"aspect-auto h-32 w-full",children:l.jsxs(Xv,{data:u,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"model",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:11},interval:0,height:40,tickFormatter:y=>y.length>15?y.substring(0,12)+"...":y}),l.jsx(Nu,{domain:[0,100],tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:y=>`${y}%`}),l.jsx(Fd,{cursor:!1,content:({active:y,payload:v})=>{if(!y||!v||v.length===0)return null;const x=v[0].payload;return l.jsx("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:l.jsxs("div",{className:"grid gap-2",children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"text-xs font-semibold",children:x.model}),l.jsxs("span",{className:"text-xs text-muted-foreground mt-0.5",children:[x.passed," passed · ",x.failed," failed"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"h-2 w-2 rounded-full",style:{backgroundColor:"var(--color-passRate)"}}),l.jsxs("span",{className:"text-sm font-semibold",children:[x.passRate,"%"]})]})]})})}}),l.jsx(Ml,{dataKey:"passRate",fill:"var(--color-passRate)",radius:[4,4,0,0],isAnimationActive:!1,minPointSize:8})]})}):l.jsx("p",{className:"text-xs text-muted-foreground",children:"No model data available."})})]})]}),l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground flex flex-col max-h-[600px]",children:[l.jsxs("div",{className:"border-b px-4 py-2 shrink-0 flex items-center justify-between",children:[l.jsx("div",{children:l.jsx("p",{className:"text-xs text-muted-foreground",children:"Click on a test case to view its run history and performance."})}),l.jsxs("select",{value:i,onChange:y=>a(y.target.value),className:"text-xs border rounded px-2 py-1 bg-background",children:[l.jsx("option",{value:"runs",children:"Runs"}),l.jsx("option",{value:"test-cases",children:"Test Cases"})]})]}),f.length>0&&l.jsxs("div",{className:"flex items-center gap-6 w-full px-4 py-1.5 bg-muted/30 border-b text-xs font-medium text-muted-foreground",children:[l.jsx("div",{className:"flex-1 min-w-[200px]",children:"Test Case Name"}),l.jsx("div",{className:"min-w-[100px] text-right",children:"Iterations"}),l.jsx("div",{className:"min-w-[100px] text-right",children:"Avg Accuracy"}),l.jsx("div",{className:"min-w-[100px] text-right",children:"Avg Duration"})]}),l.jsx("div",{className:"divide-y overflow-y-auto",children:f.length===0?l.jsx("div",{className:"px-4 py-12 text-center text-sm text-muted-foreground",children:"No test cases found."}):f.map(({testCase:y,iterations:v,avgAccuracy:x,avgDuration:_})=>l.jsxs("button",{onClick:()=>s(y._id),className:"flex items-center gap-6 w-full px-4 py-2.5 text-left transition-colors hover:bg-muted/50 focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60",children:[l.jsx("span",{className:"text-xs font-medium flex-1 min-w-[200px] truncate",children:y.title||"Untitled test case"}),l.jsx("span",{className:"min-w-[100px] text-right text-xs font-mono text-muted-foreground",children:v}),l.jsx("span",{className:"min-w-[100px] text-right text-xs font-mono text-muted-foreground",children:v>0?`${x}%`:"—"}),l.jsx("span",{className:"min-w-[100px] text-right text-xs font-mono text-muted-foreground",children:v>0?p(_):"—"})]},y._id))})]})]})}function wWt({testCase:e,iterations:t,runs:n,onBack:r,onViewRun:i,serverNames:a=[]}){const[s,o]=b.useState(null),u=b.useMemo(()=>{const p=new Set(n.filter(m=>m.isActive===!1).map(m=>m._id));return t.filter(m=>!m.suiteRunId||!p.has(m.suiteRunId))},[t,n]),c=b.useMemo(()=>{const p=new Map;u.forEach(y=>{y.suiteRunId&&(p.has(y.suiteRunId)||p.set(y.suiteRunId,[]),p.get(y.suiteRunId).push(y))});const m=[];return n.forEach(y=>{if(y.isActive===!1)return;const v=p.get(y._id);if(v&&v.length>0){const x=v.map(T=>Fl(T)),_=x.filter(T=>T==="passed").length,S=x.filter(T=>T==="passed"||T==="failed").length,w=S>0?Math.round(_/S*100):0;m.push({runId:y._id,runIdDisplay:y._id.slice(-6),passRate:w,label:new Date(y.completedAt??y.createdAt).toLocaleString()})}}),m.sort((y,v)=>{const x=n.find(T=>T._id===y.runId),_=n.find(T=>T._id===v.runId),S=x?.createdAt??0,w=_?.createdAt??0;return S-w})},[u,n]),d=b.useMemo(()=>{const p=new Map;return u.forEach(m=>{const y=m.testCaseSnapshot;if(!y)return;const v=Fl(m);if(v!=="passed"&&v!=="failed")return;const x=`${y.provider}/${y.model}`;p.has(x)||p.set(x,{provider:y.provider,model:y.model,passed:0,failed:0,total:0});const _=p.get(x);_.total+=1,v==="passed"?_.passed+=1:_.failed+=1}),Array.from(p.values()).map(m=>({model:`${m.provider}/${m.model}`,passRate:m.total>0?Math.round(m.passed/m.total*100):0,passed:m.passed,failed:m.failed})).sort((m,y)=>y.passRate-m.passRate)},[u]),f={passRate:{label:"Pass Rate",color:"var(--chart-1)"}};return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-lg font-semibold",children:e.title||"Untitled test case"}),e.query&&l.jsx("p",{className:"text-sm text-muted-foreground mt-0.5",children:e.query})]}),l.jsx(Ee,{variant:"ghost",size:"icon",onClick:r,children:l.jsx(Yn,{className:"h-4 w-4"})})]}),l.jsxs("div",{className:"grid gap-4 lg:grid-cols-2",children:[c.length>0&&l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Performance across runs"})}),l.jsx("div",{className:"px-4 pb-4",children:l.jsx(IZ,{data:c,height:"h-32",showLabel:!0,onClick:i})})]}),d.length>0&&l.jsxs("div",{className:"rounded-xl border bg-card text-card-foreground",children:[l.jsx("div",{className:"px-4 pt-3 pb-2",children:l.jsx("div",{className:"text-xs font-medium text-muted-foreground",children:"Performance by model"})}),l.jsx("div",{className:"px-4 pb-4",children:l.jsx(Ud,{config:f,className:"aspect-auto h-32 w-full",children:l.jsxs(Xv,{data:d,width:void 0,height:void 0,children:[l.jsx($p,{strokeDasharray:"3 3",vertical:!1,stroke:"hsl(var(--muted-foreground) / 0.2)"}),l.jsx(Tu,{dataKey:"model",tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:11},interval:0,height:40,tickFormatter:p=>{const m=p.split("/");return m.length===2&&m[1].length>15?`${m[0]}/${m[1].substring(0,12)}...`:p}}),l.jsx(Nu,{domain:[0,100],tickLine:!1,axisLine:!1,tickMargin:8,tick:{fontSize:12},tickFormatter:p=>`${p}%`}),l.jsx(Fd,{cursor:!1,content:({active:p,payload:m})=>{if(!p||!m||m.length===0)return null;const y=m[0].payload;return l.jsx("div",{className:"rounded-lg border bg-background p-2 shadow-sm",children:l.jsxs("div",{className:"grid gap-2",children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{className:"text-xs font-semibold",children:y.model}),l.jsxs("span",{className:"text-xs text-muted-foreground mt-0.5",children:[y.passed," passed · ",y.failed," failed"]})]}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("div",{className:"h-2 w-2 rounded-full",style:{backgroundColor:"var(--color-passRate)"}}),l.jsxs("span",{className:"text-sm font-semibold",children:[y.passRate,"%"]})]})]})})}}),l.jsx(Ml,{dataKey:"passRate",fill:"var(--color-passRate)",radius:[4,4,0,0],isAnimationActive:!1,minPointSize:8})]})})})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs font-medium text-muted-foreground",children:"Iterations"}),u.length===0?l.jsx("div",{className:"py-12 text-center text-sm text-muted-foreground",children:"No iterations found for this test."}):l.jsx("div",{className:"rounded-md border bg-card text-card-foreground divide-y overflow-hidden",children:u.map(p=>{const m=p.testCaseSnapshot,y=p.startedAt??p.createdAt,v=p.updatedAt??p.createdAt,x=y&&v?Math.max(v-y,0):null,_=p.actualToolCalls||[],S=p.result==="pending",w=s===p._id,T=N=>{if(N<1e3)return`${N}ms`;const E=Math.round(N/1e3);if(E<60)return`${E}s`;const A=Math.floor(E/60),I=E%60;return I?`${A}m ${I}s`:`${A}m`};return l.jsxs("div",{className:`relative ${S?"opacity-60":""}`,children:[l.jsx("div",{className:`absolute left-0 top-0 h-full w-1 ${SK(p.result)}`}),l.jsxs("button",{onClick:()=>o(w?null:p._id),className:"flex w-full items-center justify-between gap-3 px-3 py-2 text-left transition-colors focus:outline-none focus-visible:ring-2 focus-visible:ring-primary/60 cursor-pointer hover:bg-muted/50",children:[l.jsxs("div",{className:"flex min-w-0 flex-1 items-center gap-3 pl-2",children:[l.jsx("div",{className:"text-muted-foreground shrink-0",children:w?l.jsx(Wr,{className:"h-3.5 w-3.5"}):l.jsx(wr,{className:"h-3.5 w-3.5"})}),l.jsx("div",{className:"flex min-w-0 flex-1 items-center gap-2",children:l.jsx("span",{className:"text-xs font-medium capitalize",children:p.result})})]}),l.jsxs("div",{className:"flex items-center gap-4 text-xs text-muted-foreground shrink-0",children:[l.jsx("div",{className:"min-w-[120px] text-left truncate",children:l.jsx("span",{className:"font-mono text-xs",children:m?`${m.provider}/${m.model}`:"—"})}),l.jsx("div",{className:"min-w-[50px] text-center",children:l.jsx("span",{className:"font-mono",children:S?"—":_.length})}),l.jsx("div",{className:"min-w-[60px] text-center",children:l.jsx("span",{className:"font-mono",children:S?"—":Number(p.tokensUsed||0).toLocaleString()})}),l.jsx("div",{className:"font-mono min-w-[40px] text-right",children:S?"—":x!==null?T(x):"—"}),p.suiteRunId&&i&&!S&&l.jsx("div",{className:"min-w-[100px]",children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-5 text-[11px] px-2",onClick:N=>{N.stopPropagation(),i(p.suiteRunId)},children:["Run ",r2(p.suiteRunId)]})}),S&&l.jsx("div",{className:"w-3.5 flex items-center justify-center",children:l.jsx(Pn,{className:"h-3.5 w-3.5 animate-spin text-warning"})})]})]}),w&&l.jsx("div",{className:"border-t bg-muted/20 px-4 pb-4 pt-3 pl-8",children:l.jsx(jZ,{iteration:p,testCase:e,serverNames:a})})]},p._id)})})]})]})}function SWt(e,t,n,r,i,a){const s=b.useMemo(()=>new Set(i.filter(p=>p.isActive!==!1).map(p=>p._id)),[i]),o=b.useMemo(()=>{const p=a?.totals;if(!p)return{passRate:0,passed:0,failed:0,total:0,cancelled:0,pending:0};const m=p.passed+p.failed+p.cancelled+p.pending;return{passRate:m>0?Math.round(p.passed/m*100):0,passed:p.passed,failed:p.failed,total:m,cancelled:p.cancelled,pending:p.pending}},[a]),u=b.useMemo(()=>i.filter(y=>y.isActive!==!1).slice().reverse().map(y=>{const x=r.filter(T=>T.suiteRunId===y._id).map(T=>Fl(T)),_=x.filter(T=>T==="passed").length,S=x.filter(T=>T==="passed"||T==="failed").length;let w;if(S>0)w=Math.round(_/S*100);else if(y.summary)w=Math.round(y.summary.passRate*100);else return null;return{runId:y._id,runIdDisplay:r2(y._id),passRate:w,label:LPt(y.completedAt??y.createdAt)}}).filter(y=>y!==null),[i,r]),c=b.useMemo(()=>{const p=r.filter(v=>!v.suiteRunId||s.has(v.suiteRunId)),m=new Map;return p.forEach(v=>{const x=v.testCaseSnapshot?.model||"Unknown",_=v.testCaseSnapshot?.model||"Unknown Model",S=Fl(v);if(S!=="passed"&&S!=="failed")return;m.has(x)||m.set(x,{passed:0,failed:0,total:0,modelName:_});const w=m.get(x);w.total+=1,S==="passed"?w.passed+=1:w.failed+=1}),Array.from(m.entries()).map(([v,x])=>({model:x.modelName,passRate:x.total>0?Math.round(x.passed/x.total*100):0,passed:x.passed,failed:x.failed,total:x.total})).sort((v,x)=>v.model.localeCompare(x.model))},[r,s]),d=b.useMemo(()=>{const p=new Map;t.forEach(v=>{p.set(v._id,{testCase:v,iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}})});const m={testCase:null,iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}};n.forEach(v=>{if(v.testCaseId){const x=p.get(v.testCaseId);x?x.iterations.push(v):m.iterations.push(v)}else if(v.testCaseSnapshot){const x=`snapshot-${v.testCaseSnapshot.title}-${v.testCaseSnapshot.query}`;if(!p.has(x)){const _={_id:x,evalTestSuiteId:e._id,createdBy:v.createdBy||"",title:v.testCaseSnapshot.title,query:v.testCaseSnapshot.query,provider:v.testCaseSnapshot.provider,model:v.testCaseSnapshot.model,expectedToolCalls:v.testCaseSnapshot.expectedToolCalls};p.set(x,{testCase:_,iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}})}p.get(x).iterations.push(v)}else m.iterations.push(v)});const y=Array.from(p.values()).filter(v=>v.iterations.length>0).map(v=>{const x=[...v.iterations].sort((_,S)=>_.iterationNumber!=null&&S.iterationNumber!=null?_.iterationNumber-S.iterationNumber:(_.createdAt??0)-(S.createdAt??0));return{...v,iterations:x,summary:mD(x)}});if(m.iterations.length>0){const v=[...m.iterations].sort((x,_)=>x.iterationNumber!=null&&_.iterationNumber!=null?x.iterationNumber-_.iterationNumber:(x.createdAt??0)-(_.createdAt??0));y.push({...m,iterations:v,summary:mD(v)})}return y},[t,n,e._id]),f=b.useMemo(()=>{const p=new Map;return(e.config?.tests||[]).forEach(y=>{const v=y.title.replace(/\s*\[.*?\]\s*$/,"").trim(),x=`template:${v}-${y.query}`;if(p.has(x)||p.set(x,{title:v,query:y.query,testCaseIds:[],iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}}),y.testCaseId){const _=p.get(x);_.testCaseIds.includes(y.testCaseId)||_.testCaseIds.push(y.testCaseId)}}),d.forEach(y=>{if(!y.testCase)return;const v=UPt(y.testCase),x=y.testCase.title.replace(/\s*\[.*?\]\s*$/,"").trim(),_=`template:${x}-${y.testCase.query}`,S=p.has(_)?_:v;p.has(S)||p.set(S,{title:x,query:y.testCase.query,testCaseIds:[],iterations:[],summary:{runs:0,passed:0,failed:0,cancelled:0,pending:0,tokens:0,avgDuration:null}});const w=p.get(S);w.testCaseIds.includes(y.testCase._id)||w.testCaseIds.push(y.testCase._id),w.iterations.push(...y.iterations)}),Array.from(p.values()).map(y=>({...y,summary:mD(y.iterations)}))},[d,e.config?.tests]);return{activeRunIds:s,generalSummary:o,runTrendData:u,modelStats:c,caseGroups:d,templateGroups:f}}function kWt(e,t,n){const r=b.useMemo(()=>e?t.filter(s=>s.suiteRunId===e):[],[e,t]),i=b.useMemo(()=>e?[...r.map(u=>{const c=u.testCaseSnapshot;return{iteration:u,model:c?.model||"",provider:c?.provider||"",title:c?.title||"",query:c?.query||"",result:u.result}})].sort((u,c)=>{if(n==="model"){const d=`${u.provider}/${u.model}`,f=`${c.provider}/${c.model}`;if(d!==f)return d.localeCompare(f);if(u.title!==c.title)return u.title.localeCompare(c.title);const p=u.iteration.iterationNumber??0,m=c.iteration.iterationNumber??0;return p-m}else if(n==="test"){if(u.title!==c.title)return u.title.localeCompare(c.title);const d=`${u.provider}/${u.model}`,f=`${c.provider}/${c.model}`;if(d!==f)return d.localeCompare(f);const p=u.iteration.iterationNumber??0,m=c.iteration.iterationNumber??0;return p-m}else{const d={passed:0,failed:1,cancelled:2,pending:3},f=d[u.result]??4,p=d[c.result]??4;if(f!==p)return f-p;if(u.title!==c.title)return u.title.localeCompare(c.title);const m=`${u.provider}/${u.model}`,y=`${c.provider}/${c.model}`;return m.localeCompare(y)}}).map(u=>u.iteration):[],[e,r,n]),a=b.useMemo(()=>{if(!e||i.length===0)return{donutData:[],durationData:[],tokensData:[],modelData:[]};let s=0,o=0,u=0,c=0;const d=new Map;r.forEach(x=>{const _=x.testCaseSnapshot?.model||"Unknown",S=x.testCaseSnapshot?.model||"Unknown Model",w=Fl(x);if(w!=="passed"&&w!=="failed")return;d.has(_)||d.set(_,{passed:0,failed:0,total:0,modelName:S});const T=d.get(_);T.total+=1,w==="passed"?T.passed+=1:T.failed+=1});const f=Array.from(d.entries()).map(([x,_])=>({model:_.modelName,passRate:_.total>0?Math.round(_.passed/_.total*100):0,passed:_.passed,failed:_.failed,total:_.total})).sort((x,_)=>x.model.localeCompare(_.model)),p=new Map;i.forEach(x=>{const _=x.testCaseSnapshot?.title||"Unknown";p.has(_)||p.set(_,{title:_,durations:[],tokens:[],passed:0,failed:0,pending:0,cancelled:0});const S=p.get(_);x.result==="pending"?S.pending++:x.result==="cancelled"?S.cancelled++:MI(x)?S.passed++:S.failed++;const w=x.startedAt??x.createdAt,T=x.updatedAt??x.createdAt;w&&T&&x.result!=="pending"&&S.durations.push(Math.max(T-w,0)),x.result!=="pending"&&x.tokensUsed&&S.tokens.push(x.tokensUsed)}),p.forEach(x=>{s+=x.passed,o+=x.failed,u+=x.pending,c+=x.cancelled});const m=Array.from(p.values()).map(x=>{const _=x.durations.length>0?x.durations.reduce((S,w)=>S+w,0)/x.durations.length:0;return{name:x.title,duration:_,durationSeconds:_/1e3}}),y=Array.from(p.values()).map(x=>{const _=x.tokens.length>0?x.tokens.reduce((S,w)=>S+w,0)/x.tokens.length:0;return{name:x.title,tokens:_}}),v=[];return s>0&&v.push({name:"Passed",value:s,fill:"hsl(142.1 76.2% 36.3%)"}),o>0&&v.push({name:"Failed",value:o,fill:"hsl(0 84.2% 60.2%)"}),u>0&&v.push({name:"Pending",value:u,fill:"hsl(45.4 93.4% 47.5%)"}),c>0&&v.push({name:"Cancelled",value:c,fill:"hsl(240 3.7% 15.9%)"}),{donutData:v,durationData:m,tokensData:y,modelData:f}},[e,i,r]);return{iterationsForSelectedRun:r,caseGroupsForSelectedRun:i,selectedRunChartData:a}}function EWt({suite:e,cases:t,iterations:n,allIterations:r,runs:i,runsLoading:a,aggregate:s,onRerun:o,onCancelRun:u,onDelete:c,onDeleteRun:d,onDirectDeleteRun:f,connectedServerNames:p,rerunningSuiteId:m,cancellingRunId:y,deletingSuiteId:v,deletingRunId:x,availableModels:_,route:S}){const w=S.type==="suite-edit",T=S.type==="test-detail"||S.type==="test-edit"?S.testId:null,N=S.type==="run-detail"?S.runId:null,E=S.type==="run-detail"?"run-detail":S.type==="test-detail"?"test-detail":S.type==="test-edit"?"test-edit":"overview",A=S.type==="suite-overview"&&S.view==="test-cases"?"test-cases":"runs",[I,M]=b.useState(!1),[$,O]=b.useState("model"),[R,U]=b.useState(100),[z,F]=b.useState(e.description||""),[D,W]=b.useState(!1),q=_n("testSuites:updateTestSuite"),X=_n("testSuites:updateSuiteModels"),{runTrendData:L,modelStats:Y}=SWt(e,t,n,r,i,s),{caseGroupsForSelectedRun:G,selectedRunChartData:P}=kWt(N,r,$),V=b.useMemo(()=>N?i.find(Z=>Z._id===N)??null:null,[N,i]);b.useEffect(()=>{F(e.description||"")},[e.description]),b.useEffect(()=>{if(e.defaultPassCriteria?.minimumPassRate!==void 0){if(U(e.defaultPassCriteria.minimumPassRate),typeof window<"u")try{localStorage.setItem(`suite-${e._id}-criteria-rate`,String(e.defaultPassCriteria.minimumPassRate))}catch(te){console.warn("Failed to sync default pass criteria to localStorage",te)}}else if(typeof window<"u")try{const te=localStorage.getItem(`suite-${e._id}-criteria-rate`);te&&U(Number(te))}catch(te){console.warn("Failed to load default pass criteria",te)}},[e._id,e.defaultPassCriteria]);const K=b.useCallback(()=>{W(!0),F(e.description||"")},[e.description]),Q=b.useCallback(async()=>{if(W(!1),z!==e.description)try{await q({suiteId:e._id,description:z}),Pe.success("Suite description updated")}catch(te){Pe.error("Failed to update suite description"),console.error("Failed to update suite description:",te),F(e.description||"")}else F(e.description||"")},[z,e.description,e._id,q]),oe=b.useCallback(te=>{te.key==="Escape"&&(W(!1),F(e.description||""))},[e.description]),re=async te=>{try{await X({suiteId:e._id,models:te.map(Z=>({model:Z.model,provider:Z.provider}))}),Pe.success("Models updated successfully")}catch(Z){throw Pe.error("Failed to update models"),console.error("Failed to update models:",Z),Z}},ee=te=>{_s({type:"run-detail",suiteId:e._id,runId:te})},le=()=>{M(!1),_s({type:"suite-overview",suiteId:e._id})};return l.jsxs("div",{className:"flex flex-col h-full",children:[l.jsx("div",{className:"shrink-0",children:l.jsx(IGt,{suite:e,viewMode:E,selectedRunDetails:V,isEditMode:w,onRerun:o,onDelete:c,onCancelRun:u,onDeleteRun:d,onViewModeChange:le,connectedServerNames:p,rerunningSuiteId:m,cancellingRunId:y,deletingSuiteId:v,deletingRunId:x,showRunSummarySidebar:I,setShowRunSummarySidebar:M,runsViewMode:A,runs:i,allIterations:r,aggregate:s,testCases:t,availableModels:_,onUpdateModels:re})}),!w&&l.jsx("div",{className:"flex-1 min-h-0",children:E==="test-edit"&&T?l.jsx("div",{className:"h-full",children:l.jsx(bWt,{suiteId:e._id,selectedTestCaseId:T,connectedServerNames:p})}):E==="test-detail"&&T?(()=>{const te=t.find(ne=>ne._id===T);if(!te)return null;const Z=r.filter(ne=>ne.testCaseId===T);return l.jsx(wWt,{testCase:te,iterations:Z,runs:i,serverNames:(e.environment?.servers||[]).filter(ne=>p.has(ne)),onBack:()=>{_s({type:"suite-overview",suiteId:e._id,view:"test-cases"})},onViewRun:ne=>{_s({type:"run-detail",suiteId:e._id,runId:ne})}})})():E==="overview"?l.jsx("div",{className:"space-y-4",children:A==="runs"?l.jsx(jGt,{suite:e,runs:i,runsLoading:a,allIterations:r,runTrendData:L,modelStats:Y,onRunClick:ee,onDirectDeleteRun:f,runsViewMode:A,onViewModeChange:te=>{_s({type:"suite-overview",suiteId:e._id,view:te})}}):l.jsx(_Wt,{suite:e,cases:t,allIterations:r,runs:i,runsViewMode:A,onViewModeChange:te=>{_s({type:"suite-overview",suiteId:e._id,view:te})},onTestCaseClick:te=>{_s({type:"test-detail",suiteId:e._id,testId:te})},runTrendData:L,modelStats:Y,runsLoading:a,onRunClick:ee})},A):E==="run-detail"&&V?l.jsx(DGt,{selectedRunDetails:V,caseGroupsForSelectedRun:G,selectedRunChartData:P,runDetailSortBy:$,onSortChange:O,showRunSummarySidebar:I,setShowRunSummarySidebar:M,serverNames:(e.environment?.servers||[]).filter(te=>p.has(te))}):null}),w&&l.jsx("div",{className:"flex-1 min-h-0 overflow-auto",children:l.jsxs("div",{className:"p-6 max-w-5xl mx-auto space-y-8",children:[l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-base font-semibold text-foreground",children:"Description"}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Provide context about what this evaluation suite tests"})]}),D?l.jsx("textarea",{value:z,onChange:te=>F(te.target.value),onBlur:Q,onKeyDown:oe,placeholder:"Enter a description for this suite...",autoFocus:!0,className:"w-full px-4 py-3 text-sm border border-input rounded-lg focus:outline-none focus:ring-2 focus:ring-ring resize-none min-h-[100px] bg-background",rows:4}):l.jsx("button",{onClick:K,className:"w-full px-4 py-3 text-sm text-left rounded-lg border border-border hover:border-input hover:bg-accent/50 whitespace-pre-wrap transition-all",children:e.description?l.jsx("span",{className:"text-foreground leading-relaxed",children:e.description}):l.jsx("span",{className:"text-muted-foreground italic",children:"Click to add a description..."})})]}),l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{children:[l.jsx("h2",{className:"text-base font-semibold text-foreground",children:"Default Pass/Fail Criteria"}),l.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["Set the default criteria for ",l.jsx("strong",{children:"new"})," evaluation runs of this suite. Existing runs keep their original criteria."]})]}),l.jsx(A5e,{minimumPassRate:R,onMinimumPassRateChange:async te=>{U(te),localStorage.setItem(`suite-${e._id}-criteria-rate`,String(te));try{await q({suiteId:e._id,defaultPassCriteria:{minimumPassRate:te}}),Pe.success("Suite updated successfully")}catch(Z){Pe.error("Failed to update suite"),console.error("Failed to update suite:",Z),U(e.defaultPassCriteria?.minimumPassRate??100)}}})]}),l.jsx(zGt,{suite:e,testCases:t,onUpdate:re,availableModels:_})]})})]})}function TWt({server:e,selected:t,onToggle:n}){const[r,i]=b.useState(null),[a,s]=b.useState(!0),{label:o,Icon:u,iconClassName:c,indicatorColor:d}=B1e(e.connectionStatus),f=H1e(e.config),p=q1e(e.config),m=JSON.stringify(e.config,null,2),y=()=>{n(e.name)},v=S=>{(S.key==="Enter"||S.key===" ")&&(S.preventDefault(),y())},x=async(S,w,T)=>{S.stopPropagation();try{await navigator.clipboard.writeText(w),i(T),setTimeout(()=>i(null),2e3)}catch(N){console.error("Failed to copy text:",N)}},_=e.connectionStatus==="failed"?`${o} (${e.retryCount} retries)`:o;return l.jsx(vx,{role:"button",tabIndex:0,onClick:y,onKeyDown:v,className:Ie("border bg-card/50 backdrop-blur-sm hover:border-primary/50 hover:shadow-md hover:bg-card/70 transition-all duration-200 cursor-pointer relative",t?"border-primary/60 ring-2 ring-primary/30 shadow-lg":"border-border/50"),children:l.jsxs("div",{className:"p-4 space-y-3 py-0",children:[l.jsx("div",{className:"flex items-baseline justify-between",children:l.jsxs("div",{className:"flex items-baseline gap-3 flex-1",children:[l.jsx("div",{className:"h-2 w-2 rounded-full flex-shrink-0 mt-1",style:{backgroundColor:d}}),l.jsxs("div",{className:"min-w-0 flex-1",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h3",{className:"font-medium text-sm text-foreground",children:e.name}),l.jsxs("div",{className:"flex items-center gap-1 leading-none",children:[l.jsx(u,{className:c}),l.jsx("p",{className:"text-xs text-muted-foreground leading-none",children:_})]})]}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:f})]})]})}),l.jsxs("div",{className:"font-mono text-xs text-muted-foreground bg-muted/30 p-2 rounded border border-border/30 break-all relative group",onClick:S=>S.stopPropagation(),children:[l.jsx("div",{className:"pr-8",children:p}),l.jsx("button",{type:"button",onClick:S=>x(S,p,"command"),className:"absolute top-1 right-1 p-1 text-muted-foreground/50 hover:text-foreground transition-colors cursor-pointer",children:r==="command"?l.jsx(xi,{className:"h-3 w-3 text-success"}):l.jsx(Ca,{className:"h-3 w-3"})})]}),a&&l.jsxs("div",{className:"relative rounded border border-border/20 bg-muted/20 p-2 font-mono text-xs text-muted-foreground",onClick:S=>S.stopPropagation(),children:[l.jsx("pre",{className:"max-h-40 overflow-auto pr-8 whitespace-pre-wrap",children:m}),l.jsx("button",{type:"button",onClick:S=>x(S,m,"config"),className:"absolute top-1 right-1 p-1 text-muted-foreground/50 hover:text-foreground transition-colors cursor-pointer",children:r==="config"?l.jsx(xi,{className:"h-3 w-3 text-success"}):l.jsx(Ca,{className:"h-3 w-3"})})]}),l.jsx("div",{className:"flex justify-end pt-0.5",children:l.jsx("button",{type:"button",onClick:S=>{S.stopPropagation(),s(w=>!w)},"aria-label":a?"Hide config":"Show config",className:"rounded-full border border-border/50 bg-background/70 p-1 text-muted-foreground transition-colors hover:text-foreground cursor-pointer",children:a?l.jsx(Ex,{className:"h-3 w-3"}):l.jsx(Wr,{className:"h-3 w-3"})})})]})})}function NWt({connectedServers:e,selectedServers:t,onToggleServer:n}){return l.jsxs("div",{className:"space-y-4",children:[l.jsx("div",{className:"flex items-center justify-between",children:l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg pb-2",children:"Select servers to test"}),l.jsx("p",{className:"text-sm text-muted-foreground pb-2",children:"Choose at least one connected MCP server. You can evaluate multiple servers in the same run."})]})}),e.length>0?l.jsx("div",{className:"grid grid-cols-1 gap-3 lg:grid-cols-2 xl:grid-cols-3",children:e.map(([r,i])=>{const a=t.includes(r);return l.jsx(TWt,{server:i,selected:a,onToggle:n},r)})}):l.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:[l.jsx("p",{className:"font-medium text-foreground",children:"No connected servers yet"}),l.jsx("p",{className:"mt-2",children:"Launch a server from the Workspaces tab to make it available here. Once connected, it will appear instantly."}),l.jsx(Ee,{type:"button",variant:"outline",size:"sm",className:"mt-4",onClick:()=>{window.location.hash="servers"},children:"Go to Workspaces tab"})]})]})}function CWt({availableModels:e,selectedModels:t,modelTab:n,onModelTabChange:r,onToggleModel:i,hasProviderToken:a}){return l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg pb-2",children:"Choose evaluation models"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Select one or more models. Each test will run against all selected models."})]}),l.jsxs("div",{className:"flex items-center gap-1 rounded-lg border p-1 w-fit",children:[l.jsx("button",{type:"button",onClick:()=>r("mcpjam"),className:Ie("rounded-md px-4 py-2 text-sm font-medium transition-colors",n==="mcpjam"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"MCPJam Free Models"}),l.jsx("button",{type:"button",onClick:()=>r("yours"),className:Ie("rounded-md px-4 py-2 text-sm font-medium transition-colors",n==="yours"?"bg-primary text-primary-foreground shadow-sm":"text-muted-foreground hover:text-foreground"),children:"Your Providers"})]}),l.jsx("div",{className:"grid grid-cols-1 gap-3 lg:grid-cols-2 xl:grid-cols-3",children:e.filter(s=>n==="mcpjam"?_r(s.id):!_r(s.id)).map(s=>{const o=t.some(d=>d.id===s.id),c=!_r(s.id)&&!a(s.provider);return l.jsx("button",{type:"button",onClick:()=>i(s),className:Ie("rounded-xl border p-4 text-left transition-colors relative",o?"border-primary bg-primary/5":"hover:border-primary/40",c&&"opacity-60"),children:l.jsx("div",{className:"flex items-start justify-between gap-3",children:l.jsxs("div",{className:"flex-1",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("h4",{className:"font-semibold text-sm",children:s.name}),o&&l.jsx(xi,{className:"h-4 w-4 text-primary shrink-0"})]}),l.jsxs("p",{className:"text-xs text-muted-foreground mt-1",children:["by ",s.provider]}),c&&l.jsx("p",{className:"text-xs text-destructive mt-2",children:"Missing API key"})]})})},s.id)})}),t.length>0&&l.jsx("div",{className:"rounded-lg border bg-muted/30 p-3",children:l.jsxs("p",{className:"text-sm font-medium",children:[t.length," model",t.length===1?"":"s"," selected"]})})]})}function AWt({testTemplates:e,availableTools:t,canGenerateTests:n,hasServerAndModelSelection:r,isGenerating:i,isGeneratingNegativeTests:a,onGenerateTests:s,onGenerateNegativeTests:o,onAddTestTemplate:u,onAddNegativeTestTemplate:c,onRemoveTestTemplate:d,onUpdateTestTemplate:f}){const p=e.length>0&&e.some(S=>S.query.trim().length>0),m=(S,w)=>l.jsxs("div",{className:"space-y-3 rounded-lg border bg-background p-4",children:[l.jsxs("div",{className:"flex items-start justify-between gap-3",children:[l.jsxs("div",{className:"flex flex-col flex-1 space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Title"}),l.jsx(Ct,{className:"w-full",value:S.title,onChange:T=>f(w,"title",T.target.value),placeholder:"(Paypal) List transactions"})]}),e.length>1&&l.jsx(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(w),children:l.jsx(Yn,{className:"h-4 w-4"})})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Query"}),l.jsx(So,{value:S.query,onChange:T=>f(w,"query",T.target.value),placeholder:"Can you find the most recent Paypal transactions, then create an invoice?",rows:3})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Runs"}),l.jsx(Ct,{type:"number",min:1,value:S.runs,onChange:T=>f(w,"runs",Number(T.target.value)>0?Number(T.target.value):1)})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Expected tools"}),l.jsx(C5e,{toolCalls:S.expectedToolCalls,onChange:T=>f(w,"expectedToolCalls",T),availableTools:t})]})]},w),y=(S,w)=>l.jsxs("div",{className:"space-y-3 rounded-lg border border-orange-500/50 bg-orange-50/5 p-4",children:[l.jsxs("div",{className:"flex items-start justify-between gap-3",children:[l.jsx("div",{className:"flex items-center gap-2",children:l.jsxs(Cn,{variant:"outline",className:"bg-orange-500/10 text-orange-600 border-orange-500/30",children:[l.jsx(Lv,{className:"h-3 w-3 mr-1"}),"Negative Test"]})}),e.length>1&&l.jsx(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>d(w),children:l.jsx(Yn,{className:"h-4 w-4"})})]}),l.jsxs("div",{className:"flex flex-col flex-1 space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Title"}),l.jsx(Ct,{className:"w-full",value:S.title,onChange:T=>f(w,"title",T.target.value),placeholder:"Meta question about search"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Scenario"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"Describe why the AI should NOT trigger any tools for this prompt"}),l.jsx(So,{value:S.scenario||"",onChange:T=>f(w,"scenario",T.target.value),placeholder:"User is asking about how the search feature works, not performing a search",rows:2})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"User Prompt"}),l.jsx("p",{className:"text-xs text-muted-foreground mb-1",children:"The prompt that should NOT trigger any tools"}),l.jsx(So,{value:S.query,onChange:T=>f(w,"query",T.target.value),placeholder:"Can you explain what parameters the search tool accepts?",rows:3})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{className:"text-xs uppercase text-muted-foreground",children:"Runs"}),l.jsx(Ct,{type:"number",min:1,value:S.runs,onChange:T=>f(w,"runs",Number(T.target.value)>0?Number(T.target.value):1)})]})]},w),v=()=>l.jsxs("div",{className:"space-y-12",children:[e.map((S,w)=>S.isNegativeTest?y(S,w):m(S,w)),l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Ee,{type:"button",variant:"outline",onClick:u,"aria-label":"Add test case",className:"flex-1",children:[l.jsx(_o,{className:"h-4 w-4 mr-2"}),"Add test case"]}),l.jsxs(Ee,{type:"button",variant:"outline",onClick:c,"aria-label":"Add negative test case",className:"flex-1 border-orange-500/30 text-orange-600 hover:bg-orange-50/10",children:[l.jsx(Lv,{className:"h-4 w-4 mr-2"}),"Add negative test"]})]})]});if(!r&&!p)return l.jsxs("div",{className:"space-y-6",children:[l.jsx("div",{className:"flex items-start justify-between",children:l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg pb-2",children:"Define your test cases"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Specify tool names and their expected arguments. Leave arguments empty to skip argument checking."})]})}),l.jsxs("div",{className:"rounded-lg border border-dashed p-6 text-sm text-muted-foreground",children:[l.jsx("p",{className:"font-medium text-foreground",children:"Finish previous steps first"}),l.jsx("p",{className:"mt-2",children:"Select at least one server and choose a model to unlock test authoring. That ensures generated tests know which stack to target."})]})]});const _=i||a;return l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("h3",{className:"text-lg",children:"Define your test cases"}),l.jsx("p",{className:"text-sm text-muted-foreground mt-1",children:"Specify tool names and their expected arguments. Leave arguments empty to skip argument checking."})]}),n&&l.jsxs("div",{className:"flex gap-2",children:[l.jsxs(Ee,{type:"button",variant:"outline",onClick:s,disabled:_,children:[i?"Generating...":"Generate tests",l.jsx(D1e,{className:"h-4 w-4 ml-2"})]}),l.jsxs(Ee,{type:"button",variant:"outline",onClick:o,disabled:_,className:"border-orange-500/30 text-orange-600 hover:bg-orange-50/10",children:[a?"Generating...":"Generate negative tests",l.jsx(Lv,{className:"h-4 w-4 ml-2"})]})]})]}),_&&r?l.jsx("div",{className:"flex items-center justify-center rounded-lg border p-6",children:l.jsx("div",{className:"text-center text-sm text-muted-foreground",children:i?"Generating test cases...":"Generating negative test cases..."})}):v()]})}function IWt({suiteName:e,suiteDescription:t,minimumPassRate:n,selectedServers:r,selectedModels:i,validTestTemplates:a,onSuiteNameChange:s,onSuiteDescriptionChange:o,onMinimumPassRateChange:u,onEditStep:c,showNameError:d=!1}){return l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsxs(Zn,{htmlFor:"suite-name",className:"text-sm font-medium",children:["Test Suite Name ",l.jsx("span",{className:"text-destructive",children:"*"})]}),l.jsx(Ct,{id:"suite-name",type:"text",value:e,onChange:f=>s(f.target.value),placeholder:"e.g., Weather API Integration Tests",className:Ie("text-lg font-semibold",d&&!e.trim()&&"border-destructive focus-visible:ring-destructive"),autoFocus:!0}),d&&!e.trim()&&l.jsx("p",{className:"text-sm text-destructive font-medium",children:"Please provide a name for this test suite"})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx(Zn,{htmlFor:"suite-description",className:"text-sm font-medium",children:"Description (optional)"}),l.jsx(So,{id:"suite-description",value:t,onChange:f=>o(f.target.value),rows:3,placeholder:"What does this suite cover?",className:"resize-none"})]})]}),l.jsx(A5e,{minimumPassRate:n,onMinimumPassRateChange:u}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("h3",{className:"text-lg",children:"Review your configuration"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"After confirming the run, you will see your run begin in the eval results tab."})]}),l.jsxs("div",{className:"space-y-4 rounded-lg border bg-background p-4",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Servers"}),l.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:r.map(f=>l.jsx(Cn,{variant:"outline",children:f},f))})]}),l.jsx(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(0),children:"Edit"})]}),l.jsx(Ew,{}),l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Models"}),i.length>0?l.jsx("div",{className:"mt-2 flex flex-wrap gap-2",children:i.map(f=>l.jsx(Cn,{variant:"outline",children:f.name},f.id))}):l.jsx("p",{className:"mt-2 text-sm text-muted-foreground",children:"No models selected"})]}),l.jsx(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(1),children:"Edit"})]}),l.jsx(Ew,{}),l.jsxs("div",{className:"flex items-start justify-between gap-6",children:[l.jsxs("div",{className:"flex-1",children:[l.jsx("p",{className:"text-sm font-medium text-muted-foreground",children:"Test Templates"}),l.jsx("div",{className:"mt-3 space-y-3",children:a.map((f,p)=>l.jsxs("div",{className:Ie("rounded-md border p-3",f.isNegativeTest?"bg-orange-50/5 border-orange-500/30":"bg-muted/30"),children:[l.jsxs("div",{className:"flex items-center gap-2",children:[f.isNegativeTest&&l.jsxs(Cn,{variant:"outline",className:"bg-orange-500/10 text-orange-600 border-orange-500/30 text-xs",children:[l.jsx(Lv,{className:"h-3 w-3 mr-1"}),"Negative"]}),l.jsx("p",{className:"text-sm font-semibold text-foreground",children:f.title})]}),f.isNegativeTest&&f.scenario&&l.jsxs("p",{className:"mt-1 text-xs text-orange-600/80 italic",children:["Scenario: ",f.scenario]}),l.jsx("p",{className:"mt-1 line-clamp-2 text-sm text-muted-foreground",children:f.query}),f.expectedOutput&&l.jsxs("p",{className:"mt-1 text-xs text-muted-foreground/80 italic",children:["Expected: ",f.expectedOutput]}),l.jsxs("div",{className:"mt-2 flex flex-wrap items-center gap-3 text-xs text-muted-foreground",children:[l.jsxs("span",{children:[f.runs," run",f.runs===1?"":"s"]}),!f.isNegativeTest&&f.expectedToolCalls.length>0&&l.jsxs("span",{children:["Tools:"," ",f.expectedToolCalls.map(m=>m.toolName).join(", ")]}),f.isNegativeTest&&l.jsx("span",{className:"text-orange-600",children:"Expected: No tools triggered"})]})]},p))})]}),l.jsx(Ee,{type:"button",variant:"ghost",size:"sm",onClick:()=>c(2),children:"Edit"})]})]})]})}const _8=()=>({title:"",query:"",runs:wK.RUNS_PER_TEST,expectedToolCalls:[]}),jWt=()=>({title:"",query:"",runs:wK.RUNS_PER_TEST,expectedToolCalls:[],isNegativeTest:!0,scenario:""}),hme=e=>{if(e.length===0)return!1;for(const t of e){if(!t.toolName||t.toolName.trim()==="")return!1;if(t.arguments){for(const n of Object.values(t.arguments))if(n==="")return!1}}return!0};function OWt({availableModels:e,inline:t=!1,onSuccess:n,preselectedServer:r}){const[i,a]=b.useState(!1),[s,o]=b.useState(!1),[u,c]=b.useState(!1),[d,f]=b.useState(!1),p=r&&r!=="none",[m,y]=b.useState(p?1:0),[v,x]=b.useState(null),{isAuthenticated:_}=Ba(),{getAccessToken:S}=Aa(),w=Rx(),{getToken:T,hasToken:N}=zx(),[E,A]=b.useState(()=>p?[r]:[]),[I,M]=b.useState([]),[$,O]=b.useState([_8()]),[R,U]=b.useState("mcpjam"),[z,F]=b.useState(p?r:""),[D,W]=b.useState(""),[q,X]=b.useState(!1),[L,Y]=b.useState(!1),[G,P]=b.useState([]),[V,K]=b.useState(wK.MIN_PASS_RATE),Q=b.useMemo(()=>Object.entries(w.servers).filter(([,fe])=>fe.connectionStatus==="connected"),[w.servers]),oe=b.useMemo(()=>new Set(Q.map(([fe])=>fe)),[Q]);b.useEffect(()=>{if(!(typeof window>"u"))try{const fe=localStorage.getItem(ule.EVAL_RUNNER_PREFERENCES);if(!fe)return;const xe=JSON.parse(fe);x({servers:xe.servers??[],modelIds:xe.modelIds??[]}),xe.passCriteria&&xe.passCriteria.minimumPassRate!==void 0&&K(xe.passCriteria.minimumPassRate)}catch(fe){console.warn("Failed to load eval runner preferences",fe)}},[]),b.useEffect(()=>{if(v&&!p&&v.servers?.length){const fe=v.servers.filter(xe=>oe.has(xe));fe.length&&A(fe)}},[v,oe,p]),b.useEffect(()=>{if(!L&&e.length!==0){if(v?.modelIds&&v.modelIds.length>0){const fe=e.filter(xe=>v.modelIds.includes(xe.id));fe.length>0&&M(fe)}Y(!0)}},[e,v,L]),b.useEffect(()=>{if(!(typeof window>"u"))try{const fe={servers:E,modelIds:I.map(xe=>xe.id),passCriteria:{minimumPassRate:V}};localStorage.setItem(ule.EVAL_RUNNER_PREFERENCES,JSON.stringify(fe))}catch(fe){console.warn("Failed to persist eval runner preferences",fe)}},[E,I,V]),b.useEffect(()=>{async function fe(){if(E.length===0){P([]);return}try{const xe=await fetch(y1.LIST_TOOLS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:E})});if(xe.ok){const Ce=await xe.json();P(Ce.tools||[])}}catch(xe){console.error("Failed to fetch tools:",xe)}}fe()},[E]),b.useEffect(()=>{!t&&!i&&(y(p?1:0),Y(!1))},[t,i,p]);const re=b.useMemo(()=>$.filter(fe=>fe.query.trim().length>0),[$]),ee=b.useMemo(()=>{const fe=I.every(Ce=>_r(Ce.id)||N(Ce.provider)),xe=re.every(Ce=>Ce.isNegativeTest?Ce.query.trim().length>0&&(Ce.scenario?.trim().length??0)>0:hme(Ce.expectedToolCalls));return{servers:E.length>0,model:I.length>0&&fe,tests:re.length>0&&xe}},[E,I,re,N]),le=b.useMemo(()=>ee.servers?ee.model?ee.tests?3:2:1:0,[ee]),te=b.useMemo(()=>{switch(m){case 0:return ee.servers;case 1:return ee.model;case 2:return ee.tests;case 3:return ee.tests&&ee.servers&&ee.model;default:return!1}},[m,ee]),Z=fe=>{A(xe=>xe.includes(fe)?xe.filter(Ce=>Ce!==fe):[...xe,fe])},ne=fe=>{M(xe=>xe.some(He=>He.id===fe.id)?xe.filter(He=>He.id!==fe.id):[...xe,fe])},J=()=>{O(fe=>[...fe,_8()])},se=()=>{O(fe=>[...fe,jWt()])},ie=fe=>{O(xe=>xe.filter((Ce,He)=>He!==fe))},he=(fe,xe,Ce)=>{O(He=>{const Ze=[...He];return Ze[fe]={...Ze[fe],[xe]:Ce},Ze})},ye=async()=>{if(Tr.capture("eval_generate_tests_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),!_){Pe.error("Please sign in to generate tests");return}if(E.length===0){Pe.error("Please select at least one server");return}c(!0);try{const fe=await S(),xe=await fetch(y1.EVALS_GENERATE_TESTS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:E,convexAuthToken:fe})}),Ce=await xe.json();if(!xe.ok)throw new Error(Ce.error||"Failed to generate tests");if(Ce.tests&&Ce.tests.length>0){const He=Ce.tests.map((Ze,st)=>({title:Ze.title||`Generated test ${st+1}`,query:Ze.query||"",runs:Number(Ze.runs)>0?Number(Ze.runs):1,expectedToolCalls:Array.isArray(Ze.expectedToolCalls)?Ze.expectedToolCalls:[]}));O(He),y(2),Pe.success(`Generated ${He.length} test template(s).`)}}catch(fe){console.error("Failed to generate tests:",fe),Pe.error(fe instanceof Error?fe.message:"Failed to generate test cases")}finally{c(!1)}},Ne=async()=>{if(Tr.capture("eval_generate_negative_tests_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),!_){Pe.error("Please sign in to generate negative tests");return}if(E.length===0){Pe.error("Please select at least one server");return}f(!0);try{const fe=await S(),xe=await fetch(y1.EVALS_GENERATE_NEGATIVE_TESTS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:E,convexAuthToken:fe})}),Ce=await xe.json();if(!xe.ok)throw new Error(Ce.error||"Failed to generate negative tests");if(Ce.tests&&Ce.tests.length>0){const He=Ce.tests.map(Ze=>({title:Ze.title||"Untitled Negative Test",query:Ze.query||"",runs:Number(Ze.runs)>0?Number(Ze.runs):1,expectedToolCalls:[],isNegativeTest:!0,scenario:Ze.scenario||""}));O(Ze=>[...Ze,...He]),y(2),Pe.success(`Generated ${He.length} negative test template(s).`)}}catch(fe){console.error("Failed to generate negative tests:",fe),Pe.error(fe instanceof Error?fe.message:"Failed to generate negative test cases")}finally{f(!1)}},ce=()=>{m>=gl.length-1||te&&y(fe=>Math.min(fe+1,gl.length-1))},Te=()=>{m!==0&&y(fe=>Math.max(fe-1,0))},we=async()=>{if(!_){Pe.error("Please sign in to run evals");return}if(E.length===0){Pe.error("Please select at least one server"),y(0);return}if(I.length===0){Pe.error("Please select at least one model"),y(1);return}const fe={};for(const xe of I)if(!_r(xe.id)){const Ce=T(xe.provider);if(!Ce){Pe.error(`Please configure your ${xe.provider} API key in Settings`),y(1);return}fe[xe.provider]=Ce}if(re.length===0){Pe.error("Please add at least one test template with a query"),y(2);return}if(!z.trim()){X(!0);return}X(!1),t?n?.():(a(!1),window.location.hash="evals"),o(!0);try{const xe=await S(),Ce=re.flatMap(ot=>{const mt=crypto.randomUUID();return I.map(Bt=>({title:ot.title,query:ot.query,runs:ot.runs,model:Bt.id,provider:Bt.provider,expectedToolCalls:ot.expectedToolCalls,isNegativeTest:ot.isNegativeTest,scenario:ot.scenario,testTemplateKey:mt}))}),He=`Pass Criteria: Min ${V}% Accuracy`,Ze=await fetch(y1.EVALS_RUN,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({suiteName:z.trim(),suiteDescription:D.trim()||void 0,tests:Ce,serverIds:E,modelApiKeys:fe,convexAuthToken:xe,passCriteria:{minimumPassRate:V},notes:He})});if(!Ze.ok){let ot="Failed to start evals";try{ot=(await Ze.json()).error||ot}catch(mt){console.error("Failed to parse error response:",mt)}throw new Error(ot)}const st=await Ze.json();Pe.success(st.message||"Evals started successfully!"),Tr.capture("eval_suite_created",{location:"eval_runner",platform:Et(),environment:void 0,suite_id:st.suiteId,num_test_cases:re.length,num_models:I.length,num_servers:E.length}),O([_8()]),F(""),W(""),X(!1),y(3)}catch(xe){Pe.error(xe instanceof Error?xe.message:"Failed to start evals")}finally{o(!1)}},Oe=()=>{switch(gl[m].key){case"servers":return l.jsx(NWt,{connectedServers:Q,selectedServers:E,onToggleServer:Z});case"model":return l.jsx(CWt,{availableModels:e,selectedModels:I,modelTab:R,onModelTabChange:U,onToggleModel:ne,hasProviderToken:N});case"tests":return l.jsx(AWt,{testTemplates:$,availableTools:G,canGenerateTests:ee.servers&&ee.model,hasServerAndModelSelection:ee.servers&&ee.model,isGenerating:u,isGeneratingNegativeTests:d,onGenerateTests:ye,onGenerateNegativeTests:Ne,onAddTestTemplate:J,onAddNegativeTestTemplate:se,onRemoveTestTemplate:ie,onUpdateTestTemplate:he});case"review":return l.jsx(IWt,{suiteName:z,suiteDescription:D,minimumPassRate:V,selectedServers:E,selectedModels:I,validTestTemplates:re,onSuiteNameChange:F,onSuiteDescriptionChange:W,onMinimumPassRateChange:K,onEditStep:y,showNameError:q});default:return null}},Ue=l.jsx("ol",{className:"flex flex-col items-center gap-4 text-center md:flex-row md:gap-6",children:gl.map((fe,xe)=>{const Ce=m===xe,He=xe<m&&xe<=le,Ze=xe<=Math.max(le,m);return l.jsx("li",{className:"flex flex-col items-center gap-2",children:l.jsxs("button",{type:"button",onClick:()=>Ze?y(xe):void 0,disabled:!Ze,className:Ie("flex flex-col items-center gap-2 transition",!Ze&&"cursor-not-allowed opacity-60"),children:[l.jsx("span",{className:Ie("flex h-8 w-8 items-center justify-center rounded-full border text-sm font-medium",He&&"border-primary bg-primary text-primary-foreground",Ce&&!He&&"border-primary bg-primary/10 text-primary",!Ce&&!He&&"border-border text-muted-foreground"),children:xe+1}),l.jsx("span",{className:Ie("text-xs leading-tight",Ce?"text-foreground":"text-muted-foreground"),children:fe.title})]})},fe.key)})}),Me=m<gl.length-1?!te:s||!te,be=Me?"secondary":"default",je=()=>{if(!Me)return m===gl.length-1?"Start the eval run":"Continue to next step";if(m===2){const fe=re.some(Ce=>!Ce.isNegativeTest&&!hme(Ce.expectedToolCalls)),xe=re.some(Ce=>Ce.isNegativeTest&&(!Ce.scenario?.trim()||!Ce.query.trim()));if(fe)return"All tool names must be specified and argument values cannot be empty";if(xe)return"Negative tests require both a scenario description and user prompt"}return m===0?"Select at least one server to continue":m===1?"Select at least one model and ensure all models have API keys configured":m===2?"Add at least one test case with a query to continue":m===3?"Complete all required fields to start the eval run":"Complete the current step to continue"},Xe=()=>{t?n?.():a(!1)},ue=l.jsxs("div",{className:Ie("mx-auto flex w-full flex-col gap-8 pb-10 pt-4",t?"max-w-none px-4 sm:px-6 md:px-12 lg:px-32":"max-w-3xl px-4"),children:[l.jsxs("div",{className:"flex flex-wrap items-center gap-4",children:[t&&l.jsx(Ee,{type:"button",variant:"ghost",size:"icon",onClick:Xe,"aria-label":"Close",className:"h-8 w-8",children:l.jsx(Yn,{className:"h-4 w-4"})}),l.jsxs(Ee,{type:"button",variant:"outline",onClick:Te,disabled:m===0,"aria-label":"Back",className:"justify-center gap-2",children:[l.jsx(Dq,{className:"h-4 w-4"}),"Back"]}),l.jsx("div",{className:"flex flex-1 justify-center",children:l.jsx("div",{className:"max-w-xl",children:Ue})}),Me?l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsxs(Ee,{type:"button",variant:be,onClick:()=>{m<gl.length-1?(Tr.capture("eval_setup_next_step_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),ce()):(Tr.capture("eval_setup_start_eval_run_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),we())},disabled:Me,"aria-label":m===gl.length-1?"Start":"Next",className:Ie("justify-center gap-2",!Me&&"shadow-sm"),children:[m===gl.length-1?"Start":"Next",l.jsx(wr,{className:"h-4 w-4"})]})})}),l.jsx(zt,{children:je()})]}):l.jsxs(Ee,{type:"button",variant:be,onClick:()=>{m<gl.length-1?(Tr.capture("eval_setup_next_step_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),ce()):(Tr.capture("eval_setup_start_eval_run_button_clicked",{location:"eval_runner",platform:Et(),environment:void 0,step:m}),we())},disabled:Me,"aria-label":m===gl.length-1?"Start":"Next",className:Ie("justify-center gap-2",!Me&&"shadow-sm"),children:[m===gl.length-1?"Start":"Next",l.jsx(wr,{className:"h-4 w-4"})]})]}),l.jsx("div",{className:"space-y-6",children:Oe()})]});return t?ue:l.jsxs(si,{open:i,onOpenChange:a,children:[l.jsx(r2e,{asChild:!0,children:l.jsxs(Ee,{children:[l.jsx(_o,{className:"mr-2 h-4 w-4"}),"New eval run"]})}),l.jsxs(oi,{className:"max-h-[80vh] w-full max-w-4xl overflow-y-auto sm:max-w-4xl",children:[l.jsxs(vi,{className:"mx-auto w-full max-w-3xl gap-1 text-left",children:[l.jsx(yi,{children:"Create eval run"}),l.jsx(us,{children:"Follow the guided steps to configure your evaluation and run it with confidence."})]}),ue]})]})}function RWt({testCases:e,suiteId:t,selectedTestId:n,isLoading:r,onCreateTestCase:i,onDeleteTestCase:a,onDuplicateTestCase:s,onGenerateTests:o,deletingTestCaseId:u,duplicatingTestCaseId:c,isGeneratingTests:d,showingOverview:f,noServerSelected:p,selectedServer:m,suite:y,onRerun:v,rerunningSuiteId:x,connectedServerNames:_}){const w=(y?.environment?.servers||[]).filter(A=>!_?.has(A)),T=w.length===0&&y&&v,N=x===y?._id,E=()=>{t&&_s({type:"suite-overview",suiteId:t})};return p?l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"p-4 border-b",children:l.jsx("h2",{className:"text-sm font-semibold",children:"Test Cases"})}),l.jsx("div",{className:"flex-1 flex items-center justify-center p-4",children:l.jsx("p",{className:"text-xs text-muted-foreground text-center",children:"Select a server to view test cases."})})]}):l.jsxs(l.Fragment,{children:[l.jsxs("div",{className:"p-4 border-b flex items-center justify-between",children:[l.jsxs("h2",{className:"text-sm font-semibold",children:["Test Cases",m&&l.jsxs("span",{className:"text-muted-foreground font-normal",children:[" ","[",m,"]"]})]}),l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsx(Ee,{variant:"ghost",size:"sm",onClick:()=>{y&&v&&(Tr.capture("rerun_suite_button_clicked",{location:"test_case_list_sidebar",platform:Et(),environment:void 0}),v(y))},disabled:!T||N||e.length===0,className:"h-7 w-7 p-0",children:l.jsx(bU,{className:Ie("h-4 w-4",N&&"animate-spin")})})})}),l.jsx(zt,{children:e.length===0?"Add test cases first":!T&&w.length>0?`Connect the following servers: ${w.join(", ")}`:N?"Running...":"Run all tests"})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("span",{children:l.jsx(Ee,{variant:"ghost",size:"sm",onClick:()=>{o&&(Tr.capture("generate_tests_button_clicked",{location:"test_case_list_sidebar",platform:Et(),environment:void 0}),o())},disabled:d||!o,className:"h-7 w-7 p-0",children:l.jsx(D1e,{className:Ie("h-4 w-4",d&&"animate-pulse")})})})}),l.jsx(zt,{children:d?"Generating...":"Generate test cases with AI"})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:"ghost",size:"sm",onClick:()=>{Tr.capture("create_test_case_button_clicked",{location:"test_case_list_sidebar",platform:Et(),environment:void 0}),i()},className:"h-7 w-7 p-0",children:l.jsx(_o,{className:"h-4 w-4"})})}),l.jsx(zt,{children:"Create new test case"})]})]})]}),t&&l.jsxs("div",{onClick:E,className:Ie("flex items-center gap-2 px-4 py-2.5 text-sm cursor-pointer transition-colors border-b","hover:bg-accent/50",f&&"bg-accent font-medium"),children:[l.jsx(T1e,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("span",{children:"Results & Runs"})]}),l.jsx("div",{className:"flex-1 overflow-y-auto",children:r?l.jsx("div",{className:"p-4 text-center text-xs text-muted-foreground",children:"Loading test cases..."}):d?l.jsxs("div",{className:"p-4 flex flex-col items-center justify-center gap-2 text-xs text-muted-foreground",children:[l.jsx(Pn,{className:"h-5 w-5 animate-spin"}),l.jsx("span",{children:"Generating test cases..."})]}):e.length===0?l.jsx("div",{className:"p-4 text-center text-xs text-muted-foreground",children:"No test cases yet"}):l.jsx("div",{className:"py-2",children:e.map(A=>{const I=n===A._id,M=u===A._id,$=c===A._id;return l.jsxs("div",{onClick:()=>{t&&_s({type:"test-edit",suiteId:t,testId:A._id})},className:Ie("group w-full flex items-center gap-1 px-4 py-2 text-left text-sm hover:bg-accent/50 transition-colors cursor-pointer",I&&"bg-accent font-medium"),children:[l.jsxs("div",{className:"flex-1 min-w-0 text-left flex items-center gap-1.5",children:[l.jsx("span",{className:"truncate",children:A.title}),A.isNegativeTest&&l.jsx("span",{className:"text-[10px] text-orange-500 shrink-0",title:"Negative test",children:"NEG"})]}),l.jsxs(Ic,{children:[l.jsx(jc,{asChild:!0,children:l.jsx("button",{onClick:O=>O.stopPropagation(),className:"shrink-0 p-1 hover:bg-accent/50 rounded transition-colors opacity-0 group-hover:opacity-100","aria-label":"Test case options",children:l.jsx(A1e,{className:"h-4 w-4"})})}),l.jsxs(Oc,{align:"end",children:[l.jsxs(Oi,{onClick:O=>{O.stopPropagation(),s(A._id)},disabled:$,children:[l.jsx(Ca,{className:"h-4 w-4 mr-2 text-foreground"}),$?"Duplicating...":"Duplicate"]}),l.jsxs(Oi,{onClick:O=>{O.stopPropagation(),a(A._id,A.title)},disabled:M,variant:"destructive",children:[l.jsx(Ll,{className:"h-4 w-4 mr-2"}),M?"Deleting...":"Delete"]})]})]})]},A._id)})})})]})}const w8="skipDeleteTestCaseConfirmation";function PWt({suiteToDelete:e,setSuiteToDelete:t,deletingSuiteId:n,onConfirmDeleteSuite:r,runToDelete:i,setRunToDelete:a,deletingRunId:s,onConfirmDeleteRun:o,testCaseToDelete:u,setTestCaseToDelete:c,deletingTestCaseId:d,onConfirmDeleteTestCase:f}){const[p,m]=b.useState(!1);b.useEffect(()=>{u&&localStorage.getItem(w8)==="true"&&f()},[u,f]);const y=()=>{p&&localStorage.setItem(w8,"true"),f()},v=localStorage.getItem(w8)==="true";return l.jsxs(l.Fragment,{children:[l.jsx(si,{open:!!e,onOpenChange:x=>!x&&t(null),children:l.jsxs(oi,{children:[l.jsxs(vi,{children:[l.jsxs(yi,{className:"flex items-center gap-2",children:[l.jsx(wo,{className:"h-5 w-5 text-destructive"}),"Delete Test Suite"]}),l.jsxs(us,{children:["Are you sure you want to delete the test suite?",l.jsx("br",{}),l.jsx("br",{})]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:()=>t(null),disabled:!!n,children:"Cancel"}),l.jsx(Ee,{variant:"destructive",onClick:r,disabled:!!n,children:n?"Deleting...":"Delete Suite"})]})]})}),l.jsx(si,{open:!!i,onOpenChange:x=>!x&&a(null),children:l.jsxs(oi,{children:[l.jsxs(vi,{children:[l.jsxs(yi,{className:"flex items-center gap-2",children:[l.jsx(wo,{className:"h-5 w-5 text-destructive"}),"Delete Run"]}),l.jsxs(us,{children:["Are you sure you want to delete this run?",l.jsx("br",{}),l.jsx("br",{}),"This will permanently delete all iterations and results associated with this run. This action cannot be undone."]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:()=>a(null),disabled:!!s,children:"Cancel"}),l.jsx(Ee,{variant:"destructive",onClick:o,disabled:!!s,children:s?"Deleting...":"Delete Run"})]})]})}),!v&&l.jsx(si,{open:!!u,onOpenChange:x=>!x&&c(null),children:l.jsxs(oi,{children:[l.jsxs(vi,{children:[l.jsxs(yi,{className:"flex items-center gap-2",children:[l.jsx(wo,{className:"h-5 w-5 text-destructive"}),"Delete Test Case"]}),l.jsx(us,{children:"Are you sure you want to delete the test case?"})]}),l.jsxs(Js,{className:"flex-row items-center sm:justify-between",children:[l.jsxs("div",{className:"flex items-center space-x-2",children:[l.jsx(Hw,{id:"dont-show-delete-test-case",checked:p,onCheckedChange:x=>m(x===!0)}),l.jsx(Zn,{htmlFor:"dont-show-delete-test-case",className:"text-sm text-muted-foreground cursor-pointer",children:"Do not show this again"})]}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Ee,{variant:"outline",onClick:()=>c(null),disabled:!!d,children:"Cancel"}),l.jsx(Ee,{variant:"destructive",onClick:y,disabled:!!d,children:d?"Deleting...":"Delete Test Case"})]})]})]})})]})}function mme({isAuthenticated:e,user:t,selectedSuiteId:n,deletingSuiteId:r}){const i=e&&!!t,a=Ua("testSuites:getTestSuitesOverview",i?{}:"skip"),s=e&&!!t&&!!n&&r!==n,o=Ua("testSuites:getAllTestCasesAndIterationsBySuite",s?{suiteId:n}:"skip"),u=Ua("testSuites:listTestSuiteRuns",s?{suiteId:n,limit:20}:"skip"),c=a===void 0,d=s&&o===void 0,f=s&&u===void 0,p=b.useMemo(()=>!n||!a?null:a.find(S=>S.suite._id===n)??null,[n,a]),m=p?.suite??null,y=b.useMemo(()=>o?[...o.iterations].sort((S,w)=>(w.startedAt||w.createdAt)-(S.startedAt||S.createdAt)):[],[o]),v=b.useMemo(()=>u?[...u]:[],[u]),x=b.useMemo(()=>{if(!u||y.length===0)return y;const S=new Set(u.filter(w=>w.isActive!==!1).map(w=>w._id));return y.filter(w=>!w.suiteRunId||S.has(w.suiteRunId))},[y,u]),_=b.useMemo(()=>a?[...a].sort((S,w)=>{const T=S.suite.updatedAt??S.latestRun?.completedAt??S.latestRun?.createdAt??S.suite._creationTime??0;return(w.suite.updatedAt??w.latestRun?.completedAt??w.latestRun?.createdAt??w.suite._creationTime??0)-T}):[],[a]);return{suiteOverview:a,suiteDetails:o,suiteRuns:u,selectedSuiteEntry:p,selectedSuite:m,sortedIterations:y,runsForSelectedSuite:v,activeIterations:x,sortedSuites:_,isOverviewLoading:c,isSuiteDetailsLoading:d,isSuiteRunsLoading:f,enableOverviewQuery:i,enableSuiteDetailsQuery:s}}function $Wt(){const e=_n("testSuites:deleteTestSuite"),t=_n("testSuites:deleteTestSuiteRun"),n=_n("testSuites:cancelTestSuiteRun"),r=_n("testSuites:duplicateTestSuite"),i=_n("testSuites:createTestCase"),a=_n("testSuites:deleteTestCase"),s=_n("testSuites:duplicateTestCase"),o=_n("testSuites:createTestSuite");return{deleteSuiteMutation:e,deleteRunMutation:t,cancelRunMutation:n,duplicateSuiteMutation:r,createTestCaseMutation:i,deleteTestCaseMutation:a,duplicateTestCaseMutation:s,createTestSuiteMutation:o}}function MWt({mutations:e,selectedSuiteEntry:t,selectedSuiteId:n,selectedTestId:r}){const i=gve(),{getAccessToken:a}=Aa(),{getToken:s,hasToken:o}=zx(),[u,c]=b.useState(null),[d,f]=b.useState(null),[p,m]=b.useState(null),[y,v]=b.useState(null),[x,_]=b.useState(null),[S,w]=b.useState(null),[T,N]=b.useState(null),[E,A]=b.useState(!1),[I,M]=b.useState(null),[$,O]=b.useState(null),[R,U]=b.useState(null),[z,F]=b.useState(!1),D=b.useCallback(async le=>{try{return await i.query("testSuites:listTestCases",{suiteId:le})}catch(te){return console.error("Failed to fetch test cases:",te),[]}},[i]),W=b.useCallback(async le=>{if(u)return;const te=le.environment?.servers||[],Z=await D(le._id);if(!Z||Z.length===0){Pe.error("No test cases found in this suite");return}const ne=[];for(const ie of Z)if(!(!ie.models||ie.models.length===0))for(const he of ie.models)ne.push({title:ie.title,query:ie.query,runs:ie.runs||1,model:he.model,provider:he.provider,expectedToolCalls:ie.expectedToolCalls||[],isNegativeTest:ie.isNegativeTest,scenario:ie.scenario,advancedConfig:ie.advancedConfig,testCaseId:ie._id});if(ne.length===0){Pe.error("No tests to run. Please add models to your test cases.");return}const J={},se=new Set;for(const ie of ne)_r(ie.model)||se.add(ie.provider);for(const ie of se){const he=ie.toLowerCase();if(!o(he)){Pe.error(`Please add your ${ie} API key in Settings before running evals`);return}const ye=s(he);ye&&(J[ie]=ye)}c(le._id),Pe.success("Run started successfully! Results will appear shortly.");try{const ie=await a(),he=le.defaultPassCriteria?.minimumPassRate,ye=t?.latestRun,Ne=he??ye?.passCriteria?.minimumPassRate??100,ce=`Pass Criteria: Min ${Ne}% Accuracy`,Te=await Yt("/api/mcp/evals/run",{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({suiteId:le._id,suiteName:le.name,suiteDescription:le.description,tests:ne.map(we=>({title:we.title,query:we.query,runs:we.runs??1,model:we.model,provider:we.provider,expectedToolCalls:we.expectedToolCalls,isNegativeTest:we.isNegativeTest,scenario:we.scenario,advancedConfig:we.advancedConfig})),serverIds:te,modelApiKeys:Object.keys(J).length>0?J:void 0,convexAuthToken:ie,passCriteria:{minimumPassRate:Ne},notes:ce})});if(!Te.ok){const we=await Te.text();throw new Error(we||"Failed to start eval run")}Tr.capture("eval_suite_run_started",{location:"evals_tab",platform:Et(),environment:void 0,suite_id:le._id,num_test_cases:Z.length,num_tests:ne.length,num_models:se.size,minimum_pass_rate:Ne}),Pe.success("Eval run completed!")}catch(ie){console.error("Failed to rerun evals:",ie),Pe.error(ie instanceof Error?ie.message:"Failed to start eval run")}finally{c(null)}},[u,t,a,o,s,D]),q=b.useCallback(le=>{p||v(le)},[p]),X=b.useCallback(async()=>{if(!(!y||p)){m(y._id);try{await e.deleteSuiteMutation({suiteId:y._id}),Pe.success("Test suite deleted successfully"),n===y._id&&_s({type:"list"}),v(null)}catch(le){console.error("Failed to delete suite:",le),Pe.error(le instanceof Error?le.message:"Failed to delete test suite")}finally{m(null)}}},[y,p,e.deleteSuiteMutation,n]),L=b.useCallback(async le=>{if(!x){_(le._id);try{const te=await e.duplicateSuiteMutation({suiteId:le._id});Pe.success("Test suite duplicated successfully"),te&&te._id&&Tr.capture("eval_suite_duplicated",{location:"evals_tab",platform:Et(),environment:void 0,original_suite_id:le._id,new_suite_id:te._id}),te&&te._id&&_s({type:"suite-overview",suiteId:te._id})}catch(te){console.error("Failed to duplicate suite:",te),Pe.error(te instanceof Error?te.message:"Failed to duplicate test suite")}finally{_(null)}}},[x,e.duplicateSuiteMutation]),Y=b.useCallback(async le=>{if(!d){f(le);try{await e.cancelRunMutation({runId:le}),Pe.success("Run cancelled successfully")}catch(te){console.error("Failed to cancel run:",te),Pe.error(te instanceof Error?te.message:"Failed to cancel run")}finally{f(null)}}},[d,e.cancelRunMutation]),G=b.useCallback(le=>{S||N(le)},[S]),P=b.useCallback(async le=>{try{await e.deleteRunMutation({runId:le})}catch(te){throw console.error("Failed to delete run:",te),te}},[e.deleteRunMutation]),V=b.useCallback(async()=>{if(!(!T||S)){w(T);try{await e.deleteRunMutation({runId:T}),Pe.success("Run deleted successfully"),N(null)}catch(le){console.error("Failed to delete run:",le),Pe.error(le instanceof Error?le.message:"Failed to delete run")}finally{w(null)}}},[T,S,e.deleteRunMutation]),K=b.useCallback(async le=>{if(!E){A(!0);try{const te=await i.query("testSuites:listTestCases",{suiteId:le});let Z=[];if(te&&Array.isArray(te)&&te.length>0){const J=new Map;for(const se of te)if(se.models&&Array.isArray(se.models)){for(const ie of se.models)if(ie.model&&ie.provider){const he=`${ie.provider}:${ie.model}`;J.has(he)||J.set(he,{model:ie.model,provider:ie.provider})}}Z=Array.from(J.values())}Z.length===0&&(Z=[{model:"anthropic/claude-haiku-4.5",provider:"anthropic"}]);const ne=await e.createTestCaseMutation({suiteId:le,title:"Untitled test case",query:"",models:Z});return Pe.success("Test case created"),Tr.capture("eval_test_case_created",{location:"evals_tab",platform:Et(),environment:void 0,suite_id:le,test_case_id:ne,num_models:Z.length}),_s({type:"test-detail",suiteId:le,testId:ne}),ne}catch(te){return console.error("Failed to create test case:",te),Pe.error(te instanceof Error?te.message:"Failed to create test case"),null}finally{A(!1)}}},[E,e.createTestCaseMutation,i]),Q=b.useCallback((le,te)=>{I||U({id:le,title:te})},[I]),oe=b.useCallback(async()=>{if(!(!R||I)){M(R.id);try{await e.deleteTestCaseMutation({testCaseId:R.id}),Pe.success("Test case deleted successfully"),r===R.id&&n&&_s({type:"suite-overview",suiteId:n}),U(null)}catch(le){console.error("Failed to delete test case:",le),Pe.error(le instanceof Error?le.message:"Failed to delete test case")}finally{M(null)}}},[R,I,e.deleteTestCaseMutation,r,n]),re=b.useCallback(async(le,te)=>{if(!$){O(le);try{const Z=await e.duplicateTestCaseMutation({testCaseId:le});return Pe.success("Test case duplicated successfully"),Z&&Z._id&&Tr.capture("eval_test_case_duplicated",{location:"evals_tab",platform:Et(),environment:void 0,suite_id:te,original_test_case_id:le,new_test_case_id:Z._id}),Z&&Z._id&&_s({type:"test-edit",suiteId:te,testId:Z._id}),Z}catch(Z){return console.error("Failed to duplicate test case:",Z),Pe.error(Z instanceof Error?Z.message:"Failed to duplicate test case"),null}finally{O(null)}}},[$,e.duplicateTestCaseMutation]),ee=b.useCallback(async(le,te)=>{if(!z){F(!0);try{const Z=await a(),ne=await i.query("testSuites:listTestCases",{suiteId:le});let J=[];if(ne&&Array.isArray(ne)&&ne.length>0){const ye=new Map;for(const Ne of ne)if(Ne.models&&Array.isArray(Ne.models)){for(const ce of Ne.models)if(ce.model&&ce.provider){const Te=`${ce.provider}:${ce.model}`;ye.has(Te)||ye.set(Te,{model:ce.model,provider:ce.provider})}}J=Array.from(ye.values())}J.length===0&&(J=[{model:"anthropic/claude-haiku-4.5",provider:"anthropic"}]);const se=await Yt(y1.EVALS_GENERATE_TESTS,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({serverIds:te,convexAuthToken:Z})}),ie=await se.json();if(!se.ok)throw new Error(ie.error||"Failed to generate tests");if(!ie.tests||ie.tests.length===0){Pe.info("No test cases were generated");return}let he=0;for(const ye of ie.tests)try{await e.createTestCaseMutation({suiteId:le,title:ye.title||"Generated test",query:ye.query||"",models:J,expectedToolCalls:ye.expectedToolCalls||[],runs:ye.runs||1,isNegativeTest:ye.isNegativeTest||!1,scenario:ye.scenario,expectedOutput:ye.expectedOutput}),he++}catch(Ne){console.error("Failed to create test case:",Ne)}he>0&&(Pe.success(`Generated ${he} test case${he>1?"s":""}`),Tr.capture("eval_tests_generated_from_sidebar",{location:"test_case_list_sidebar",platform:Et(),environment:void 0,suite_id:le,generated_count:he}))}catch(Z){console.error("Failed to generate tests:",Z),Pe.error(Z instanceof Error?Z.message:"Failed to generate test cases")}finally{F(!1)}}},[z,a,i,e.createTestCaseMutation]);return{handleRerun:W,handleDelete:q,confirmDelete:X,handleDuplicateSuite:L,handleCancelRun:Y,handleDeleteRun:G,directDeleteRun:P,confirmDeleteRun:V,handleCreateTestCase:K,handleDeleteTestCase:Q,confirmDeleteTestCase:oe,handleDuplicateTestCase:re,handleGenerateTests:ee,rerunningSuiteId:u,cancellingRunId:d,deletingSuiteId:p,suiteToDelete:y,setSuiteToDelete:v,duplicatingSuiteId:x,deletingRunId:S,runToDelete:T,setRunToDelete:N,isCreatingTestCase:E,deletingTestCaseId:I,duplicatingTestCaseId:$,testCaseToDelete:R,setTestCaseToDelete:U,isGeneratingTests:z}}function DWt({selectedServer:e}){const{isAuthenticated:t,isLoading:n}=Ba(),{user:r}=Aa(),i=OPt(),a=i.type==="test-detail"||i.type==="test-edit"?i.testId:null,s=i.type==="test-edit"?i.testId:null,{availableModels:o}=PPt({systemPrompt:"",temperature:1,selectedServers:[]}),u=Rx(),c=b.useMemo(()=>new Set(Object.entries(u.servers).filter(([,D])=>D.connectionStatus==="connected").map(([D])=>D)),[u.servers]),d=$Wt(),f=mme({isAuthenticated:t,user:r,selectedSuiteId:null,deletingSuiteId:null}),p=e&&e!=="none"&&u.servers[e]?.connectionStatus==="connected",m=b.useMemo(()=>p?f.sortedSuites.find(D=>D.suite.environment?.servers?.[0]===e):null,[f.sortedSuites,e,p]),y=m?.suite??null,v=y?._id??null,x=MWt({mutations:d,selectedSuiteEntry:m??null,selectedSuiteId:v,selectedTestId:a}),_=mme({isAuthenticated:t,user:r,selectedSuiteId:v,deletingSuiteId:x.deletingSuiteId}),{selectedSuite:S,suiteDetails:w,sortedIterations:T,runsForSelectedSuite:N,activeIterations:E,isOverviewLoading:A,isSuiteDetailsLoading:I,isSuiteRunsLoading:M,enableOverviewQuery:$}=_;b.useEffect(()=>{Tr.capture("evals_tab_viewed",{location:"evals_tab",platform:Et(),environment:void 0})},[]);const O=b.useMemo(()=>!S||!w?null:FPt(S,w.testCases,E),[S,w,E]),R=b.useCallback(D=>{_s(D?{type:"suite-overview",suiteId:D}:{type:"list"})},[]),U=b.useCallback(async()=>{let D=v;if(!D&&e&&p)try{D=(await d.createTestSuiteMutation({name:e,description:`Test suite for ${e}`,environment:{servers:[e]}}))?._id}catch(W){console.error("Failed to create suite:",W),Pe.error("Failed to create test case. Please try again.");return}D&&await x.handleCreateTestCase(D)},[v,e,p,d.createTestSuiteMutation,x.handleCreateTestCase]),z=b.useCallback(D=>{v&&x.handleDuplicateTestCase(D,v)},[v,x.handleDuplicateTestCase]),F=b.useCallback(async()=>{if(!e||!p)return;let D=v;if(!D)try{D=(await d.createTestSuiteMutation({name:e,description:`Test suite for ${e}`,environment:{servers:[e]}}))?._id}catch(W){console.error("Failed to create suite:",W),Pe.error("Failed to generate tests. Please try again.");return}D&&await x.handleGenerateTests(D,[e])},[v,e,p,d.createTestSuiteMutation,x.handleGenerateTests]);return n?l.jsx("div",{className:"p-6",children:l.jsx("div",{className:"flex min-h-[calc(100vh-200px)] items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading..."})]})})}):!t||!r?l.jsx("div",{className:"p-6",children:l.jsx(Rc,{icon:T1,title:"Sign in to use evals",description:"Create an account or sign in to run evaluations and view results.",className:"h-[calc(100vh-200px)]"})}):A&&$&&i.type!=="create"?l.jsx("div",{className:"p-6",children:l.jsx("div",{className:"flex min-h-[calc(100vh-200px)] items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading your eval data..."})]})})}):l.jsxs("div",{className:"h-full flex flex-col overflow-hidden",children:[i.type==="create"?l.jsx("div",{className:"flex-1 overflow-y-auto px-6 pb-6 pt-6",children:l.jsx(OWt,{availableModels:o,inline:!0,onSuccess:R,preselectedServer:e})}):l.jsxs(Bc,{direction:"horizontal",className:"flex-1 overflow-hidden",children:[l.jsx(ta,{defaultSize:30,minSize:15,maxSize:40,className:"border-r bg-muted/30 flex flex-col",children:l.jsx(RWt,{testCases:w?.testCases||[],suiteId:v,selectedTestId:s,isLoading:I,onCreateTestCase:U,onDeleteTestCase:x.handleDeleteTestCase,onDuplicateTestCase:z,onGenerateTests:F,deletingTestCaseId:x.deletingTestCaseId,duplicatingTestCaseId:x.duplicatingTestCaseId,isGeneratingTests:x.isGeneratingTests,showingOverview:!s&&v!==null,noServerSelected:!p,selectedServer:e,suite:S,onRerun:x.handleRerun,rerunningSuiteId:x.rerunningSuiteId,connectedServerNames:c})}),l.jsx($u,{withHandle:!0}),l.jsx(ta,{defaultSize:70,className:"flex flex-col overflow-hidden",children:p?y?I?l.jsx("div",{className:"flex h-full items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading test cases..."})]})}):S?l.jsx("div",{className:"flex-1 overflow-y-auto px-6 pb-6 pt-6",children:l.jsx(EWt,{suite:S,cases:w?.testCases||[],iterations:E,allIterations:T,runs:N,runsLoading:M,aggregate:O,onRerun:x.handleRerun,onCancelRun:x.handleCancelRun,onDelete:x.handleDelete,onDeleteRun:x.handleDeleteRun,onDirectDeleteRun:x.directDeleteRun,connectedServerNames:c,rerunningSuiteId:x.rerunningSuiteId,cancellingRunId:x.cancellingRunId,deletingSuiteId:x.deletingSuiteId,deletingRunId:x.deletingRunId,availableModels:o,route:i})}):null:l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsxs("div",{className:"text-center max-w-md mx-auto p-8",children:[l.jsx("div",{className:"w-20 h-20 bg-muted rounded-full flex items-center justify-center mx-auto mb-6",children:l.jsx(T1,{className:"h-10 w-10 text-muted-foreground"})}),l.jsx("h2",{className:"text-2xl font-semibold text-foreground mb-2",children:"No test cases yet"}),l.jsxs("p",{className:"text-sm text-muted-foreground mb-6",children:['Create your first test case for "',e,'" to start evaluating your MCP server.']})]})}):l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsxs("div",{className:"text-center max-w-md mx-auto p-8",children:[l.jsx("div",{className:"w-20 h-20 bg-muted rounded-full flex items-center justify-center mx-auto mb-6",children:l.jsx(T1,{className:"h-10 w-10 text-muted-foreground"})}),l.jsx("h2",{className:"text-2xl font-semibold text-foreground mb-2",children:"Select a server"}),l.jsx("p",{className:"text-sm text-muted-foreground mb-6",children:"Choose a server from the tabs above to view and manage its test cases."})]})})})]}),l.jsx(PWt,{suiteToDelete:x.suiteToDelete,setSuiteToDelete:x.setSuiteToDelete,deletingSuiteId:x.deletingSuiteId,onConfirmDeleteSuite:x.confirmDelete,runToDelete:x.runToDelete,setRunToDelete:x.setRunToDelete,deletingRunId:x.deletingRunId,onConfirmDeleteRun:x.confirmDeleteRun,testCaseToDelete:x.testCaseToDelete,setTestCaseToDelete:x.setTestCaseToDelete,deletingTestCaseId:x.deletingTestCaseId,onConfirmDeleteTestCase:x.confirmDeleteTestCase})]})}function LWt({views:e,selectedViewId:t,onSelectView:n,onEditView:r,onDuplicateView:i,onDeleteView:a,deletingViewId:s,duplicatingViewId:o,isLoading:u}){return l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"p-4 border-b",children:l.jsx("h2",{className:"text-sm font-semibold",children:"Views"})}),l.jsx("div",{className:"flex-1 overflow-y-auto",children:u?l.jsx("div",{className:"p-4 text-center text-xs text-muted-foreground",children:"Loading views..."}):e.length===0?l.jsx("div",{className:"p-4 text-center text-xs text-muted-foreground",children:"No views yet"}):l.jsx("div",{className:"py-1",children:e.map(c=>{const d=t===c._id,f=s===c._id,p=o===c._id;return l.jsxs("div",{onClick:()=>n(c._id),className:Ie("group flex items-center gap-3 px-4 py-3 cursor-pointer transition-colors",d?"bg-accent":"hover:bg-accent/50"),children:[l.jsxs("div",{className:"flex-1 min-w-0 flex items-center gap-2",children:[l.jsx("span",{className:Ie("text-sm truncate",d?"font-medium":"font-normal"),children:c.name}),l.jsx("span",{className:"text-xs text-muted-foreground truncate shrink-0",children:c.toolName})]}),l.jsxs("div",{className:Ie("flex items-center gap-0.5 shrink-0 transition-opacity",d?"opacity-100":"opacity-0 group-hover:opacity-100"),children:[l.jsx(Ee,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:m=>{m.stopPropagation(),r(c)},"aria-label":"Edit view",children:l.jsx(Fq,{className:"h-3.5 w-3.5"})}),l.jsx(Ee,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-foreground",onClick:m=>{m.stopPropagation(),i(c)},disabled:p,"aria-label":"Duplicate view",children:l.jsx(Ca,{className:"h-3.5 w-3.5"})}),l.jsx(Ee,{variant:"ghost",size:"icon",className:"h-7 w-7 text-muted-foreground hover:text-destructive",onClick:m=>{m.stopPropagation(),a(c)},disabled:f,"aria-label":"Delete view",children:l.jsx(Ll,{className:"h-3.5 w-3.5"})})]})]},c._id)})})})]})}function zWt({view:e,displayMode:t="inline",onDisplayModeChange:n,serverName:r,serverConnectionStatus:i,toolInputOverride:a,toolOutputOverride:s,widgetStateOverride:o,isLoadingOverride:u,toolOutputErrorOverride:c}){const[d,f]=b.useState(null),[p,m]=b.useState(!0),[y,v]=b.useState(null),x=i!=="connected",_=a!==void 0?a:e.toolInput,S=s!==void 0?s:d,w=u!==void 0?u:p,T=c!==void 0?c:y;b.useEffect(()=>{if(s!==void 0){m(!1),v(null);return}async function $(){if(!e.toolOutputUrl){f(null),m(!1),v("No output URL available");return}m(!0),v(null);try{const O=await fetch(e.toolOutputUrl);if(!O.ok)throw new Error(`Failed to fetch output: ${O.status}`);const R=await O.json();f(R)}catch(O){console.error("Failed to load output:",O),v(O instanceof Error?O.message:"Failed to load output"),f(null)}finally{m(!1)}}$()},[e.toolOutputUrl,e._id,s]);const N=b.useCallback(()=>{},[]),E=b.useCallback(async()=>({}),[]),A=b.useCallback(()=>{},[]),I=b.useCallback(()=>{},[]),M=b.useMemo(()=>`view-preview-${e._id}`,[e._id]);if(w)return l.jsxs("div",{className:"flex items-center justify-center p-8 text-muted-foreground",children:[l.jsx(Pn,{className:"h-6 w-6 animate-spin mr-2"}),"Loading preview..."]});if(!S)return l.jsxs("div",{className:"flex items-center justify-center p-8 text-destructive",children:[l.jsx(Gs,{className:"h-5 w-5 mr-2"}),T||"No output data available"]});if(!r)return l.jsxs("div",{className:"flex items-center justify-center p-8 text-destructive",children:[l.jsx(Gs,{className:"h-5 w-5 mr-2"}),"Server not found. The server that created this view may have been deleted."]});if(e.protocol==="mcp-apps"){const $=e;return l.jsx("div",{className:"relative",children:l.jsx(yK,{serverId:r,toolCallId:M,toolName:e.toolName,toolState:e.toolState,toolInput:_,toolOutput:S,toolErrorText:e.toolErrorText,resourceUri:$.resourceUri,toolMetadata:e.toolMetadata,toolsMetadata:$.toolsMetadata,onSendFollowUp:N,onCallTool:E,onWidgetStateChange:A,onModelContextUpdate:I,displayMode:t,onDisplayModeChange:n,pipWidgetId:null,fullscreenWidgetId:null,isOffline:x,cachedWidgetHtmlUrl:$.widgetHtmlUrl??void 0},M)})}if(e.protocol==="openai-apps"){const $=e,O=o!==void 0?o:$.widgetState,R=e.toolMetadata,U=$.outputTemplate||R?.["openai/outputTemplate"]||"",z={...R,...U?{"openai/outputTemplate":U}:{}};return l.jsx(vK,{serverId:r,toolCallId:M,toolName:e.toolName,toolState:e.toolState,toolInput:_,toolOutput:S,toolMetadata:z,onSendFollowUp:N,onCallTool:E,onWidgetStateChange:A,serverInfo:$.serverInfo,initialWidgetState:O,displayMode:t,onDisplayModeChange:n,pipWidgetId:null,fullscreenWidgetId:null,isOffline:x,cachedWidgetHtmlUrl:$.widgetHtmlUrl??void 0},M)}return l.jsxs("div",{className:"flex items-center justify-center p-8 text-muted-foreground",children:["Unknown protocol: ",e.protocol]})}const UWt=[{label:"Light",value:"light"},{label:"Dark",value:"dark"}];UWt.map(e=>e.value);const I5e=[{label:"Default",value:"default",primary:{light:"oklch(0.205 0 0)",dark:"oklch(0.922 0 0)"}},{label:"Brutalist",value:"brutalist",primary:{light:"oklch(0.6489 0.2370 26.9728)",dark:"oklch(0.7044 0.1872 23.1858)"}},{label:"Soft Pop",value:"soft-pop",primary:{light:"oklch(0.5106 0.2301 276.9656)",dark:"oklch(0.6801 0.1583 276.9349)"}},{label:"Tangerine",value:"tangerine",primary:{light:"oklch(0.64 0.17 36.44)",dark:"oklch(0.64 0.17 36.44)"}}];I5e.map(e=>e.value);function FWt(){try{const e=localStorage.getItem(yPe);if(e==="dark"||e==="light")return e}catch(e){console.warn("Cannot access localStorage for theme mode:",e)}return"light"}function RZ(e){const t=document.documentElement;t.classList.add("disable-transitions"),t.classList.toggle("dark",e==="dark"),requestAnimationFrame(()=>{t.classList.remove("disable-transitions")})}function BWt(){try{const e=localStorage.getItem(xPe),t=I5e.map(n=>n.value);if(e&&t.includes(e))return e}catch(e){console.warn("Cannot access localStorage for theme preset:",e)}return"default"}function qWt(e){document.documentElement.setAttribute("data-theme-preset",e)}const gme=[{preset:"none",label:"None",shortLabel:"None"},{preset:"iphone-notch",label:"iPhone Notch",shortLabel:"Notch"},{preset:"iphone-dynamic-island",label:"Dynamic Island",shortLabel:"Island"},{preset:"android-gesture",label:"Android",shortLabel:"Android"}];function HWt({insets:e}){const t=e.top>0||e.bottom>0||e.left>0||e.right>0;return l.jsxs("div",{className:"relative w-full h-[140px] rounded-lg border-2 border-dashed border-border overflow-hidden bg-muted/30",children:[e.top>0&&l.jsx("div",{className:"absolute top-0 left-0 right-0 bg-destructive/20 border-b border-dashed border-destructive/40 flex items-center justify-center",style:{height:`${Math.min(e.top*.8,40)}px`},children:l.jsxs("span",{className:"text-[9px] text-muted-foreground font-medium",children:[e.top,"px"]})}),e.bottom>0&&l.jsx("div",{className:"absolute bottom-0 left-0 right-0 bg-destructive/20 border-t border-dashed border-destructive/40 flex items-center justify-center",style:{height:`${Math.min(e.bottom*.8,40)}px`},children:l.jsxs("span",{className:"text-[9px] text-muted-foreground font-medium",children:[e.bottom,"px"]})}),e.left>0&&l.jsx("div",{className:"absolute left-0 bg-destructive/20 border-r border-dashed border-destructive/40 flex items-center justify-center",style:{width:`${Math.min(e.left*.8,30)}px`,top:`${Math.min(e.top*.8,40)}px`,bottom:`${Math.min(e.bottom*.8,40)}px`},children:l.jsx("span",{className:"text-[9px] text-muted-foreground font-medium writing-mode-vertical",children:e.left})}),e.right>0&&l.jsx("div",{className:"absolute right-0 bg-destructive/20 border-l border-dashed border-destructive/40 flex items-center justify-center",style:{width:`${Math.min(e.right*.8,30)}px`,top:`${Math.min(e.top*.8,40)}px`,bottom:`${Math.min(e.bottom*.8,40)}px`},children:l.jsx("span",{className:"text-[9px] text-muted-foreground font-medium writing-mode-vertical",children:e.right})}),l.jsx("div",{className:"absolute bg-green-500/10 border border-dashed border-green-500/40 flex items-center justify-center",style:{top:`${Math.min(e.top*.8,40)}px`,bottom:`${Math.min(e.bottom*.8,40)}px`,left:`${Math.min(e.left*.8,30)}px`,right:`${Math.min(e.right*.8,30)}px`},children:l.jsx("span",{className:"text-[10px] text-muted-foreground",children:t?"Safe Content Area":"No Insets"})})]})}function ON({label:e,value:t,onChange:n}){return l.jsxs("div",{className:"flex flex-col items-center gap-1",children:[l.jsx("span",{className:"text-[10px] text-muted-foreground uppercase tracking-wide",children:e}),l.jsxs("div",{className:"relative",children:[l.jsx(Ct,{type:"number",min:0,max:100,value:t,onChange:r=>n(Math.max(0,parseInt(r.target.value)||0)),className:"w-16 h-7 text-xs text-center pr-5 [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"}),l.jsx("span",{className:"absolute right-2 top-1/2 -translate-y-1/2 text-[10px] text-muted-foreground",children:"px"})]})]})}function vme(){const e=Zt(s=>s.safeAreaPreset),t=Zt(s=>s.safeAreaInsets),n=Zt(s=>s.setSafeAreaPreset),r=Zt(s=>s.setSafeAreaInsets),i=(s,o)=>{r({[s]:o})},a=t.top>0||t.bottom>0||t.left>0||t.right>0;return l.jsxs(qo,{children:[l.jsx(Sl,{asChild:!0,children:l.jsx(Ee,{variant:a?"secondary":"ghost",size:"icon",className:"h-7 w-7",children:l.jsx(SQe,{className:"h-3.5 w-3.5"})})}),l.jsx(Ho,{className:"w-[280px] p-3",align:"start",children:l.jsxs("div",{className:"space-y-3",children:[l.jsxs("div",{className:"flex items-center justify-between",children:[l.jsx("span",{className:"text-xs font-medium uppercase tracking-wide text-muted-foreground",children:"Safe Area"}),e!=="none"&&e!=="custom"&&l.jsx("span",{className:"text-[10px] text-muted-foreground",children:gme.find(s=>s.preset===e)?.label})]}),l.jsx(HWt,{insets:t}),l.jsx("div",{className:"flex gap-1",children:gme.map(s=>l.jsx(Ee,{variant:e===s.preset?"secondary":"ghost",size:"sm",onClick:()=>n(s.preset),className:Ie("flex-1 h-6 text-[10px] px-1",e===s.preset&&"ring-1 ring-ring"),children:s.shortLabel},s.preset))}),l.jsxs("div",{className:"grid grid-cols-4 gap-2",children:[l.jsx(ON,{label:"Top",value:t.top,onChange:s=>i("top",s)}),l.jsx(ON,{label:"Bottom",value:t.bottom,onChange:s=>i("bottom",s)}),l.jsx(ON,{label:"Left",value:t.left,onChange:s=>i("left",s)}),l.jsx(ON,{label:"Right",value:t.right,onChange:s=>i("right",s)})]})]})})]})}const sw={mobile:{..._5.mobile,label:"Phone",icon:HQe},tablet:{..._5.tablet,label:"Tablet",icon:JQe},desktop:{..._5.desktop,label:"Desktop",icon:QJe}},VWt={label:"Custom",icon:oy},yme=[{code:"en-US",label:"English (US)"},{code:"en-GB",label:"English (UK)"},{code:"es-ES",label:"Español"},{code:"es-MX",label:"Español (MX)"},{code:"fr-FR",label:"Français"},{code:"de-DE",label:"Deutsch"},{code:"it-IT",label:"Italiano"},{code:"pt-BR",label:"Português (BR)"},{code:"ja-JP",label:"日本語"},{code:"zh-CN",label:"简体中文"},{code:"zh-TW",label:"繁體中文"},{code:"ko-KR",label:"한국어"},{code:"ar-SA",label:"العربية"},{code:"hi-IN",label:"हिन्दी"},{code:"ru-RU",label:"Русский"},{code:"nl-NL",label:"Nederlands"}],xme=[{zone:"America/New_York",label:"New York",offset:"UTC-5/-4"},{zone:"America/Chicago",label:"Chicago",offset:"UTC-6/-5"},{zone:"America/Denver",label:"Denver",offset:"UTC-7/-6"},{zone:"America/Los_Angeles",label:"Los Angeles",offset:"UTC-8/-7"},{zone:"America/Sao_Paulo",label:"São Paulo",offset:"UTC-3"},{zone:"America/Mexico_City",label:"Mexico City",offset:"UTC-6/-5"},{zone:"Europe/London",label:"London",offset:"UTC+0/+1"},{zone:"Europe/Paris",label:"Paris",offset:"UTC+1/+2"},{zone:"Europe/Berlin",label:"Berlin",offset:"UTC+1/+2"},{zone:"Europe/Moscow",label:"Moscow",offset:"UTC+3"},{zone:"Asia/Dubai",label:"Dubai",offset:"UTC+4"},{zone:"Asia/Kolkata",label:"Mumbai",offset:"UTC+5:30"},{zone:"Asia/Singapore",label:"Singapore",offset:"UTC+8"},{zone:"Asia/Shanghai",label:"Shanghai",offset:"UTC+8"},{zone:"Asia/Tokyo",label:"Tokyo",offset:"UTC+9"},{zone:"Asia/Seoul",label:"Seoul",offset:"UTC+9"},{zone:"Australia/Sydney",label:"Sydney",offset:"UTC+10/+11"},{zone:"Pacific/Auckland",label:"Auckland",offset:"UTC+12/+13"},{zone:"UTC",label:"UTC",offset:"UTC+0"}],RN=[{mode:"permissive",label:"Permissive",description:"Allows all HTTPS resources"},{mode:"widget-declared",label:"Strict",description:"Only widget-declared domains"}];function j5e({protocol:e,showThemeToggle:t=!1,className:n}){const[r,i]=b.useState(!1),[a,s]=b.useState(!1),[o,u]=b.useState(!1),[c,d]=b.useState(!1),f=Zt(q=>q.deviceType),p=Zt(q=>q.setDeviceType),m=Zt(q=>q.customViewport),y=Zt(q=>q.setCustomViewport),v=Zt(q=>q.globals),x=Zt(q=>q.updateGlobal),_=Zt(q=>q.capabilities),S=Zt(q=>q.setCapabilities),w=Zt(q=>q.cspMode),T=Zt(q=>q.setCspMode),N=Zt(q=>q.mcpAppsCspMode),E=Zt(q=>q.setMcpAppsCspMode),A=e===bn.MCP_APPS?N:w,I=e===bn.MCP_APPS?E:T,M=eo(q=>q.themeMode),$=eo(q=>q.setThemeMode),O=b.useCallback(()=>{const q=M==="dark"?"light":"dark";RZ(q),$(q)},[M,$]),R=b.useMemo(()=>f==="custom"?{...VWt,width:m.width,height:m.height}:sw[f],[f,m]),U=R.icon,z=v.locale,F=v.timeZone,D=e===null||e===bn.OPENAI_SDK,W=e===bn.MCP_APPS;return l.jsx("div",{className:n,children:l.jsxs("div",{className:"flex items-center gap-4",children:[D&&l.jsxs(l.Fragment,{children:[l.jsxs(qo,{open:r,onOpenChange:i,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(U,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:R.label}),l.jsxs("span",{className:"text-muted-foreground text-[10px]",children:[R.width,"×",R.height]})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Device"})})]}),l.jsx(Ho,{className:"w-56 p-2",align:"start",children:l.jsxs("div",{className:"space-y-2",children:[Object.entries(sw).map(([q,X])=>{const L=X.icon,Y=f===q;return l.jsxs("button",{onClick:()=>{p(q),i(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${Y?"bg-accent text-accent-foreground":""}`,children:[l.jsx(L,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:X.label}),l.jsxs("span",{className:"text-muted-foreground text-[10px] ml-auto",children:[X.width,"×",X.height]})]},q)}),l.jsxs("button",{onClick:()=>p("custom"),className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${f==="custom"?"bg-accent text-accent-foreground":""}`,children:[l.jsx(oy,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:"Custom"}),l.jsxs("span",{className:"text-muted-foreground text-[10px] ml-auto",children:[m.width,"×",m.height]})]}),f==="custom"&&l.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{htmlFor:"custom-width",className:"text-[10px] text-muted-foreground",children:"Width"}),l.jsx(Ct,{id:"custom-width",type:"number",min:100,max:2560,defaultValue:m.width,onBlur:q=>{const X=parseInt(q.target.value)||100;y({width:Math.max(100,Math.min(2560,X))})},className:"h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"},`w-${m.width}`)]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{htmlFor:"custom-height",className:"text-[10px] text-muted-foreground",children:"Height"}),l.jsx(Ct,{id:"custom-height",type:"number",min:100,max:2560,defaultValue:m.height,onBlur:q=>{const X=parseInt(q.target.value)||100;y({height:Math.max(100,Math.min(2560,X))})},className:"h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"},`h-${m.height}`)]})]})]})})]}),l.jsxs(qo,{open:a,onOpenChange:s,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(vte,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:z})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Locale"})})]}),l.jsx(Ho,{className:"w-48 p-2",align:"start",children:l.jsx("div",{className:"space-y-1",children:yme.map(q=>l.jsxs("button",{onClick:()=>{x("locale",q.code),s(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${z===q.code?"bg-accent text-accent-foreground":""}`,children:[l.jsx("span",{children:q.label}),l.jsx("span",{className:"text-muted-foreground text-[10px] ml-auto",children:q.code})]},q.code))})})]}),l.jsxs(qo,{open:o,onOpenChange:u,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(lA,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:RN.find(q=>q.mode===A)?.label})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"CSP"})})]}),l.jsx(Ho,{className:"w-56 p-2",align:"start",children:l.jsx("div",{className:"space-y-1",children:RN.map(q=>l.jsxs("button",{onClick:()=>{I(q.mode),u(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${A===q.mode?"bg-accent text-accent-foreground":""}`,children:[l.jsx("span",{className:"font-medium",children:q.label}),l.jsx("span",{className:"text-muted-foreground text-[10px] ml-auto",children:q.description})]},q.mode))})})]}),l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:_.hover?"secondary":"ghost",size:"icon",onClick:()=>S({hover:!_.hover}),className:"h-7 w-7",children:l.jsx(xte,{className:"h-3.5 w-3.5"})})}),l.jsxs(zt,{children:[l.jsx("p",{className:"font-medium",children:"Hover"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:_.hover?"Enabled":"Disabled"})]})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:_.touch?"secondary":"ghost",size:"icon",onClick:()=>S({touch:!_.touch}),className:"h-7 w-7",children:l.jsx(yte,{className:"h-3.5 w-3.5"})})}),l.jsxs(zt,{children:[l.jsx("p",{className:"font-medium",children:"Touch"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:_.touch?"Enabled":"Disabled"})]})]})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("div",{children:l.jsx(vme,{})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Safe Area"})})]})]}),W&&l.jsxs(l.Fragment,{children:[l.jsxs(qo,{open:r,onOpenChange:i,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(U,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:R.label}),l.jsxs("span",{className:"text-muted-foreground text-[10px]",children:[R.width,"×",R.height]})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Device"})})]}),l.jsx(Ho,{className:"w-56 p-2",align:"start",children:l.jsxs("div",{className:"space-y-2",children:[Object.entries(sw).map(([q,X])=>{const L=X.icon,Y=f===q;return l.jsxs("button",{onClick:()=>{p(q),i(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${Y?"bg-accent text-accent-foreground":""}`,children:[l.jsx(L,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:X.label}),l.jsxs("span",{className:"text-muted-foreground text-[10px] ml-auto",children:[X.width,"×",X.height]})]},q)}),l.jsxs("button",{onClick:()=>p("custom"),className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${f==="custom"?"bg-accent text-accent-foreground":""}`,children:[l.jsx(oy,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:"Custom"}),l.jsxs("span",{className:"text-muted-foreground text-[10px] ml-auto",children:[m.width,"×",m.height]})]}),f==="custom"&&l.jsxs("div",{className:"grid grid-cols-2 gap-2 pt-1",children:[l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{htmlFor:"custom-width-mcp",className:"text-[10px] text-muted-foreground",children:"Width"}),l.jsx(Ct,{id:"custom-width-mcp",type:"number",min:100,max:2560,defaultValue:m.width,onBlur:q=>{const X=parseInt(q.target.value)||100;y({width:Math.max(100,Math.min(2560,X))})},className:"h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"},`w-mcp-${m.width}`)]}),l.jsxs("div",{className:"space-y-1",children:[l.jsx(Zn,{htmlFor:"custom-height-mcp",className:"text-[10px] text-muted-foreground",children:"Height"}),l.jsx(Ct,{id:"custom-height-mcp",type:"number",min:100,max:2560,defaultValue:m.height,onBlur:q=>{const X=parseInt(q.target.value)||100;y({height:Math.max(100,Math.min(2560,X))})},className:"h-7 text-xs [appearance:textfield] [&::-webkit-outer-spin-button]:appearance-none [&::-webkit-inner-spin-button]:appearance-none"},`h-mcp-${m.height}`)]})]})]})})]}),l.jsxs(qo,{open:a,onOpenChange:s,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(vte,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:z})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Locale"})})]}),l.jsx(Ho,{className:"w-48 p-2",align:"start",children:l.jsx("div",{className:"space-y-1",children:yme.map(q=>l.jsxs("button",{onClick:()=>{x("locale",q.code),s(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${z===q.code?"bg-accent text-accent-foreground":""}`,children:[l.jsx("span",{children:q.label}),l.jsx("span",{className:"text-muted-foreground text-[10px] ml-auto",children:q.code})]},q.code))})})]}),l.jsxs(qo,{open:c,onOpenChange:d,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(Sw,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:xme.find(q=>q.zone===F)?.label||F})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Timezone"})})]}),l.jsx(Ho,{className:"w-56 p-2",align:"start",children:l.jsx("div",{className:"space-y-1",children:xme.map(q=>l.jsxs("button",{onClick:()=>{x("timeZone",q.zone),d(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${F===q.zone?"bg-accent text-accent-foreground":""}`,children:[l.jsx("span",{children:q.label}),l.jsx("span",{className:"text-muted-foreground text-[10px] ml-auto",children:q.offset})]},q.zone))})})]}),l.jsxs(qo,{open:o,onOpenChange:u,children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"sm",className:"h-7 px-2 text-xs gap-1.5",children:[l.jsx(lA,{className:"h-3.5 w-3.5"}),l.jsx("span",{children:RN.find(q=>q.mode===N)?.label})]})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"CSP"})})]}),l.jsx(Ho,{className:"w-56 p-2",align:"start",children:l.jsx("div",{className:"space-y-1",children:RN.map(q=>l.jsxs("button",{onClick:()=>{E(q.mode),u(!1)},className:`w-full flex items-center gap-2 px-2 py-1.5 rounded text-sm hover:bg-accent transition-colors ${N===q.mode?"bg-accent text-accent-foreground":""}`,children:[l.jsx("span",{className:"font-medium",children:q.label}),l.jsx("span",{className:"text-muted-foreground text-[10px] ml-auto",children:q.description})]},q.mode))})})]}),l.jsxs("div",{className:"flex items-center gap-0.5",children:[l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:_.hover?"secondary":"ghost",size:"icon",onClick:()=>S({hover:!_.hover}),className:"h-7 w-7",children:l.jsx(xte,{className:"h-3.5 w-3.5"})})}),l.jsxs(zt,{children:[l.jsx("p",{className:"font-medium",children:"Hover"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:_.hover?"Enabled":"Disabled"})]})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:_.touch?"secondary":"ghost",size:"icon",onClick:()=>S({touch:!_.touch}),className:"h-7 w-7",children:l.jsx(yte,{className:"h-3.5 w-3.5"})})}),l.jsxs(zt,{children:[l.jsx("p",{className:"font-medium",children:"Touch"}),l.jsx("p",{className:"text-xs text-muted-foreground",children:_.touch?"Enabled":"Disabled"})]})]})]}),l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx("div",{children:l.jsx(vme,{})})}),l.jsx(zt,{children:l.jsx("p",{className:"font-medium",children:"Safe Area"})})]})]}),t&&l.jsxs(Dt,{children:[l.jsx(Lt,{asChild:!0,children:l.jsx(Ee,{variant:"ghost",size:"icon",onClick:O,className:"h-7 w-7",children:M==="dark"?l.jsx(z1e,{className:"h-3.5 w-3.5"}):l.jsx($1e,{className:"h-3.5 w-3.5"})})}),l.jsx(zt,{children:M==="dark"?"Light mode":"Dark mode"})]})]})})}function GWt({view:e,serverName:t,serverConnectionStatus:n,toolInputOverride:r,toolOutputOverride:i,widgetStateOverride:a,isLoadingOverride:s,toolOutputErrorOverride:o,isEditing:u=!1}){const c=Zt(T=>T.deviceType),d=Zt(T=>T.customViewport),f=Zt(T=>T.setPlaygroundActive),p=Zt(T=>T.setDeviceType),m=Zt(T=>T.setCustomViewport),y=Zt(T=>T.updateGlobal),v=Zt(T=>T.setCapabilities),x=Zt(T=>T.setSafeAreaInsets),_=Zt(T=>T.setSelectedProtocol),S=b.useMemo(()=>c==="custom"?{width:d.width,height:d.height}:sw[c],[c,d]);b.useEffect(()=>(f(!0),()=>f(!1)),[f]),b.useEffect(()=>{const T=e.protocol==="mcp-apps"?bn.MCP_APPS:bn.OPENAI_SDK;_(T)},[e.protocol,_]),b.useEffect(()=>{if(e.defaultContext){const T=e.defaultContext;T.deviceType&&p(T.deviceType),T.viewport&&m(T.viewport),T.locale&&y("locale",T.locale),T.timeZone&&y("timeZone",T.timeZone),T.capabilities&&v(T.capabilities),T.safeAreaInsets&&x(T.safeAreaInsets)}},[e._id,e.defaultContext,p,m,y,v,x]);const w=e.protocol==="mcp-apps"?bn.MCP_APPS:bn.OPENAI_SDK;return l.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[u&&l.jsx("div",{className:"flex items-center justify-center px-4 py-2 border-b bg-muted/30 text-xs text-muted-foreground",children:l.jsx(j5e,{protocol:w})}),l.jsx("div",{className:"flex-1 flex items-center justify-center p-4 min-h-0 overflow-auto bg-muted/20",children:l.jsx("div",{className:"relative bg-background border border-border rounded-xl shadow-lg flex flex-col overflow-hidden",style:{width:S.width,maxWidth:"100%",height:S.height,maxHeight:"100%"},children:l.jsx("div",{className:"flex-1 min-h-0 overflow-y-auto overscroll-contain",children:l.jsx(zWt,{view:e,displayMode:"inline",serverName:t,serverConnectionStatus:n,toolInputOverride:r,toolOutputOverride:i,widgetStateOverride:a,isLoadingOverride:s,toolOutputErrorOverride:o})})})})]})}function bme({value:e,onSave:t,className:n,inputClassName:r,disabled:i=!1,truncate:a=!0,onClick:s}){const[o,u]=b.useState(!1),[c,d]=b.useState(e),[f,p]=b.useState(!1),m=b.useRef(null);b.useEffect(()=>{d(e)},[e]),b.useEffect(()=>{o&&m.current&&(m.current.focus(),m.current.select())},[o]);const y=b.useCallback(()=>{!i&&t&&(d(e),u(!0))},[i,t,e]),v=b.useCallback(()=>{d(e),u(!1)},[e]),x=b.useCallback(async()=>{const T=c.trim();if(!T||T===e){v();return}if(!t){v();return}p(!0);try{await t(T),u(!1)}catch{}finally{p(!1)}},[c,e,t,v]),_=b.useCallback(T=>{T.key==="Enter"?(T.preventDefault(),x()):T.key==="Escape"&&v()},[x,v]),S=b.useCallback(T=>{s?.(T)},[s]),w=b.useCallback(T=>{s?.(T),y()},[s,y]);return o?l.jsx("input",{ref:m,type:"text",value:c,onChange:T=>d(T.target.value),onClick:S,onBlur:x,onKeyDown:_,disabled:f,className:Ie("px-0 py-0 bg-transparent border-none focus:outline-none focus:ring-0",f&&"opacity-50",n,r)}):l.jsx("span",{onClick:w,className:Ie(a&&"truncate",!i&&t&&"cursor-pointer hover:opacity-60 transition-opacity",n),children:e})}function WWt({view:e,onBack:t,initialToolOutput:n,liveToolOutput:r,initialWidgetState:i,liveWidgetState:a,isLoadingToolOutput:s,onDataChange:o,isSaving:u=!1,onSave:c,hasUnsavedChanges:d=!1,serverConnectionStatus:f,isRunning:p=!1,onRun:m,onRename:y}){const v=b.useCallback((I,M,$)=>{const O={toolInput:I,toolOutput:M};return e.protocol==="openai-apps"?{...O,widgetState:$??null}:O},[e.protocol]),[x,_]=b.useState(()=>v(e.toolInput,n??null,i??null)),S=b.useRef(r),w=b.useRef(a);b.useEffect(()=>{_(v(e.toolInput,n??null,i??null))},[e._id,n,i,v]),b.useEffect(()=>{r!==S.current&&(S.current=r,_(I=>({...I,toolOutput:r??null})))},[r]),b.useEffect(()=>{e.protocol==="openai-apps"&&a!==w.current&&(w.current=a,_(I=>({...I,widgetState:a??null})))},[e.protocol,a]);const T=b.useCallback(I=>{if(I&&typeof I=="object"){const M=I,$=e.protocol==="openai-apps"?{toolInput:M.toolInput,toolOutput:M.toolOutput,widgetState:"widgetState"in M?M.widgetState:null}:{toolInput:M.toolInput,toolOutput:M.toolOutput};_($),e.protocol==="openai-apps"?o?.({toolInput:$.toolInput,toolOutput:$.toolOutput,widgetState:$.widgetState}):o?.({toolInput:$.toolInput,toolOutput:$.toolOutput})}},[o,e.protocol]),N=b.useCallback(async()=>{!d||!c||await c()},[d,c]);if(s)return l.jsxs("div",{className:"flex flex-col h-full overflow-hidden",children:[l.jsx("div",{className:"flex items-center justify-between px-3 py-1.5 bg-muted/30",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ee,{variant:"ghost",size:"sm",onClick:t,className:"h-7 w-7 p-0",children:l.jsx(mte,{className:"h-4 w-4"})}),l.jsx(bme,{value:e.name,onSave:y,disabled:!y,className:"text-sm font-medium max-w-[200px]"})]})}),l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsx(Pn,{className:"h-6 w-6 animate-spin text-muted-foreground"})})]});const E=l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Ee,{variant:"ghost",size:"sm",onClick:t,className:"h-7 w-7 p-0",children:l.jsx(mte,{className:"h-4 w-4"})}),l.jsx(bme,{value:e.name,onSave:y,disabled:!y,className:"text-sm font-medium max-w-[200px]"})]}),A=l.jsxs("div",{className:"flex items-center gap-2",children:[f==="connected"&&m&&l.jsxs(Ee,{variant:"outline",size:"sm",onClick:m,disabled:p||u,className:"h-7 px-2 text-xs",children:[p?l.jsx(Pn,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):l.jsx(Tx,{className:"h-3.5 w-3.5 mr-1"}),"Run"]}),l.jsxs(Ee,{size:"sm",onClick:N,disabled:!d||u||p,className:"h-7 px-2 text-xs",children:[u?l.jsx(Pn,{className:"h-3.5 w-3.5 mr-1 animate-spin"}):l.jsx(vS,{className:"h-3.5 w-3.5 mr-1"}),"Save"]})]});return l.jsx("div",{className:"flex flex-col h-full overflow-hidden",children:l.jsx(zn,{value:x,onChange:T,expandJsonStrings:!0,mode:"edit",showToolbar:!0,showModeToggle:!1,wrapLongLinesInEdit:!0,allowMaximize:!0,height:"100%",toolbarLeftContent:E,toolbarRightContent:A})})}function KWt({selectedServer:e}){const{isAuthenticated:t,isLoading:n}=Ba(),r=ci(),i=Rx(),s=i.workspaces[i.activeWorkspaceId]?.sharedWorkspaceId??null,[o,u]=b.useState(null),[c,d]=b.useState(!1),[f,p]=b.useState(null),[m,y]=b.useState(null),[v,x]=b.useState(null),[_,S]=b.useState(null),[w,T]=b.useState(null),[N,E]=b.useState(null),[A,I]=b.useState(null),[M,$]=b.useState(!1),[O,R]=b.useState(!1),[U,z]=b.useState(!1),F=CPe(),D=bs(Me=>Me.widgets),W=b.useRef(null),{sortedViews:q,isLoading:X}=xK({isAuthenticated:t,workspaceId:s}),{serversById:L,serversByName:Y}=bK({isAuthenticated:t,workspaceId:s}),G=e?Y.get(e):void 0,P=b.useMemo(()=>G?q.filter(Me=>Me.serverId===G):[],[q,G]),V=P.length>0;b.useEffect(()=>{o&&G&&(P.some(be=>be._id===o)||(u(null),d(!1),x(null),S(null),T(null),E(null),I(null),$(!1),W.current=null))},[G,o,P]);const K=b.useCallback(Me=>{if(Me)return i.servers[Me]?.connectionStatus},[i.servers]),{createMcpView:Q,createOpenaiView:oe,updateMcpView:re,updateOpenaiView:ee,removeMcpView:le,removeOpenaiView:te,generateMcpUploadUrl:Z,generateOpenaiUploadUrl:ne}=NPe(),J=b.useMemo(()=>o?P.find(Me=>Me._id===o)??null:null,[o,P]);b.useEffect(()=>{if(!J){x(null),S(null),T(null),E(null),I(null),$(!1),W.current=null;return}if(W.current===J._id)return;const Me=J._id,be=new AbortController;let je=!0;x(J.toolInput),S(null),T(J.protocol==="openai-apps"?J.widgetState??null:null),E(null),I(null);const Xe=!!J.toolOutputUrl;$(Xe);async function ue(){if(!J?.toolOutputUrl){W.current=Me;return}try{const fe=await fetch(J.toolOutputUrl,{signal:be.signal});if(!fe.ok)throw new Error(`Failed to fetch output: ${fe.status}`);const xe=await fe.json();if(!je)return;S(xe),E(xe),W.current=Me}catch(fe){if(!je||fe instanceof DOMException&&fe.name==="AbortError")return;console.error("Failed to load toolOutput:",fe),I(fe instanceof Error?fe.message:"Failed to load output"),W.current=Me}finally{je&&$(!1)}}return ue(),()=>{je=!1,be.abort()}},[J]),b.useEffect(()=>{r.capture("views_tab_viewed",{location:"views_tab",platform:Et(),environment:void 0})},[r]);const se=b.useCallback(Me=>{u(Me),W.current=null,r.capture("view_selected",{location:"views_tab",platform:Et(),environment:void 0})},[r]),ie=b.useCallback(async Me=>{p(Me._id);try{Me.protocol==="mcp-apps"?await le({viewId:Me._id}):await te({viewId:Me._id}),Pe.success(`View "${Me.name}" deleted`),r.capture("view_deleted",{location:"views_tab",platform:Et(),environment:void 0}),o===Me._id&&u(null)}catch(be){console.error("Failed to delete view:",be),Pe.error("Failed to delete view")}finally{p(null)}},[o,le,te,r]),he=b.useCallback(Me=>{u(Me._id),d(!0),W.current=null,r.capture("view_edit_started",{location:"views_tab",platform:Et(),environment:void 0})},[r]),ye=b.useCallback(async(Me,be)=>{try{const je={viewId:Me._id,name:be};Me.protocol==="mcp-apps"?await re(je):await ee(je),Pe.success(`View renamed to "${be}"`),r.capture("view_renamed",{location:"views_tab",platform:Et(),environment:void 0})}catch(je){throw console.error("Failed to rename view:",je),Pe.error("Failed to rename view"),je}},[re,ee,r]),Ne=b.useCallback(async Me=>{if(s){y(Me._id);try{let be;if(Me.toolOutputUrl){const Ce=await fetch(Me.toolOutputUrl);if(Ce.ok){const He=await Ce.json(),Ze=Me.protocol==="mcp-apps"?await Z():await ne(),st=await fetch(Ze,{method:"POST",body:JSON.stringify(He),headers:{"Content-Type":"application/json"}});if(st.ok){const{storageId:ot}=await st.json();be=ot}}}let je;if(Me.widgetHtmlUrl){const Ce=await fetch(Me.widgetHtmlUrl);if(Ce.ok){const He=await Ce.text(),Ze=Me.protocol==="mcp-apps"?await Z():await ne(),st=await fetch(Ze,{method:"POST",body:He,headers:{"Content-Type":"text/html"}});if(st.ok){const{storageId:ot}=await st.json();je=ot}}}const Xe=Me.name.replace(/ \(copy( \d+)?\)$/,""),fe=P.filter(Ce=>Ce.name.startsWith(Xe)&&Ce.name.match(/ \(copy( \d+)?\)$/)).length+1,xe=fe===1?`${Xe} (copy)`:`${Xe} (copy ${fe})`;Me.protocol==="mcp-apps"?await Q({workspaceId:s,serverId:Me.serverId,name:xe,description:Me.description,resourceUri:Me.resourceUri,toolName:Me.toolName,toolState:Me.toolState,toolInput:Me.toolInput,toolOutputBlobId:be,widgetHtmlBlobId:je,toolErrorText:Me.toolErrorText,toolMetadata:Me.toolMetadata,prefersBorder:Me.prefersBorder,tags:Me.tags,category:Me.category,defaultContext:Me.defaultContext}):await oe({workspaceId:s,serverId:Me.serverId,name:xe,description:Me.description,outputTemplate:Me.outputTemplate,toolName:Me.toolName,toolState:Me.toolState,toolInput:Me.toolInput,toolOutputBlobId:be,widgetHtmlBlobId:je,toolErrorText:Me.toolErrorText,toolMetadata:Me.toolMetadata,prefersBorder:Me.prefersBorder,tags:Me.tags,category:Me.category,defaultContext:Me.defaultContext,serverInfo:Me.serverInfo,widgetState:Me.widgetState}),Pe.success(`View duplicated as "${xe}"`),r.capture("view_duplicated",{location:"views_tab",platform:Et(),environment:void 0})}catch(be){console.error("Failed to duplicate view:",be),Pe.error("Failed to duplicate view")}finally{y(null)}}},[s,P,Q,oe,Z,ne,r]),ce=b.useCallback(Me=>{x(Me.toolInput),S(Me.toolOutput),"widgetState"in Me&&T(Me.widgetState)},[]),Te=b.useMemo(()=>{if(!J)return!1;const Me=JSON.stringify(v)!==JSON.stringify(J.toolInput),be=JSON.stringify(_)!==JSON.stringify(N),je=!nle(F,J.defaultContext),Xe=J.protocol==="openai-apps"?J.widgetState??null:null,ue=J.protocol==="openai-apps"&&JSON.stringify(w??null)!==JSON.stringify(Xe);return Me||be||je||ue},[J,v,_,w,N,F]),we=b.useCallback(async()=>{if(!(!J||!Te)){R(!0);try{const Me=JSON.stringify(_)!==JSON.stringify(N),be=!nle(F,J.defaultContext),je=J.protocol==="openai-apps"?J.widgetState??null:null,Xe=J.protocol==="openai-apps"&&JSON.stringify(w??null)!==JSON.stringify(je);let ue,fe;if(Me&&_!==null){const st=J.protocol==="mcp-apps"?await Z():await ne(),ot=await fetch(st,{method:"POST",body:JSON.stringify(_),headers:{"Content-Type":"application/json"}});if(!ot.ok)throw new Error(`Failed to upload toolOutput: ${ot.status}`);const{storageId:mt}=await ot.json();ue=mt}const xe=`view-preview-${J._id}`,Ce=D.get(xe),He=Ce?.widgetHtml;if(He){const st=J.protocol==="mcp-apps"?await Z():await ne(),ot=await fetch(st,{method:"POST",body:He,headers:{"Content-Type":"text/html"}});if(!ot.ok)throw new Error(`Failed to upload widget HTML: ${ot.status}`);const{storageId:mt}=await ot.json();fe=mt}const Ze={viewId:J._id,toolInput:v};ue&&(Ze.toolOutputBlobId=ue),fe&&(Ze.widgetHtmlBlobId=fe),be&&(Ze.defaultContext=F),J.protocol==="openai-apps"&&(Xe?Ze.widgetState=w??null:Ce!==void 0&&(Ze.widgetState=Ce.widgetState)),J.protocol==="mcp-apps"?await re(Ze):await ee(Ze),E(_),Pe.success("View saved successfully"),r.capture("view_saved",{location:"views_tab",platform:Et(),environment:void 0})}catch(Me){console.error("Failed to save view:",Me),Pe.error("Failed to save view")}finally{R(!1)}}},[J,Te,v,_,w,N,F,Z,ne,re,ee,D,r]),Oe=b.useCallback(async()=>{if(!J||v===null||!e)return;if(K(e)!=="connected"){Pe.error("Server is not connected");return}z(!0);try{const be=v??{},je=await n3(e,J.toolName,be);if("error"in je){Pe.error(`Execution failed: ${je.error}`);return}if(je.status==="elicitation_required"){Pe.error("Tool requires elicitation (not supported in Views)");return}if(je.status==="task_created"){Pe.error("Background tasks not supported in Views");return}S(je.result),Pe.success("Tool executed successfully"),r.capture("view_tool_executed",{location:"views_tab",platform:Et(),environment:void 0})}catch(be){const je=be instanceof Error?be.message:"Execution failed";Pe.error(je)}finally{z(!1)}},[J,v,e,K,r]),Ue=b.useCallback(()=>{u(null),d(!1),x(null),S(null),T(null),E(null),W.current=null},[]);return n?l.jsx("div",{className:"p-6",children:l.jsx("div",{className:"flex min-h-[calc(100vh-200px)] items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading..."})]})})}):t?s?X?l.jsx("div",{className:"p-6",children:l.jsx("div",{className:"flex min-h-[calc(100vh-200px)] items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"mx-auto h-8 w-8 animate-spin rounded-full border-b-2 border-primary"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Loading views..."})]})})}):l.jsx("div",{className:"h-full flex flex-col overflow-hidden",children:l.jsxs(Bc,{direction:"horizontal",className:"flex-1 overflow-hidden",children:[l.jsx(ta,{defaultSize:55,minSize:30,maxSize:70,className:"border-r bg-muted/30 flex flex-col",children:J&&c?l.jsx(WWt,{view:J,onBack:Ue,initialToolOutput:N,liveToolOutput:_,initialWidgetState:J.protocol==="openai-apps"?J.widgetState:void 0,liveWidgetState:J.protocol==="openai-apps"?w:void 0,isLoadingToolOutput:M,onDataChange:ce,isSaving:O,onSave:we,hasUnsavedChanges:Te,serverConnectionStatus:K(e),isRunning:U,onRun:Oe,onRename:Me=>ye(J,Me)}):l.jsx(LWt,{views:P,selectedViewId:o,onSelectView:se,onEditView:he,onDuplicateView:Ne,onDeleteView:ie,deletingViewId:f,duplicatingViewId:m,isLoading:X})}),l.jsx($u,{withHandle:!0}),l.jsx(ta,{defaultSize:50,className:"flex flex-col overflow-hidden",children:J?l.jsx(GWt,{view:J,serverName:L.get(J.serverId),serverConnectionStatus:K(L.get(J.serverId)),toolInputOverride:v,isLoadingOverride:M,toolOutputErrorOverride:A,toolOutputOverride:_,widgetStateOverride:J.protocol==="openai-apps"?w:void 0,isEditing:c}):l.jsx("div",{className:"flex-1 flex items-center justify-center",children:l.jsxs("div",{className:"text-center max-w-md mx-auto p-8",children:[l.jsx("div",{className:"w-20 h-20 bg-muted rounded-full flex items-center justify-center mx-auto mb-6",children:l.jsx(N1,{className:"h-10 w-10 text-muted-foreground"})}),l.jsx("h2",{className:"text-2xl font-semibold text-foreground mb-2",children:V?"Select a view":e?"No views for this server":"Select a server"}),l.jsx("p",{className:"text-sm text-muted-foreground mb-6",children:V?"Choose a view from the list to see its details and preview.":e?"This server has no saved views yet. Save tool executions from the Chat tab to create reusable views.":"Select a server from the tabs above to view its saved views."})]})})})]})}):l.jsx("div",{className:"p-6",children:l.jsx(Rc,{icon:N1,title:"No workspace selected",description:"Select a shared workspace to view and manage saved views.",className:"h-[calc(100vh-200px)]"})}):l.jsx("div",{className:"p-6",children:l.jsx(Rc,{icon:N1,title:"Sign in to view saved views",description:"Create an account or sign in to save and manage tool execution snapshots.",className:"h-[calc(100vh-200px)]"})})}function ZWt({open:e,onOpenChange:t,provider:n,value:r,onValueChange:i,baseUrlValue:a,onBaseUrlChange:s,onSave:o,onCancel:u,onRemove:c,isConfigured:d}){const f=ci();return l.jsx(si,{open:e,onOpenChange:t,children:l.jsxs(oi,{className:"max-w-md",children:[l.jsx(vi,{children:l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[n&&l.jsx("div",{className:"w-12 h-12 rounded-lg bg-card p-2 border",children:l.jsx("img",{src:n.logo,alt:n.logoAlt,className:"w-full h-full object-contain"})}),l.jsxs("div",{children:[l.jsxs(yi,{className:"text-left",children:["Configure ",n?.name]}),l.jsx(us,{className:"text-left",children:n?.description})]})]})}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{htmlFor:"api-key",className:"text-sm font-medium",children:"API Key"}),l.jsx(Ct,{id:"api-key",type:"password",value:r,onChange:p=>i(p.target.value),placeholder:n?.placeholder,className:"mt-1"})]}),n?.defaultBaseUrl&&s&&l.jsxs("div",{children:[l.jsx("label",{htmlFor:"base-url",className:"text-sm font-medium",children:"Base URL (Optional)"}),l.jsx(Ct,{id:"base-url",type:"text",value:a||"",onChange:p=>s(p.target.value),placeholder:n.defaultBaseUrl,className:"mt-1"}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Leave empty to use the default endpoint"})]}),l.jsxs("div",{className:"flex items-center gap-2 p-3 bg-info/10 rounded-lg",children:[l.jsx(Iu,{className:"w-4 h-4 text-info"}),l.jsxs("span",{className:"text-sm text-info",children:["Need an API key?"," ",l.jsx("button",{onClick:()=>n&&window.open(n.getApiKeyUrl,"_blank"),className:"underline hover:no-underline",children:"Get one here"})]})]}),n?.id==="openai"&&l.jsx(mK,{children:l.jsx(gK,{children:l.jsxs("p",{children:[l.jsx("strong",{children:"GPT-5 models require organization verification."})," ","If you encounter access errors, visit"," ",l.jsx("a",{href:"https://platform.openai.com/settings/organization/general",target:"_blank",rel:"noreferrer",className:"underline hover:no-underline font-medium align-baseline inline",children:"OpenAI Settings"})," ","and verify your organization. Access may take up to 15 minutes after verification."]})})})]}),l.jsxs(Js,{className:"flex-row justify-between sm:justify-between",children:[d&&c?l.jsx(Ee,{variant:"ghost",className:"text-destructive hover:text-destructive hover:bg-destructive/10",onClick:c,children:"Remove"}):l.jsx("div",{}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Ee,{variant:"outline",onClick:u,children:"Cancel"}),l.jsx(Ee,{onClick:()=>{f.capture("save_api_key",{location:"provider_config_dialog",platform:Et(),environment:void 0}),o()},disabled:!r.trim(),children:"Save"})]})]})]})})}function YWt({open:e,onOpenChange:t,value:n,onValueChange:r,onSave:i,onCancel:a}){return l.jsx(si,{open:e,onOpenChange:t,children:l.jsxs(oi,{className:"max-w-md",children:[l.jsx(vi,{children:l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[l.jsx("div",{className:"w-12 h-12 rounded-lg bg-card p-2 border",children:l.jsx("img",{src:"/ollama_logo.svg",alt:"Ollama",className:"w-full h-full object-contain"})}),l.jsxs("div",{children:[l.jsx(yi,{className:"text-left pb-2",children:"Configure Ollama URL"}),l.jsx(us,{className:"text-left",children:"Set the base URL for your Ollama instance"})]})]})}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{htmlFor:"ollama-url",className:"text-sm font-medium",children:"Base URL"}),l.jsx(Ct,{id:"ollama-url",type:"url",value:n,onChange:s=>r(s.target.value),placeholder:"http://127.0.0.1:11434/api",className:"mt-1"})]}),l.jsxs("div",{className:"flex items-center gap-2 p-3 bg-info/10 rounded-lg",children:[l.jsx(Iu,{className:"w-4 h-4 text-info"}),l.jsxs("span",{className:"text-sm text-info",children:["Need help?"," ",l.jsx("button",{onClick:()=>window.open("https://ollama.ai/download","_blank"),className:"underline hover:no-underline",children:"Download Ollama"})]})]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:a,children:"Cancel"}),l.jsx(Ee,{onClick:i,disabled:!n.trim(),children:"Save URL"})]})]})})}function XWt({open:e,onOpenChange:t,baseUrl:n,apiKey:r,modelAlias:i,onBaseUrlChange:a,onApiKeyChange:s,onModelAliasChange:o,onSave:u,onCancel:c}){return l.jsx(si,{open:e,onOpenChange:t,children:l.jsxs(oi,{className:"max-w-md",children:[l.jsx(vi,{children:l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[l.jsx("div",{className:"w-12 h-12 rounded-lg bg-card p-2 flex items-center justify-center border",children:l.jsx("img",{src:"/litellm_logo.png",alt:"LiteLLM Logo",className:"w-full h-full object-contain"})}),l.jsxs("div",{children:[l.jsx(yi,{className:"text-left pb-2",children:"Configure LiteLLM Proxy"}),l.jsx(us,{className:"text-left",children:"Set up your LiteLLM proxy connection"})]})]})}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{htmlFor:"litellm-url",className:"text-sm font-medium",children:"Base URL"}),l.jsx(Ct,{id:"litellm-url",type:"url",value:n,onChange:d=>a(d.target.value),placeholder:"http://localhost:4000",className:"mt-1"})]}),l.jsxs("div",{children:[l.jsx("label",{htmlFor:"litellm-api-key",className:"text-sm font-medium",children:"API Key"}),l.jsx(Ct,{id:"litellm-api-key",type:"password",value:r,onChange:d=>s(d.target.value),placeholder:"sk-...",className:"mt-1"})]}),l.jsxs("div",{children:[l.jsxs("label",{htmlFor:"litellm-model",className:"text-sm font-medium",children:["Model Aliases"," ",l.jsx("span",{className:"text-muted-foreground",children:"(comma-separated)"})]}),l.jsx(Ct,{id:"litellm-model",type:"text",value:i,onChange:d=>o(d.target.value),placeholder:"gemini/gemini-2.5-flash, gpt-4, claude-3-opus",className:"mt-1"}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Enter multiple model aliases separated by commas. Each will appear as a separate option in the chat."})]}),l.jsxs("div",{className:"flex items-center gap-2 p-3 bg-info/10 rounded-lg",children:[l.jsx(Iu,{className:"w-4 h-4 text-info"}),l.jsxs("span",{className:"text-sm text-info",children:["Need help?"," ",l.jsx("button",{onClick:()=>window.open("https://docs.litellm.ai/docs/proxy/quick_start","_blank"),className:"underline hover:no-underline",children:"LiteLLM Proxy Docs"})]})]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:c,children:"Cancel"}),l.jsx(Ee,{onClick:u,disabled:!n.trim()||!i.trim(),children:"Save Configuration"})]})]})})}function JWt({items:e,placeholder:t="Select item...",searchPlaceholder:n="Search...",emptyMessage:r="No item found.",className:i,value:a,onValueChange:s,label:o="Model"}){const[u,c]=b.useState(!1),[d,f]=b.useState([]),p=a!==void 0?a:d,m=v=>{s?s(v):f(v)},y=()=>{const v=p;return v&&v.length>0?v.length===1?`1 ${o} Selected`:`${v.length} ${o}s Selected`:t};return l.jsxs(qo,{open:u,onOpenChange:c,modal:!0,children:[l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"outline",role:"combobox","aria-expanded":u,className:Ie("w-[200px] justify-between bg-background",i),children:[l.jsx("span",{className:"truncate",children:y()}),l.jsx(Lq,{className:"ml-2 h-4 w-4 shrink-0 opacity-50"})]})}),l.jsx(Ho,{className:"w-96 p-0",align:"start",children:l.jsxs(S5e,{children:[l.jsx(k5e,{placeholder:n,className:"h-9"}),l.jsx(E5e,{children:r}),l.jsx(T5e,{className:"max-h-48 overflow-auto",children:e.map(v=>{const x=p.includes(v.value);return l.jsxs(N5e,{value:v.value,onSelect:_=>{const S=p||[],w=S.includes(v.value)?S.filter(T=>T!==v.value):[...S,v.value];m(w)},children:[l.jsxs("div",{className:"flex flex-col",children:[l.jsx("span",{children:v.label}),v.description&&l.jsx("span",{className:"text-xs text-muted-foreground",children:v.description})]}),l.jsx(xi,{className:Ie("ml-auto h-4 w-4",x?"opacity-100":"opacity-0")})]},v.value)})})]})})]})}function QWt(){const[e,t]=b.useState([]),[n,r]=b.useState(!1),[i,a]=b.useState(null),s=b.useCallback(async()=>{r(!0),a(null);try{const o=await fetch("https://openrouter.ai/api/v1/models?supported_parameters=tools");if(!o.ok)throw new Error(`Failed to fetch models: ${o.statusText}`);const d=((await o.json()).data||[]).map(f=>({value:f.id,label:f.name,description:f.id}));d.sort((f,p)=>f.label.localeCompare(p.label)),t(d)}catch(o){const u=o instanceof Error?o.message:"Failed to fetch models";a(u),console.error("Error fetching OpenRouter models:",o)}finally{r(!1)}},[]);return b.useEffect(()=>{s()},[s]),{models:e,loading:n,error:i,refetch:s}}function eKt({open:e,onOpenChange:t,apiKey:n,selectedModels:r,onApiKeyChange:i,onSelectedModelsChange:a,onSave:s,onCancel:o,onRemove:u,isConfigured:c}){const{models:d,loading:f,error:p}=QWt(),[m,y]=b.useState(r);b.useEffect(()=>{y(r)},[r]);const v=()=>{a(m),s(n,m)};return l.jsx(si,{open:e,onOpenChange:t,children:l.jsxs(oi,{className:"max-w-md",children:[l.jsx(vi,{children:l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[l.jsx("div",{className:"w-12 h-12 rounded-lg bg-card p-2 flex items-center justify-center border",children:l.jsx("img",{src:"/openrouter_logo.png",alt:"OpenRouter Logo",className:"w-full h-full object-contain"})}),l.jsxs("div",{children:[l.jsx(yi,{className:"text-left pb-2",children:"Configure OpenRouter"}),l.jsx(us,{className:"text-left",children:"Add your OpenRouter API Key"})]})]})}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{htmlFor:"openrouter-api-key",className:"text-sm font-medium",children:"API Key"}),l.jsx(Ct,{id:"openrouter-api-key",type:"password",value:n,onChange:x=>i(x.target.value),placeholder:"sk-...",className:"mt-1"})]}),l.jsxs("div",{children:[l.jsx("label",{htmlFor:"openrouter-model",className:"text-sm font-medium",children:"Models"}),f?l.jsx("div",{className:"w-full mt-1 p-2 text-sm text-muted-foreground",children:"Loading models..."}):p?l.jsx("div",{className:"w-full mt-1 p-2 text-sm text-destructive",children:p}):l.jsxs(l.Fragment,{children:[l.jsx(JWt,{items:d,placeholder:"Select models...",searchPlaceholder:"Search models...",value:m,onValueChange:y,className:"w-full mt-1"}),m.length>0&&l.jsx("div",{className:"mt-3",children:l.jsx("div",{className:"flex flex-wrap gap-2",children:m.map(x=>{const _=d.find(S=>S.value===x);return l.jsxs(Cn,{variant:"secondary",className:"flex items-center gap-1 pr-1",children:[_?.label||x,l.jsx("button",{type:"button",onClick:()=>{y(S=>S.filter(w=>w!==x))},className:"ml-1 hover:bg-destructive hover:text-destructive-foreground rounded-sm p-0.5 transition-colors",children:l.jsx(Yn,{className:"h-3 w-3"})})]},x)})})}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"We only show models that support tool calling. Select one or more to surface them in the chat."})]})]}),l.jsxs("div",{className:"flex items-center gap-2 p-3 bg-info/10 rounded-lg",children:[l.jsx(Iu,{className:"w-4 h-4 text-info"}),l.jsxs("span",{className:"text-sm text-info",children:["Need help?"," ",l.jsx("button",{type:"button",onClick:()=>window.open("https://openrouter.ai/docs/quickstart","_blank"),className:"underline hover:no-underline",children:"OpenRouter Docs"})]})]})]}),l.jsxs(Js,{className:"flex-row justify-between sm:justify-between",children:[c&&u?l.jsx(Ee,{variant:"ghost",className:"text-destructive hover:text-destructive hover:bg-destructive/10",onClick:u,children:"Remove"}):l.jsx("div",{}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Ee,{variant:"outline",onClick:o,children:"Cancel"}),l.jsx(Ee,{onClick:v,disabled:m.length===0,children:"Save"})]})]})]})})}function tKt({open:e,onOpenChange:t,baseUrl:n,apiKey:r,onBaseUrlChange:i,onApiKeyChange:a,onSave:s,onCancel:o}){return l.jsx(si,{open:e,onOpenChange:t,children:l.jsxs(oi,{className:"max-w-md",children:[l.jsx(vi,{children:l.jsxs("div",{className:"flex items-center gap-3 mb-4",children:[l.jsx("div",{className:"w-12 h-12 rounded-lg bg-card p-2 flex items-center justify-center border",children:l.jsx("img",{src:"/azure_logo.png",alt:"Azure OpenAI Logo",className:"w-full h-full object-contain"})}),l.jsxs("div",{children:[l.jsx(yi,{className:"text-left pb-2",children:"Configure Azure OpenAI"}),l.jsx(us,{className:"text-left",children:"Set up your Azure OpenAI connection"})]})]})}),l.jsxs("div",{className:"space-y-4",children:[l.jsxs("div",{children:[l.jsx("label",{htmlFor:"azure-url",className:"text-sm font-medium",children:"Base URL"}),l.jsx(Ct,{id:"azure-url",type:"url",value:n,onChange:u=>i(u.target.value),placeholder:"https://RESOURCE_NAME.openai.azure.com/openai",className:"mt-1"})]}),l.jsxs("div",{children:[l.jsx("label",{htmlFor:"azure-api-key",className:"text-sm font-medium",children:"API Key"}),l.jsx(Ct,{id:"azure-api-key",type:"password",value:r,onChange:u=>a(u.target.value),placeholder:"Open AI Key",className:"mt-1"})]}),l.jsxs("div",{className:"flex items-center gap-2 p-3 bg-info/10 rounded-lg",children:[l.jsx(Iu,{className:"w-4 h-4 text-info"}),l.jsxs("span",{className:"text-sm text-info",children:["Need help?"," ",l.jsx("button",{onClick:()=>window.open("https://ai-sdk.dev/providers/ai-sdk-providers/azure#chat-models","_blank"),className:"underline hover:no-underline",children:"Azure OpenAI Docs"})]})]})]}),l.jsxs(Js,{children:[l.jsx(Ee,{variant:"outline",onClick:o,children:"Cancel"}),l.jsx(Ee,{onClick:s,disabled:!n.trim(),children:"Save Configuration"})]})]})})}function _me({title:e,children:t}){return l.jsxs("div",{className:"space-y-2",children:[l.jsx("h2",{className:"text-sm font-medium text-muted-foreground",children:e}),l.jsx("div",{className:"space-y-1",children:t})]})}function nKt({label:e,value:t}){return l.jsxs("div",{className:"flex items-center justify-between px-4 py-3 rounded-md border border-border/40",children:[l.jsx("span",{className:"text-sm text-muted-foreground",children:e}),l.jsx("span",{className:"text-sm",children:t})]})}function wme({logo:e,logoAlt:t,name:n,isConfigured:r,onEdit:i,configType:a="api-key"}){const s=a==="base-url"?"Add Base URL":"Add API Key";return l.jsxs("button",{type:"button",onClick:i,className:Ie("w-full flex items-center justify-between px-4 py-3 rounded-md border transition-colors text-left","hover:bg-muted/30 cursor-pointer",r?"border-success/30":"border-border/40"),children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx("img",{src:e,alt:t,className:"size-5 object-contain"}),l.jsx("span",{className:"text-sm font-medium",children:n}),r&&l.jsx(xi,{className:"size-4 text-success"})]}),l.jsx("span",{className:"text-sm text-muted-foreground",children:r?"Edit":s})]})}function rKt(){const{tokens:e,setToken:t,clearToken:n,hasToken:r,getOllamaBaseUrl:i,setOllamaBaseUrl:a,getLiteLLMBaseUrl:s,setLiteLLMBaseUrl:o,getLiteLLMModelAlias:u,setLiteLLMModelAlias:c,getOpenRouterSelectedModels:d,setOpenRouterSelectedModels:f,getAzureBaseUrl:p,setAzureBaseUrl:m,getAnthropicBaseUrl:y,setAnthropicBaseUrl:v,getOpenAIBaseUrl:x,setOpenAIBaseUrl:_}=zx(),[S,w]=b.useState(""),[T,N]=b.useState(!1),[E,A]=b.useState(null),[I,M]=b.useState(!1),[$,O]=b.useState(""),[R,U]=b.useState(!1),[z,F]=b.useState(""),[D,W]=b.useState(""),[q,X]=b.useState(""),[L,Y]=b.useState(!1),[G,P]=b.useState(""),[V,K]=b.useState([]),[Q,oe]=b.useState(!1),[re,ee]=b.useState(""),[le,te]=b.useState(""),[Z,ne]=b.useState(""),J=[{id:"openai",name:"OpenAI",logo:"/openai_logo.png",logoAlt:"OpenAI",description:"GPT-4, GPT-4o, GPT-4o-mini, GPT-4.1, GPT-5",placeholder:"sk-...",getApiKeyUrl:"https://platform.openai.com/api-keys",defaultBaseUrl:"https://api.openai.com/v1"},{id:"anthropic",name:"Anthropic",logo:"/claude_logo.png",logoAlt:"Claude",description:"Claude 3.5, Claude 3.7, Claude Opus 4",placeholder:"sk-ant-...",getApiKeyUrl:"https://console.anthropic.com/",defaultBaseUrl:"https://api.anthropic.com/v1"},{id:"google",name:"Google AI",logo:"/google_logo.png",logoAlt:"Google AI",description:"Gemini 2.5, Gemini 2.5 Flash",placeholder:"AI...",getApiKeyUrl:"https://aistudio.google.com/app/apikey"},{id:"deepseek",name:"DeepSeek",logo:"/deepseek_logo.svg",logoAlt:"DeepSeek",description:"DeepSeek Chat, DeepSeek Reasoner",placeholder:"sk-...",getApiKeyUrl:"https://platform.deepseek.com/api_keys"},{id:"mistral",name:"Mistral AI",logo:"/mistral_logo.png",logoAlt:"Mistral AI",description:"Mistral Large, Mistral Small, Codestral",placeholder:"...",getApiKeyUrl:"https://console.mistral.ai/api-keys/"},{id:"xai",name:"xAI",logo:"/xai_logo.png",logoAlt:"xAI Grok",description:"Grok 3, Grok 3 Mini",placeholder:"xai-...",getApiKeyUrl:"https://console.x.ai/"}],se=[{id:"ollama",name:"Ollama",logo:"/ollama_logo.svg",isConfigured:!!i(),configType:"base-url",onEdit:()=>{O(i()),M(!0)}},{id:"litellm",name:"LiteLLM",logo:"/litellm_logo.png",isConfigured:!!s(),configType:"base-url",onEdit:()=>{F(s()),W(e.litellm||""),X(u()),U(!0)}},{id:"openrouter",name:"OpenRouter",logo:"/openrouter_logo.png",isConfigured:!!e.openrouter,onEdit:()=>{P(e.openrouter||""),K(d()),Y(!0)}},{id:"azure",name:"Azure OpenAI",logo:"/azure_logo.png",isConfigured:!!p(),configType:"base-url",onEdit:()=>{ee(p()),te(e.azure||""),oe(!0)}}],ie=ue=>{switch(ue){case"anthropic":return y();case"openai":return x();default:return""}},he=(ue,fe)=>{switch(ue){case"anthropic":v(fe);break;case"openai":_(fe);break}},ye=ue=>{const fe=J.find(xe=>xe.id===ue);if(fe){A(fe);const xe=e[ue];w(Array.isArray(xe)?xe.join(", "):xe||""),ne(ie(ue)),N(!0)}},Ne=()=>{E&&(t(E.id,S),E.defaultBaseUrl&&he(E.id,Z),N(!1),A(null),w(""),ne(""))},ce=()=>{N(!1),A(null),w(""),ne("")},Te=()=>{a($),M(!1),O("")},we=()=>{M(!1),O("")},Oe=()=>{o(z),t("litellm",D),c(q),U(!1),F(""),W(""),X("")},Ue=()=>{U(!1),F(""),W(""),X("")},Me=(ue,fe)=>{t("openrouter",ue),f(fe),Y(!1)},be=()=>{Y(!1),P(""),K([])},je=()=>{m(re),t("azure",le),oe(!1),ee(""),te("")},Xe=()=>{oe(!1),ee(""),te("")};return l.jsx("div",{className:"h-full overflow-y-auto",children:l.jsxs("div",{className:"p-10 space-y-8 max-w-3xl",children:[l.jsx("h1",{className:"text-2xl font-semibold",children:"Settings"}),l.jsx(_me,{title:"About",children:l.jsx(nKt,{label:"Version",value:"v1.5.14"})}),l.jsxs(_me,{title:"LLM Providers",children:[J.map(ue=>l.jsx(wme,{logo:ue.logo,logoAlt:ue.logoAlt,name:ue.name,isConfigured:r(ue.id),onEdit:()=>ye(ue.id)},ue.id)),se.map(ue=>l.jsx(wme,{logo:ue.logo,logoAlt:ue.name,name:ue.name,isConfigured:ue.isConfigured,onEdit:ue.onEdit,configType:ue.configType},ue.id))]}),l.jsx(ZWt,{open:T,onOpenChange:N,provider:E,value:S,onValueChange:w,baseUrlValue:Z,onBaseUrlChange:ne,onSave:Ne,onCancel:ce,onRemove:()=>{E&&(n(E.id),N(!1),A(null),w(""),ne(""))},isConfigured:E?r(E.id):!1}),l.jsx(YWt,{open:I,onOpenChange:M,value:$,onValueChange:O,onSave:Te,onCancel:we}),l.jsx(XWt,{open:R,onOpenChange:U,baseUrl:z,apiKey:D,modelAlias:q,onBaseUrlChange:F,onApiKeyChange:W,onModelAliasChange:X,onSave:Oe,onCancel:Ue}),l.jsx(tKt,{open:Q,onOpenChange:oe,baseUrl:re,apiKey:le,onBaseUrlChange:ee,onApiKeyChange:te,onSave:je,onCancel:Xe}),l.jsx(eKt,{open:L,onOpenChange:Y,apiKey:G,selectedModels:V,onApiKeyChange:P,onSelectedModelsChange:K,onSave:Me,onCancel:be,onRemove:()=>{n("openrouter"),f([]),Y(!1)},isConfigured:!!e.openrouter})]})})}function iKt(){return l.jsx("div",{className:"flex flex-col h-full",children:l.jsx(QS,{})})}class Dj{constructor(t){this.serverUrl=t,sessionStorage.setItem("debug-oauth-server-url",t)}get redirectUrl(){return`${window.location.origin}/oauth/callback/debug`}get clientMetadata(){return{redirect_uris:[this.redirectUrl],token_endpoint_auth_method:"none",grant_types:["authorization_code","refresh_token"],response_types:["code"],client_name:"MCPJam",client_uri:"https://github.com/mcpjam/inspector"}}async clientInformation(){const t=`debug-client-info-${this.serverUrl}`,n=sessionStorage.getItem(t);if(n)return JSON.parse(n)}saveClientInformation(t){const n=`debug-client-info-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(t))}async tokens(){const t=`debug-tokens-${this.serverUrl}`,n=sessionStorage.getItem(t);if(n)return JSON.parse(n)}saveTokens(t){const n=`debug-tokens-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(t))}redirectToAuthorization(t){}saveCodeVerifier(t){const n=`debug-verifier-${this.serverUrl}`;sessionStorage.setItem(n,t)}codeVerifier(){const t=`debug-verifier-${this.serverUrl}`,n=sessionStorage.getItem(t);if(!n)throw new Error("No code verifier saved for debug session");return n}saveServerMetadata(t){const n=`debug-server-metadata-${this.serverUrl}`;sessionStorage.setItem(n,JSON.stringify(t))}getServerMetadata(){const t=`debug-server-metadata-${this.serverUrl}`,n=sessionStorage.getItem(t);return n?JSON.parse(n):null}clear(){[`debug-client-info-${this.serverUrl}`,`debug-tokens-${this.serverUrl}`,`debug-verifier-${this.serverUrl}`,`debug-server-metadata-${this.serverUrl}`].forEach(n=>sessionStorage.removeItem(n))}}const PN={isInitiatingAuth:!1,oauthTokens:null,oauthStep:"metadata_discovery",oauthMetadata:null,resourceMetadata:null,resourceMetadataError:null,resource:null,authServerUrl:null,oauthClientInfo:null,authorizationUrl:null,authorizationCode:"",latestError:null,statusMessage:null,validationError:null,protocolVersion:"2025-11-25",registrationMethod:null,discoveryType:null,discoveryEndpointUsed:null,pkceSupported:!1},O5e=({open:e,onOpenChange:t,authorizationUrl:n,onAuthorizationComplete:r})=>{const i=b.useRef(null),a=b.useRef(!1);return b.useEffect(()=>{const s=u=>{u.origin===window.location.origin&&u.data?.type==="OAUTH_CALLBACK"&&u.data?.code&&(r?.(),t(!1),a.current=!1)};let o=null;try{o=new BroadcastChannel("oauth_callback_channel"),o.onmessage=u=>{u.data?.type==="OAUTH_CALLBACK"&&u.data?.code&&(r?.(),t(!1),a.current=!1)}}catch(u){console.warn("[OAuth Popup] BroadcastChannel not supported:",u)}return window.addEventListener("message",s),()=>{window.removeEventListener("message",s),o?.close()}},[t,r]),b.useEffect(()=>{if(e&&!a.current){a.current=!0;const s=600,o=700,u=window.screenX+(window.outerWidth-s)/2,c=window.screenY+(window.outerHeight-o)/2,d=`oauth_authorization_${Date.now()}`;console.log("authorizationUrl",n),i.current=window.open(n,d,`width=${s},height=${o},left=${u},top=${c},toolbar=no,location=no,status=no,menubar=no,scrollbars=yes,resizable=yes`);const f=setInterval(()=>{i.current?.closed&&(clearInterval(f),t(!1),a.current=!1)},500);return()=>{clearInterval(f)}}e||(a.current=!1)},[e,n,t]),null},V0=({label:e,isComplete:t,isCurrent:n,error:r,children:i})=>l.jsxs("div",{children:[l.jsxs("div",{className:`flex items-center p-2 rounded-md ${n?"bg-accent":""}`,children:[t?l.jsx(ko,{className:"h-5 w-5 text-success mr-2"}):l.jsx(zm,{className:"h-5 w-5 text-muted-foreground mr-2"}),l.jsx("span",{className:`${n?"font-medium":""}`,children:e})]}),(n||t)&&i&&l.jsx("div",{className:"ml-7 mt-1",children:i}),n&&r&&l.jsxs("div",{className:"ml-7 mt-2 p-3 border border-destructive/30 bg-destructive/10 rounded-md",children:[l.jsx("p",{className:"text-sm font-medium text-destructive",children:"Error:"}),l.jsx("p",{className:"text-xs text-destructive/80 mt-1",children:r.message})]})]}),$N=["metadata_discovery","client_registration","authorization_redirect","authorization_code","token_request","complete"],aKt=({serverUrl:e,flowState:t,updateFlowState:n,proceedToNextStep:r})=>{const i=b.useMemo(()=>new Dj(e),[e]),[a,s]=b.useState(null),[o,u]=b.useState(!1),c=$N.findIndex(f=>f===t.oauthStep);b.useEffect(()=>{const f=async()=>{if(t.oauthClientInfo)s(t.oauthClientInfo);else try{const p=await i.clientInformation();p&&s(p)}catch(p){console.error("Failed to fetch client information:",p)}};c>$N.indexOf("client_registration")&&f()},[i,t.oauthStep,t.oauthClientInfo,c]);const d=f=>({isComplete:c>$N.indexOf(f)||c===$N.length-1,isCurrent:t.oauthStep===f,error:t.oauthStep===f?t.latestError:null});return l.jsxs("div",{className:"rounded-md border p-6 space-y-4 mt-4",children:[l.jsx("h3",{className:"text-lg font-medium",children:"OAuth Flow Progress"}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Follow these steps to complete OAuth authentication with the server."}),l.jsxs("div",{className:"space-y-3",children:[l.jsx(V0,{label:"Metadata Discovery",...d("metadata_discovery"),children:t.oauthMetadata&&l.jsxs("details",{className:"text-xs mt-2",children:[l.jsxs("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:["OAuth Metadata Sources",!t.resourceMetadata&&" ℹ️"]}),t.resourceMetadata&&l.jsxs("div",{className:"mt-2",children:[l.jsx("p",{className:"font-medium",children:"Resource Metadata:"}),l.jsxs("p",{className:"text-xs text-muted-foreground",children:["From"," ",new URL("/.well-known/oauth-protected-resource",e).href]}),l.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(t.resourceMetadata,null,2)})]}),t.resourceMetadataError&&l.jsxs("div",{className:"mt-2 p-3 border border-info/30 bg-info/10 rounded-md",children:[l.jsxs("p",{className:"text-sm font-medium text-info",children:["ℹ️ Problem with resource metadata from"," ",l.jsx("a",{href:new URL("/.well-known/oauth-protected-resource",e).href,target:"_blank",rel:"noopener noreferrer",className:"text-info hover:text-info/80",children:new URL("/.well-known/oauth-protected-resource",e).href})]}),l.jsxs("p",{className:"text-xs text-info/80 mt-1",children:["Resource metadata was added in the"," ",l.jsx("a",{href:"https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#authorization-server-location",target:"_blank",rel:"noopener noreferrer",className:"underline",children:"2025-06-18 specification update"}),l.jsx("br",{}),t.resourceMetadataError.message,t.resourceMetadataError instanceof TypeError&&" (This could indicate the endpoint doesn't exist or does not have CORS configured)"]})]}),t.oauthMetadata&&l.jsxs("div",{className:"mt-2",children:[l.jsx("p",{className:"font-medium",children:"Authorization Server Metadata:"}),t.authServerUrl&&l.jsxs("p",{className:"text-xs text-muted-foreground",children:["From"," ",new URL("/.well-known/oauth-authorization-server",t.authServerUrl).href]}),l.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(t.oauthMetadata,null,2)})]})]})}),l.jsx(V0,{label:"Client Registration",...d("client_registration"),children:a&&l.jsxs("details",{className:"text-xs mt-2",children:[l.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Registered Client Information"}),l.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(a,null,2)})]})}),l.jsx(V0,{label:"Preparing Authorization",...d("authorization_redirect"),children:t.authorizationUrl&&l.jsxs("div",{className:"mt-2 p-3 border rounded-md bg-muted",children:[l.jsx("p",{className:"font-medium mb-2 text-sm",children:"Authorization URL:"}),l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx("p",{className:"text-xs break-all",children:String(t.authorizationUrl)}),l.jsx("button",{onClick:()=>{u(!0)},className:"flex items-center text-info hover:text-info/80","aria-label":"Open authorization URL",title:"Open authorization URL",children:l.jsx(Iu,{className:"h-4 w-4"})})]}),l.jsx("p",{className:"text-xs text-muted-foreground mt-2",children:"Click the link to authorize in your browser. After authorization, you'll be redirected back to continue the flow."})]})}),l.jsx(V0,{label:"Request Authorization and acquire authorization code",...d("authorization_code"),children:l.jsxs("div",{className:"mt-3",children:[l.jsx("label",{htmlFor:"authCode",className:"block text-sm font-medium mb-1",children:"Authorization Code"}),l.jsx("div",{className:"flex gap-2",children:l.jsx("input",{id:"authCode",value:t.authorizationCode,onChange:f=>{n({authorizationCode:f.target.value,validationError:null})},placeholder:"Enter the code from the authorization server",className:`flex h-9 w-full rounded-md border bg-background px-3 py-2 text-sm ring-offset-background file:border-0 file:bg-transparent file:text-sm file:font-medium placeholder:text-muted-foreground focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2 ${t.validationError?"border-destructive":"border-input"}`})}),t.validationError&&l.jsx("p",{className:"text-xs text-destructive mt-1",children:t.validationError}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:"Once you've completed authorization in the link, paste the code here."})]})}),l.jsx(V0,{label:"Token Request",...d("token_request"),children:t.oauthMetadata&&l.jsxs("details",{className:"text-xs mt-2",children:[l.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Token Request Details"}),l.jsxs("div",{className:"mt-2 p-2 bg-muted rounded-md",children:[l.jsx("p",{className:"font-medium",children:"Token Endpoint:"}),l.jsx("code",{className:"block mt-1 text-xs overflow-x-auto",children:t.oauthMetadata.token_endpoint})]})]})}),l.jsx(V0,{label:"Authentication Complete",...d("complete"),children:t.oauthTokens&&l.jsxs("details",{className:"text-xs mt-2",children:[l.jsx("summary",{className:"cursor-pointer text-muted-foreground font-medium",children:"Access Tokens"}),l.jsx("p",{className:"mt-1 text-sm",children:"Authentication successful! You can now use the authenticated connection. These tokens will be used automatically for server requests."}),l.jsx("pre",{className:"mt-2 p-2 bg-muted rounded-md overflow-auto max-h-[300px]",children:JSON.stringify(t.oauthTokens,null,2)})]})})]}),l.jsxs("div",{className:"flex gap-3 mt-4",children:[t.oauthStep!=="complete"&&l.jsx(l.Fragment,{children:l.jsx(Ee,{onClick:r,disabled:t.isInitiatingAuth,children:"Continue"})}),t.oauthStep==="authorization_redirect"&&t.authorizationUrl&&l.jsx(Ee,{variant:"outline",onClick:()=>{u(!0)},children:"Authorize"})]}),t.authorizationUrl&&l.jsx(O5e,{open:o,onOpenChange:u,authorizationUrl:String(t.authorizationUrl)})]})},sKt={metadata_discovery:{canTransition:async()=>!0,execute:async e=>{try{if(e.updateState({latestError:null}),!e.serverUrl)throw new Error("Server URL is required");let t;try{t=new URL(e.serverUrl).toString()}catch{throw new Error(`Invalid server URL: ${e.serverUrl}`)}let n;try{n=new URL("/",t)}catch{throw new Error(`Failed to create base URL from server URL: ${t}`)}let r=null,i=null;try{if(r=await d3(t),r?.authorization_servers?.length){const o=r.authorization_servers[0];try{n=new URL(o)}catch{}}}catch(o){i=o instanceof Error?o:new Error(String(o))}const a=await bct(n.toString());let s=null;try{s=await $Se(t,e.provider,r??void 0)??null}catch{}e.updateState({resourceMetadata:r,resourceMetadataError:i,resource:s,authServerUrl:n,oauthMetadata:a,oauthStep:"client_registration"})}catch(t){const n=t instanceof Error?t:new Error(String(t));e.updateState({latestError:n,statusMessage:{type:"error",message:`Metadata discovery failed: ${n.message}`}})}}},client_registration:{canTransition:async e=>!!e.state.oauthMetadata,execute:async e=>{try{if(e.updateState({latestError:null}),!e.state.oauthMetadata)throw new Error("OAuth metadata not available");let t;try{const n={...e.provider.clientMetadata},r=e.state.resourceMetadata?.scopes_supported||e.state.oauthMetadata.scopes_supported;r&&r.length>0&&(n.scope=r.join(" "));try{t=await zSe(e.serverUrl,{metadata:e.state.oauthMetadata,clientMetadata:n}),e.provider.saveClientInformation(t)}catch(i){if(t=await e.provider.clientInformation(),!t)throw i}}catch{const r=await e.provider.clientInformation();r?t=r:(t={client_id:`static_client_${Date.now()}`,...e.provider.clientMetadata},e.provider.saveClientInformation(t))}e.updateState({oauthClientInfo:t,oauthStep:"authorization_redirect",statusMessage:{type:"success",message:"Client registration completed successfully."}})}catch(t){const n=t instanceof Error?t:new Error(String(t));e.updateState({latestError:n,statusMessage:{type:"error",message:`Client registration failed: ${n.message}`}})}}},authorization_redirect:{canTransition:async e=>!!e.state.oauthMetadata&&!!e.state.oauthClientInfo,execute:async e=>{try{if(e.updateState({latestError:null}),!e.state.oauthMetadata||!e.state.oauthClientInfo)throw new Error("OAuth metadata or client info not available");const t=e.state.resourceMetadata?.scopes_supported||e.state.oauthMetadata.scopes_supported,n=t&&t.length>0?t.join(" "):void 0,r=new Uint8Array(32);crypto.getRandomValues(r);const i=Array.from(r,s=>s.toString(16).padStart(2,"0")).join(""),a=await DSe(e.serverUrl,{metadata:e.state.oauthMetadata,clientInformation:e.state.oauthClientInfo,redirectUrl:e.provider.redirectUrl,scope:n,state:i,resource:e.state.resource??void 0});e.provider.saveCodeVerifier(a.codeVerifier),e.updateState({authorizationUrl:a.authorizationUrl.toString(),oauthStep:"authorization_code",statusMessage:{type:"info",message:"Authorization URL generated. Please complete authorization in your browser."}})}catch(t){const n=t instanceof Error?t:new Error(String(t));e.updateState({latestError:n,statusMessage:{type:"error",message:`Authorization preparation failed: ${n.message}`}})}}},authorization_code:{canTransition:async e=>!!e.state.authorizationCode.trim(),execute:async e=>{try{if(e.updateState({latestError:null,validationError:null}),!e.state.authorizationCode.trim()){e.updateState({validationError:"Authorization code is required"});return}e.updateState({oauthStep:"token_request"})}catch(t){const n=t instanceof Error?t:new Error(String(t));e.updateState({latestError:n,validationError:n.message})}}},token_request:{canTransition:async e=>!!e.state.authorizationCode.trim()&&!!e.state.oauthMetadata,execute:async e=>{try{if(e.updateState({latestError:null}),!e.state.oauthMetadata||!e.state.authorizationCode.trim()||!e.state.oauthClientInfo)throw new Error("OAuth metadata, authorization code, or client info not available");const t=await Sct(e.serverUrl,{metadata:e.state.oauthMetadata,clientInformation:e.state.oauthClientInfo,authorizationCode:e.state.authorizationCode,codeVerifier:e.provider.codeVerifier(),redirectUri:e.provider.redirectUrl});e.updateState({oauthTokens:t,oauthStep:"complete",statusMessage:{type:"success",message:"OAuth authentication completed successfully!"}})}catch(t){const n=t instanceof Error?t:new Error(String(t));e.updateState({latestError:n,statusMessage:{type:"error",message:`Token exchange failed: ${n.message}`}})}}},complete:{canTransition:async()=>!1,execute:async()=>{}}};class oKt{constructor(t){this.context=t}async proceedToNextStep(){const t=this.context.state.oauthStep,n=sKt[t];if(!n)return!1;try{return this.context.updateState({isInitiatingAuth:!0}),await n.canTransition(this.context)?(await n.execute(this.context),!0):!1}catch(r){const i=r instanceof Error?r:new Error(String(r));return this.context.updateState({latestError:i,statusMessage:{type:"error",message:i.message}}),!1}finally{this.context.updateState({isInitiatingAuth:!1})}}reset(){this.context.updateState({isInitiatingAuth:!1,oauthTokens:null,oauthStep:"metadata_discovery",oauthMetadata:null,resourceMetadata:null,resourceMetadataError:null,resource:null,authServerUrl:null,oauthClientInfo:null,authorizationUrl:null,authorizationCode:"",latestError:null,statusMessage:null,validationError:null})}}const lKt=({message:e})=>{let t,n,r;switch(e.type){case"error":t="bg-red-50 dark:bg-red-950/50",n="text-red-700 dark:text-red-400",r="border-red-200 dark:border-red-800";break;case"success":t="bg-green-50 dark:bg-green-950/50",n="text-green-700 dark:text-green-400",r="border-green-200 dark:border-green-800";break;case"info":default:t="bg-blue-50 dark:bg-blue-950/50",n="text-blue-700 dark:text-blue-400",r="border-blue-200 dark:border-blue-800";break}return l.jsx("div",{className:`p-3 rounded-md border ${t} ${r} ${n} mb-4`,children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Gs,{className:"h-4 w-4"}),l.jsx("p",{className:"text-sm",children:e.message})]})})},uKt=({serverConfig:e,serverEntry:t,serverName:n})=>{const[r,i]=b.useState(koe),[a,s]=b.useState(PN),[o,u]=b.useState(!1),c=b.useCallback(A=>{i(I=>({...I,...A}))},[]),d=b.useCallback(A=>{s(I=>({...I,...A}))},[]),f=b.useCallback(()=>{if(u(!1),d(PN),r.serverUrl)try{new Dj(r.serverUrl).clear()}catch(A){console.warn("Failed to clear debug OAuth provider state:",A)}},[r.serverUrl,d]);b.useEffect(()=>{if(e&&e.url&&n){const A=e.url.toString(),I=La(n);c({serverUrl:A,tokens:I,error:null,statusMessage:null})}else c(koe)},[e,n,c]),b.useEffect(()=>{f()},[n,f]);const p=b.useCallback(async()=>{if(!e||!r.serverUrl||!n){c({statusMessage:{type:"error",message:"Please select a server before refreshing tokens"}});return}c({isAuthenticating:!0,error:null,statusMessage:null});try{let A;if(r.tokens)A=await HH(n);else{const I={serverName:n,serverUrl:r.serverUrl};A=await $w(I)}if(A.success){const I=La(n);c({tokens:I,isAuthenticating:!1,statusMessage:{type:"success",message:r.tokens?"Tokens refreshed successfully!":A.serverConfig?"OAuth authentication completed!":"OAuth flow initiated. You will be redirected to authorize access."}}),setTimeout(()=>{c({statusMessage:null})},3e3)}else c({isAuthenticating:!1,error:A.error||"OAuth operation failed",statusMessage:{type:"error",message:`Failed: ${A.error||"OAuth operation failed"}`}})}catch(A){c({isAuthenticating:!1,error:A instanceof Error?A.message:String(A),statusMessage:{type:"error",message:`Failed: ${A instanceof Error?A.message:String(A)}`}})}},[e,r.serverUrl,r.tokens,n,c]),m=b.useCallback(async()=>{if(!e||!r.serverUrl||!n){c({statusMessage:{type:"error",message:"Please select a server before starting OAuth"}});return}c({isAuthenticating:!0,error:null,statusMessage:null});try{uc(n);const A={serverName:n,serverUrl:r.serverUrl},I=await $w(A);if(I.success){const M=La(n);c({tokens:M,isAuthenticating:!1,statusMessage:{type:"success",message:I.serverConfig?"OAuth authentication completed!":"OAuth flow initiated. You will be redirected to authorize access."}}),setTimeout(()=>{c({statusMessage:null})},3e3)}else c({isAuthenticating:!1,error:I.error||"OAuth authentication failed",statusMessage:{type:"error",message:`Failed: ${I.error||"OAuth authentication failed"}`}})}catch(A){c({isAuthenticating:!1,error:A instanceof Error?A.message:String(A),statusMessage:{type:"error",message:`Failed: ${A instanceof Error?A.message:String(A)}`}})}},[e,r.serverUrl,n,c]),y=b.useMemo(()=>{if(!e||!n||!r.serverUrl)return null;const A=new Dj(r.serverUrl);return new oKt({state:a,serverUrl:r.serverUrl,serverName:n,provider:A,updateState:d})},[e,n,r.serverUrl,a,d]),v=b.useCallback(()=>{f(),u(!0),d(PN),y&&y.proceedToNextStep()},[y,d,f]),x=b.useCallback(async()=>{y&&await y.proceedToNextStep()},[y]),_=b.useCallback(()=>{if(u(!1),d(PN),n){const A=La(n);c({tokens:A})}},[n,c,d]),S=b.useCallback(()=>{e&&r.serverUrl&&n&&(uc(n),c({tokens:null,error:null,statusMessage:{type:"success",message:"OAuth tokens cleared successfully"}}),setTimeout(()=>{c({statusMessage:null})},3e3))},[e,r.serverUrl,n,c]),w=e&&"url"in e,T=w,N=n&&(t?.oauthTokens||La(n)||t?.connectionStatus==="oauth-flow"),E=l.jsxs("div",{className:"rounded-md border border-dashed border-primary/30 bg-primary/10 px-3 py-2 text-xs text-primary space-y-1",children:[l.jsxs("div",{children:[l.jsx("span",{className:"font-medium",children:"Help us improve this feature!"})," ","We're looking for contributors to polish up this feature."]}),l.jsx("a",{href:"https://discord.com/invite/JEnDtz8X6z",target:"_blank",rel:"noreferrer",className:"inline-flex items-center gap-1 text-xs font-medium text-primary underline hover:text-primary/80",children:"Join our Discord"})]});return e?T?l.jsx("div",{className:"h-full flex flex-col",children:l.jsxs("div",{className:"h-full flex flex-col bg-background",children:[l.jsx("div",{className:"flex items-center justify-between px-6 py-5 border-b border-border bg-background",children:l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(wn,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Authentication"})]}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage OAuth authentication for the selected server"})]})}),l.jsx("div",{className:"flex-1 overflow-auto px-6 py-6",children:l.jsxs("div",{className:"space-y-6 max-w-2xl",children:[E,l.jsxs("div",{className:"rounded-md border p-4 space-y-2",children:[l.jsx("h3",{className:"text-sm font-medium",children:"Selected Server"}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:[l.jsxs("div",{children:["Name: ",t?.name||"Unknown"]}),w&&l.jsxs("div",{children:["URL: ",e.url.toString()]}),l.jsx("div",{children:"Type: HTTP Server"})]})]}),l.jsxs("div",{className:"rounded-md border p-6 space-y-6",children:[l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(wn,{className:"h-5 w-5"}),l.jsx("h3",{className:"text-lg font-medium",children:"OAuth Authentication"})]}),l.jsx("p",{className:"text-sm text-muted-foreground mb-2",children:N?"Manage OAuth authentication for this server.":"This server supports OAuth authentication. Use Quick OAuth to authenticate and get tokens."}),r.statusMessage&&l.jsx(lKt,{message:r.statusMessage}),r.error&&!r.statusMessage&&l.jsx("div",{className:"p-3 rounded-md border border-red-200 bg-red-50 text-red-700 mb-4",children:l.jsxs("div",{className:"flex items-center gap-2",children:[l.jsx(Gs,{className:"h-4 w-4"}),l.jsx("p",{className:"text-sm",children:r.error})]})}),l.jsxs("div",{className:"space-y-4",children:[r.tokens&&l.jsxs("div",{className:"space-y-2",children:[l.jsx("p",{className:"text-sm font-medium",children:"Current Tokens:"}),l.jsxs("div",{className:"bg-muted p-3 rounded-md space-y-2",children:[l.jsxs("div",{children:[l.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Access Token:"}),l.jsxs("div",{className:"text-xs font-mono overflow-x-auto",children:[r.tokens.access_token.substring(0,40),"..."]})]}),r.tokens.refresh_token&&l.jsxs("div",{children:[l.jsx("p",{className:"text-xs font-medium text-muted-foreground",children:"Refresh Token:"}),l.jsxs("div",{className:"text-xs font-mono overflow-x-auto",children:[r.tokens.refresh_token.substring(0,40),"..."]})]}),l.jsxs("div",{className:"flex gap-4 text-xs text-muted-foreground",children:[l.jsxs("span",{children:["Type: ",r.tokens.token_type]}),r.tokens.expires_in&&l.jsxs("span",{children:["Expires in: ",r.tokens.expires_in,"s"]}),r.tokens.scope&&l.jsxs("span",{children:["Scope: ",r.tokens.scope]})]})]})]}),l.jsxs("div",{className:"flex gap-4",children:[l.jsx(Ee,{onClick:r.tokens?p:m,disabled:r.isAuthenticating||!e,className:"flex items-center gap-2",variant:r.tokens?"outline":"default",children:r.isAuthenticating?l.jsxs(l.Fragment,{children:[l.jsx(wn,{className:"h-4 w-4 animate-spin"}),r.tokens?"Refreshing...":"Authenticating..."]}):l.jsxs(l.Fragment,{children:[l.jsx(wn,{className:"h-4 w-4"}),r.tokens?"Quick Refresh":"Quick OAuth"]})}),r.tokens&&l.jsx(Ee,{onClick:m,disabled:r.isAuthenticating||!e,className:"flex items-center gap-2",variant:"default",children:r.isAuthenticating?l.jsxs(l.Fragment,{children:[l.jsx(wn,{className:"h-4 w-4 animate-spin"}),"Authenticating..."]}):l.jsxs(l.Fragment,{children:[l.jsx(wn,{className:"h-4 w-4"}),"Quick OAuth"]})}),l.jsx(Ee,{variant:"outline",onClick:S,disabled:!e||!r.tokens,children:"Clear Tokens"}),l.jsx(Ee,{variant:"secondary",onClick:v,disabled:r.isAuthenticating||!e,children:"Guided OAuth Flow"})]}),l.jsx("p",{className:"text-xs text-muted-foreground",children:e?r.tokens?"Use Quick Refresh to renew existing tokens, or Quick OAuth to start a fresh authentication flow.":"Use Quick OAuth to authenticate with the server and get tokens.":"Select a server to manage its OAuth authentication."})]}),o&&r.serverUrl&&l.jsx(aKt,{serverUrl:r.serverUrl,flowState:a,updateFlowState:d,proceedToNextStep:x}),o&&l.jsx("div",{className:"mt-4",children:l.jsx(Ee,{variant:"outline",onClick:_,children:"Exit Guided Flow"})})]})]})})]})}):l.jsx("div",{className:"h-full flex flex-col",children:l.jsxs("div",{className:"h-full flex flex-col bg-background",children:[l.jsx("div",{className:"flex items-center justify-between px-6 py-5 border-b border-border bg-background",children:l.jsxs("div",{className:"space-y-2",children:[l.jsxs("div",{className:"flex items-center gap-3",children:[l.jsx(wn,{className:"h-4 w-4 text-muted-foreground"}),l.jsx("h1",{className:"text-lg font-semibold text-foreground",children:"Authentication"})]}),l.jsx("p",{className:"text-sm text-muted-foreground",children:"Manage OAuth authentication for the selected server"})]})}),l.jsx("div",{className:"flex-1 overflow-auto px-6 py-6",children:l.jsxs("div",{className:"space-y-6 max-w-2xl",children:[E,l.jsxs("div",{className:"rounded-md border p-4 space-y-2",children:[l.jsx("h3",{className:"text-sm font-medium",children:"Selected Server"}),l.jsxs("div",{className:"text-xs text-muted-foreground",children:[l.jsxs("div",{children:["Name: ",t?.name||"Unknown"]}),w&&l.jsxs("div",{children:["URL: ",e.url.toString()]}),!w&&l.jsxs("div",{children:["Command: ",e.command]}),l.jsxs("div",{children:["Type: ",w?"HTTP Server":"STDIO Server"]})]})]}),l.jsx(vx,{children:l.jsx(h9e,{className:"pt-6",children:l.jsxs("div",{className:"text-center space-y-4",children:[l.jsx("div",{className:"mx-auto w-12 h-12 bg-muted rounded-full flex items-center justify-center",children:l.jsx(wn,{className:"h-6 w-6 text-muted-foreground"})}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("h3",{className:"text-lg font-medium",children:w?"No Authentication Required":"No OAuth Support"}),l.jsx("p",{className:"text-sm text-muted-foreground max-w-md mx-auto",children:w?`The HTTP server "${t?.name||"Unknown"}" is connected without OAuth authentication.`:"STDIO servers don't support OAuth authentication."}),w&&l.jsx("p",{className:"text-xs text-muted-foreground max-w-md mx-auto mt-2",children:"If this server supports OAuth, you can reconnect it with OAuth enabled from the Servers tab."})]})]})})})]})})]})}):l.jsx(Rc,{icon:lA,title:"No Server Selected",description:"Connect to an MCP server to manage authentication and OAuth settings."})},PZ={isInitiatingAuth:!1,currentStep:"idle",httpHistory:[],infoLogs:[],tokenEndpointAuthMethod:void 0},CC=PZ;function cKt(e,t){return[{id:"request_without_token",label:"MCP request without token",description:"Client makes initial request without authorization",from:"client",to:"mcpServer",details:e.serverUrl?[{label:"POST",value:e.serverUrl},{label:"method",value:"initialize"}]:void 0},{id:"received_401_unauthorized",label:"HTTP 401 Unauthorized with WWW-Authenticate header",description:"Server returns 401 with WWW-Authenticate header",from:"mcpServer",to:"client",details:e.resourceMetadataUrl?[{label:"Note",value:"Extract resource_metadata URL"}]:void 0},{id:"request_resource_metadata",label:"Request Protected Resource Metadata",description:"Client requests metadata from well-known URI",from:"client",to:"mcpServer",details:e.resourceMetadataUrl?[{label:"GET",value:new URL(e.resourceMetadataUrl).pathname}]:void 0},{id:"received_resource_metadata",label:"Return metadata",description:"Server returns OAuth protected resource metadata",from:"mcpServer",to:"client",details:e.resourceMetadata?.authorization_servers?[{label:"Auth Server",value:e.resourceMetadata.authorization_servers[0]}]:void 0},{id:"request_authorization_server_metadata",label:"GET Authorization server metadata endpoint",description:"Try RFC8414 path, then RFC8414 root (no OIDC support)",from:"client",to:"authServer",details:e.authorizationServerUrl?[{label:"URL",value:e.authorizationServerUrl},{label:"Protocol",value:"2025-06-18"}]:void 0},{id:"received_authorization_server_metadata",label:"Authorization server metadata response",description:"Authorization Server returns metadata",from:"authServer",to:"client",details:e.authorizationServerMetadata?[{label:"Token",value:new URL(e.authorizationServerMetadata.token_endpoint).pathname},{label:"Auth",value:new URL(e.authorizationServerMetadata.authorization_endpoint).pathname}]:void 0},...t==="dcr"?[{id:"request_client_registration",label:"POST /register (2025-06-18)",description:"Client registers dynamically with Authorization Server",from:"client",to:"authServer",details:[{label:"Note",value:"Dynamic client registration (DCR)"}]},{id:"received_client_credentials",label:"Client Credentials",description:"Authorization Server returns client ID and credentials",from:"authServer",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."}]:void 0}]:[{id:"received_client_credentials",label:"Use Pre-registered Client (2025-06-18)",description:"Client uses pre-configured credentials (skipped DCR)",from:"client",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."},{label:"Note",value:"Pre-registered (no DCR needed)"}]:[{label:"Note",value:"Pre-registered client credentials"}]}],{id:"generate_pkce_parameters",label:"Generate PKCE parameters",description:"Client generates code verifier and challenge (recommended), includes resource parameter",from:"client",to:"client",details:e.codeChallenge?[{label:"code_challenge",value:e.codeChallenge.substring(0,15)+"..."},{label:"method",value:e.codeChallengeMethod||"S256"},{label:"resource",value:e.serverUrl||"—"},{label:"Protocol",value:"2025-06-18"}]:void 0},{id:"authorization_request",label:"Open browser with authorization URL",description:"Client opens browser with authorization URL + code_challenge + resource",from:"client",to:"browser",details:e.authorizationUrl?[{label:"code_challenge",value:e.codeChallenge?.substring(0,12)+"..."||"S256"},{label:"resource",value:e.serverUrl||""}]:void 0},{id:"browser_to_auth_server",label:"Authorization request with resource parameter",description:"Browser navigates to authorization endpoint",from:"browser",to:"authServer",details:e.authorizationUrl?[{label:"Note",value:"User authorizes in browser"}]:void 0},{id:"auth_redirect_to_browser",label:"Redirect to callback with authorization code",description:"Authorization Server redirects browser back to callback URL",from:"authServer",to:"browser",details:e.authorizationCode?[{label:"code",value:e.authorizationCode.substring(0,20)+"..."}]:void 0},{id:"received_authorization_code",label:"Authorization code callback",description:"Browser redirects back to client with authorization code",from:"browser",to:"client",details:e.authorizationCode?[{label:"code",value:e.authorizationCode.substring(0,20)+"..."}]:void 0},{id:"token_request",label:"Token request + code_verifier + resource",description:"Client exchanges authorization code for access token",from:"client",to:"authServer",details:e.codeVerifier?[{label:"grant_type",value:"authorization_code"},{label:"resource",value:e.serverUrl||""}]:void 0},{id:"received_access_token",label:"Access token (+ refresh token)",description:"Authorization Server returns access token",from:"authServer",to:"client",details:e.accessToken?[{label:"token_type",value:e.tokenType||"Bearer"},{label:"expires_in",value:e.expiresIn?.toString()||"3600"}]:void 0},{id:"authenticated_mcp_request",label:"MCP request with access token",description:"Client makes authenticated request to MCP server",from:"client",to:"mcpServer",details:e.accessToken?[{label:"POST",value:"tools/list"},{label:"Authorization",value:"Bearer "+e.accessToken.substring(0,15)+"..."}]:void 0},{id:"complete",label:"MCP response",description:"MCP Server returns successful response",from:"mcpServer",to:"client",details:e.accessToken?[{label:"Status",value:"200 OK"},{label:"Content",value:"tools, resources, prompts"}]:void 0}]}function Sme(e){const t=new URL(e),n=[];if(t.pathname==="/"||t.pathname==="")n.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString());else{const r=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;n.push(new URL(`/.well-known/oauth-authorization-server${r}`,t.origin).toString()),n.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString())}return n}const dKt=e=>{const{state:t,getState:n,updateState:r,serverUrl:i,serverName:a,redirectUrl:s,fetchFn:o=fetch,customScopes:u,customHeaders:c,registrationStrategy:d="dcr"}=e,f=s||`${window.location.origin}/oauth/callback/debug`,p=(v={})=>({...c,...v}),m=()=>n?n():t,y={state:t,updateState:r,proceedToNextStep:async()=>{const v=m();r({isInitiatingAuth:!0});try{switch(v.currentStep){case"idle":const x=p({"Content-Type":"application/json"}),_={method:"POST",url:i,headers:x,body:{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:1}};r({currentStep:"request_without_token",serverUrl:i,lastRequest:_,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:_}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"request_without_token":if(!v.serverUrl)throw new Error("No server URL available");try{const Z=await ua(v.serverUrl,{method:"POST",headers:p({"Content-Type":"application/json"}),body:JSON.stringify({jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:1})}),ne={status:Z.status,statusText:Z.statusText,headers:Z.headers,body:Z.body},J=[...v.httpHistory||[]];if(J.length>0){const se=J[J.length-1];se.response=ne,se.duration=Date.now()-(se.timestamp||Date.now())}if(Z.status===401){const se=Z.headers["www-authenticate"],ie=se?yn(v,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:se,"Received from":v.serverUrl||"Unknown"}):v.infoLogs;r({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:se||void 0,lastResponse:ne,httpHistory:J,infoLogs:ie,isInitiatingAuth:!1})}else if(Z.status===200){const se=yn(v,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});r({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,lastResponse:ne,httpHistory:J,infoLogs:se,isInitiatingAuth:!1})}else throw r({lastResponse:ne,httpHistory:J}),new Error(`Expected 401 Unauthorized but got HTTP ${Z.status}: ${Z.body?.error?.message||Z.statusText}`)}catch(Z){throw new Error(`Failed to request MCP server: ${Z instanceof Error?Z.message:String(Z)}`)}break;case"received_401_unauthorized":let S;if(v.wwwAuthenticateHeader){const Z=v.wwwAuthenticateHeader.match(/resource_metadata="([^"]+)"/);Z&&(S=Z[1])}if(!S&&v.serverUrl&&(S=USe(v.serverUrl)),!S)throw new Error("Could not determine resource metadata URL");const w={method:"GET",url:S,headers:p({})};r({currentStep:"request_resource_metadata",resourceMetadataUrl:S,lastRequest:w,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:w}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"request_resource_metadata":if(!v.serverUrl)throw new Error("No server URL available");const T=[...v.httpHistory||[]];let N=T.length>0&&T[T.length-1]?.step==="request_resource_metadata"&&!T[T.length-1]?.response?T.pop():void 0;const E=[],A=Z=>Z?Z instanceof Headers?Object.fromEntries(Z.entries()):Array.isArray(Z)?Object.fromEntries(Z):Object.fromEntries(Object.entries(Z).map(([ne,J])=>[ne,String(J)])):{},I=async(Z,ne={})=>{const J=typeof Z=="string"?Z:Z.toString(),se=p(A(ne.headers)),ie=N?{...N,timestamp:Date.now(),request:{method:ne.method||"GET",url:J,headers:se,body:ne.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:ne.method||"GET",url:J,headers:se,body:ne.body}};N=void 0,E.push(ie);try{const he=await ua(J,{method:ne.method||"GET",headers:se,body:ne.body});ie.response={status:he.status,statusText:he.statusText,headers:he.headers,body:he.body},ie.duration=Date.now()-ie.timestamp;const ye={status:he.status,statusText:he.statusText,headers:he.headers},Ne=typeof he.body=="string"?he.body:JSON.stringify(he.body??{});return new Response(Ne,ye)}catch(he){throw ie.error=$d(he),ie.duration=Date.now()-ie.timestamp,he}};try{const Z=v.wwwAuthenticateHeader&&v.resourceMetadataUrl?{resourceMetadataUrl:v.resourceMetadataUrl}:void 0,ne=await d3(v.serverUrl,Z,I),J=[...T,...E],se=E[E.length-1],ie=ne.authorization_servers?.[0]||i,he=yn(v,"received_resource_metadata","authorization-servers","Authorization Servers",{Resource:ne.resource,"Authorization Servers":ne.authorization_servers});r({currentStep:"received_resource_metadata",resourceMetadata:ne,resourceMetadataUrl:se?.request?.url||v.resourceMetadataUrl,authorizationServerUrl:ie,lastRequest:se?.request,lastResponse:se?.response,httpHistory:J,infoLogs:he,isInitiatingAuth:!1})}catch(Z){const ne=Rw([...T,...E],$d(Z));throw r({lastResponse:E[E.length-1]?.response,httpHistory:ne}),new Error(`Failed to request resource metadata: ${Z instanceof Error?Z.message:String(Z)}`)}break;case"received_resource_metadata":if(!v.authorizationServerUrl)throw new Error("No authorization server URL available");const $={method:"GET",url:Sme(v.authorizationServerUrl)[0],headers:p({})};r({currentStep:"request_authorization_server_metadata",lastRequest:$,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:$}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"request_authorization_server_metadata":if(!v.authorizationServerUrl)throw new Error("No authorization server URL available");const O=Sme(v.authorizationServerUrl);let R=null,U=null,z="",F={},D={},W=null;for(const Z of O)try{const ne=p({}),J=[...v.httpHistory||[]];J.length>0&&(J[J.length-1].request={method:"GET",url:Z,headers:ne}),r({lastRequest:{method:"GET",url:Z,headers:ne},httpHistory:J});const se=await ua(Z,{method:"GET",headers:p({})});if(se.ok){R=se.body,z=Z,F=ne,D=se.headers,W=se;break}else{if(se.status>=400&&se.status<500)continue;U=new Error(`HTTP ${se.status} from ${Z}`)}}catch(ne){U=ne;continue}if(!R||!W)throw new Error(`Could not discover authorization server metadata. Last error: ${U instanceof Error?U.message:String(U)}`);if(!R.issuer)throw new Error("Authorization server metadata missing required 'issuer' field");if(!R.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!R.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!R.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const q={status:W.status,statusText:W.statusText,headers:D,body:R},X=[...v.httpHistory||[]];X.length>0&&(X[X.length-1].response=q);const L=R.code_challenge_methods_supported||[],Y={Issuer:R.issuer,"Authorization Endpoint":R.authorization_endpoint,"Token Endpoint":R.token_endpoint};R.registration_endpoint&&(Y["Registration Endpoint"]=R.registration_endpoint),R.code_challenge_methods_supported&&(Y["PKCE Methods"]=R.code_challenge_methods_supported),R.grant_types_supported&&(Y["Grant Types"]=R.grant_types_supported),R.response_types_supported&&(Y["Response Types"]=R.response_types_supported),R.scopes_supported&&(Y.Scopes=R.scopes_supported);const G=yn(m(),"received_authorization_server_metadata","as-metadata","Authorization Server Metadata",Y);L.includes("S256")?r({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:R,lastResponse:q,httpHistory:X,infoLogs:G,isInitiatingAuth:!1}):(console.warn("Authorization server may not support S256 PKCE method. Supported methods:",L),r({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:R,lastResponse:q,httpHistory:X,infoLogs:G,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1}));break;case"received_authorization_server_metadata":if(!v.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(d==="preregistered"){const{clientId:Z,clientSecret:ne}=FH(a);if(!Z){r({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const J={"Client ID":Z,"Client Secret":ne?"Configured":"Not provided (public client)","Token Auth Method":ne?"client_secret_post":"none",Note:"Using pre-registered client credentials from server config (skipped DCR)"},se=yn(m(),"received_client_credentials","dcr","Pre-registered Client",J);r({currentStep:"received_client_credentials",clientId:Z,clientSecret:ne||void 0,tokenEndpointAuthMethod:ne?"client_secret_post":"none",infoLogs:se,isInitiatingAuth:!1})}else if(v.authorizationServerMetadata.registration_endpoint){const Z=v.resourceMetadata?.scopes_supported||v.authorizationServerMetadata.scopes_supported,ne={client_name:"MCPJam Inspector Debug Client",redirect_uris:[f],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"};Z&&Z.length>0&&(ne.scope=Z.join(" "));const J={method:"POST",url:v.authorizationServerMetadata.registration_endpoint,headers:p({"Content-Type":"application/json"}),body:ne};r({currentStep:"request_client_registration",lastRequest:J,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:J}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return}else r({currentStep:"generate_pkce_parameters",clientId:"mock-client-id-for-demo",tokenEndpointAuthMethod:"none",isInitiatingAuth:!1});break;case"request_client_registration":if(!v.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!v.lastRequest?.body)throw new Error("No client metadata in request");try{const Z=await ua(v.authorizationServerMetadata.registration_endpoint,{method:"POST",headers:p({"Content-Type":"application/json"}),body:JSON.stringify(v.lastRequest.body)}),ne={status:Z.status,statusText:Z.statusText,headers:Z.headers,body:Z.body},J=[...v.httpHistory||[]];if(J.length>0){const se=J[J.length-1];se.response=ne,se.duration=Date.now()-(se.timestamp||Date.now())}if(!Z.ok)r({lastResponse:ne,httpHistory:J,error:`Dynamic Client Registration failed (${Z.status}). Using fallback client ID.`}),r({currentStep:"received_client_credentials",clientId:"preregistered-client-id",clientSecret:void 0,tokenEndpointAuthMethod:"none",isInitiatingAuth:!1});else{const se=Z.body,ie={"Client ID":se.client_id,"Client Name":se.client_name,"Token Auth Method":se.token_endpoint_auth_method||"none","Redirect URIs":se.redirect_uris,"Grant Types":se.grant_types,"Response Types":se.response_types};se.client_secret&&(ie["Client Secret"]=se.client_secret.substring(0,20)+"...",ie.Note="Server issued client_secret - this will be used in token requests");const he=yn(m(),"received_client_credentials","dcr","Dynamic Client Registration",ie);r({currentStep:"received_client_credentials",clientId:se.client_id,clientSecret:se.client_secret,tokenEndpointAuthMethod:se.token_endpoint_auth_method||"none",lastResponse:ne,httpHistory:J,infoLogs:he,error:void 0,isInitiatingAuth:!1})}}catch(Z){const ne={status:0,statusText:"Network Error",headers:p({}),body:{error:Z instanceof Error?Z.message:String(Z)}},J=[...v.httpHistory||[]];if(J.length>0){const ie=J[J.length-1];ie.response=ne,ie.duration=Date.now()-(ie.timestamp||Date.now())}r({lastResponse:ne,httpHistory:J,error:`Client registration failed: ${Z instanceof Error?Z.message:String(Z)}. Using fallback.`}),r({currentStep:"received_client_credentials",clientId:"preregistered-client-id",clientSecret:void 0,tokenEndpointAuthMethod:"none",isInitiatingAuth:!1})}break;case"received_client_credentials":const P=Vm(43),V=await UH(P),K=yn(m(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:V,method:"S256",resource:v.serverUrl||"Unknown"});r({currentStep:"generate_pkce_parameters",codeVerifier:P,codeChallenge:V,codeChallengeMethod:"S256",state:Vm(16),infoLogs:K,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!v.authorizationServerMetadata?.authorization_endpoint||!v.clientId)throw new Error("Missing authorization endpoint or client ID");const Q=new URL(v.authorizationServerMetadata.authorization_endpoint);if(Q.searchParams.set("response_type","code"),Q.searchParams.set("client_id",v.clientId),Q.searchParams.set("redirect_uri",f),Q.searchParams.set("code_challenge",v.codeChallenge||""),Q.searchParams.set("code_challenge_method","S256"),Q.searchParams.set("state",v.state||""),v.serverUrl&&Q.searchParams.set("resource",v.serverUrl),u)Q.searchParams.set("scope",u);else{const Z=v.resourceMetadata?.scopes_supported||v.authorizationServerMetadata.scopes_supported,ne=new Set;Z&&Z.length>0&&Z.forEach(J=>ne.add(J)),Z?.includes("offline_access")&&ne.add("offline_access"),ne.size>0&&Q.searchParams.set("scope",Array.from(ne).join(" "))}const oe=yn(m(),"authorization_request","auth-url","Authorization URL",{url:Q.toString()});r({currentStep:"authorization_request",authorizationUrl:Q.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:oe,isInitiatingAuth:!1});break;case"authorization_request":r({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":if(!v.authorizationCode||v.authorizationCode.trim()===""){r({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!v.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const re={grant_type:"authorization_code",code:v.authorizationCode,redirect_uri:f};v.clientId&&(re.client_id=v.clientId),v.clientSecret&&(re.client_secret=v.clientSecret),v.codeVerifier&&(re.code_verifier=v.codeVerifier),v.serverUrl&&(re.resource=v.serverUrl);const ee={method:"POST",url:v.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded"},body:re};r({currentStep:"token_request",lastRequest:ee,lastResponse:void 0,accessToken:void 0,refreshToken:void 0,httpHistory:[...v.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:ee}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"token_request":if(!v.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!v.authorizationCode)throw new Error("Missing authorization code");if(!v.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const Z=new URLSearchParams({grant_type:"authorization_code",code:v.authorizationCode,redirect_uri:f,client_id:v.clientId||"",code_verifier:v.codeVerifier||""});v.clientSecret&&Z.set("client_secret",v.clientSecret),v.serverUrl&&Z.set("resource",v.serverUrl);const ne=await ua(v.authorizationServerMetadata.token_endpoint,{method:"POST",headers:p({"Content-Type":"application/x-www-form-urlencoded"}),body:Z.toString()}),J={status:ne.status,statusText:ne.statusText,headers:ne.headers,body:ne.body},se=[...v.httpHistory||[]];if(se.length>0){const Ne=se[se.length-1];Ne.response=J,Ne.duration=Date.now()-(Ne.timestamp||Date.now())}if(!ne.ok){r({lastResponse:J,httpHistory:se,authorizationCode:void 0,error:`Token request failed: ${ne.body?.error||ne.statusText} - ${ne.body?.error_description||"Unknown error"}`,isInitiatingAuth:!1});return}const ie=ne.body;let ye=(m().infoLogs||[]).filter(Ne=>Ne.id!=="auth-code"&&Ne.id!=="oauth-tokens"&&Ne.id!=="token");if(v.authorizationCode&&(ye=[...ye,{id:"auth-code",step:"token_request",level:"info",label:"Authorization Code",data:{code:v.authorizationCode},timestamp:Date.now()}]),ie.access_token){const Ne={access_token:ie.access_token};ie.refresh_token&&(Ne.refresh_token=ie.refresh_token),ye=[...ye,{id:"oauth-tokens",step:"token_request",level:"info",label:"OAuth Tokens",data:Ne,timestamp:Date.now()}]}if(ie.access_token){const Ne=Gm(ie.access_token);if(Ne){const ce={...Ne};ce.exp&&(ce.exp=`${ce.exp} (${Ji(ce.exp)})`),ce.iat&&(ce.iat=`${ce.iat} (${Ji(ce.iat)})`),ce.nbf&&(ce.nbf=`${ce.nbf} (${Ji(ce.nbf)})`);const Te={...ce};if(ce.aud){const we=v.serverUrl,Ue=(Array.isArray(ce.aud)?ce.aud:[ce.aud]).some(Me=>Me===we);Te._validation={expected_audience:we,audience_matches:Ue,note:Ue?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Te._validation={note:"⚠ No audience claim found - server should validate token binding"};ye=[...ye,{id:"token",step:"token_request",level:"info",label:"Access Token (Decoded JWT)",data:Te,timestamp:Date.now()}]}}if(ie.id_token){const Ne=Gm(ie.id_token);if(Ne){const ce={...Ne};ce.exp&&(ce.exp=`${ce.exp} (${Ji(ce.exp)})`),ce.iat&&(ce.iat=`${ce.iat} (${Ji(ce.iat)})`),ce.nbf&&(ce.nbf=`${ce.nbf} (${Ji(ce.nbf)})`),ce.auth_time&&(ce.auth_time=`${ce.auth_time} (${Ji(ce.auth_time)})`),ce._note="OIDC ID Token - Used for user identity verification",ye=[...ye,{id:"id-token",step:"token_request",level:"info",label:"ID Token (OIDC - Decoded JWT)",data:ce,timestamp:Date.now()}]}}r({currentStep:"received_access_token",accessToken:ie.access_token,refreshToken:ie.refresh_token,tokenType:ie.token_type||"Bearer",expiresIn:ie.expires_in,lastResponse:J,httpHistory:se,infoLogs:ye,error:void 0,isInitiatingAuth:!1})}catch(Z){const ne={status:0,statusText:"Network Error",headers:p({}),body:{error:Z instanceof Error?Z.message:String(Z)}},J=[...v.httpHistory||[]];if(J.length>0){const se=J[J.length-1];se.response=ne,se.duration=Date.now()-(se.timestamp||Date.now())}r({lastResponse:ne,httpHistory:J,error:`Token exchange failed: ${Z instanceof Error?Z.message:String(Z)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!v.serverUrl||!v.accessToken)throw new Error("Missing server URL or access token");const le={method:"POST",url:v.serverUrl,headers:{Authorization:`Bearer ${v.accessToken}`,"Content-Type":"application/json","MCP-Protocol-Version":"2025-06-18"},body:{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2025-06-18",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:2}},te=yn(m(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-06-18",Client:"MCPJam Inspector v1.0.0",Endpoint:v.serverUrl});r({currentStep:"authenticated_mcp_request",lastRequest:le,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:le}],infoLogs:te,isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"authenticated_mcp_request":if(!v.serverUrl||!v.accessToken)throw new Error("Missing server URL or access token");try{const Z=await ua(v.serverUrl,{method:"POST",headers:p({Authorization:`Bearer ${v.accessToken}`,"Content-Type":"application/json"}),body:JSON.stringify({jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:2})}),ne={status:Z.status,statusText:Z.statusText,headers:Z.headers,body:Z.body},J=[...v.httpHistory||[]];if(J.length>0){const Ne=J[J.length-1];Ne.response=ne,Ne.duration=Date.now()-(Ne.timestamp||Date.now())}if(!Z.ok){r({lastResponse:ne,httpHistory:J,error:`Authenticated request failed: ${Z.status} ${Z.statusText}`,isInitiatingAuth:!1});return}let se=m().infoLogs||[];const ie=Z.headers["content-type"]||"",he=ie.includes("text/event-stream");let ye=null;if(he&&Z.body?.transport==="sse"?ye=Z.body.mcpResponse:ye=Z.body,he&&ye?.result?.protocolVersion){const Ne={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":ye.result.protocolVersion};ye.result.serverInfo&&(Ne["Server Name"]=ye.result.serverInfo.name,Ne["Server Version"]=ye.result.serverInfo.version),ye.result.capabilities&&(Ne.Capabilities=ye.result.capabilities),se=yn(m(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",Ne)}else if(he)se=yn(m(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":ie,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:Z.body?.events?`${Z.body.events.length} events parsed`:"No events parsed"});else if(ye?.result?.protocolVersion){const Ne={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":ye.result.protocolVersion};ye.result.serverInfo&&(Ne["Server Name"]=ye.result.serverInfo.name,Ne["Server Version"]=ye.result.serverInfo.version),ye.result.capabilities&&(Ne.Capabilities=ye.result.capabilities),se=yn(m(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",Ne)}r({currentStep:"complete",lastResponse:ne,httpHistory:J,infoLogs:se,error:void 0,isInitiatingAuth:!1})}catch(Z){const ne=$d(Z),J={status:0,statusText:"Network Error",headers:p({}),body:{error:ne.message,details:ne.details}},se=[...v.httpHistory||[]];if(se.length>0){const ye={...se[se.length-1],response:J,duration:Date.now()-(se[se.length-1]?.timestamp||Date.now()),error:ne};se[se.length-1]=ye}const ie=m(),he=yn(ie,"authenticated_mcp_request",`error-authenticated_mcp_request-${Date.now()}`,"Authenticated MCP request failed",{request:ie.lastRequest,error:ne},{level:"error",error:ne});r({lastResponse:J,httpHistory:se,infoLogs:he,error:`Authenticated MCP request failed: ${ne.message}`,isInitiatingAuth:!1})}break;case"complete":r({isInitiatingAuth:!1});break;default:r({isInitiatingAuth:!1});break}}catch(x){const _=m(),S=$d(x),w=yn(_,_.currentStep,`error-${_.currentStep}-${Date.now()}`,"Step failed",{step:_.currentStep,request:_.lastRequest,response:_.lastResponse,error:S},{level:"error",error:S}),T=Rw(_.httpHistory,S),N={error:S.message,infoLogs:w,isInitiatingAuth:!1};T&&(N.httpHistory=T),r(N)}},startGuidedFlow:async()=>{r({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{r({...CC,lastRequest:void 0,lastResponse:void 0,httpHistory:[],infoLogs:[],authorizationCode:void 0,authorizationUrl:void 0,accessToken:void 0,refreshToken:void 0,codeVerifier:void 0,codeChallenge:void 0,error:void 0})}};return y},fKt=PZ;function pKt(e,t){return[{id:"request_authorization_server_metadata",label:"GET /.well-known/oauth-authorization-server from MCP base URL",description:"Direct discovery from MCP server base URL with fallback to /authorize, /token, /register",from:"client",to:"authServer",details:e.authorizationServerUrl?[{label:"URL",value:e.authorizationServerUrl},{label:"Protocol",value:"2025-03-26"}]:void 0},{id:"received_authorization_server_metadata",label:"Authorization server metadata response",description:"Authorization Server returns metadata",from:"authServer",to:"client",details:e.authorizationServerMetadata?[{label:"Token",value:new URL(e.authorizationServerMetadata.token_endpoint).pathname},{label:"Auth",value:new URL(e.authorizationServerMetadata.authorization_endpoint).pathname}]:void 0},...t==="dcr"?[{id:"request_client_registration",label:"POST /register (2025-03-26)",description:"Client registers dynamically with Authorization Server",from:"client",to:"authServer",details:[{label:"Note",value:"Dynamic client registration (DCR)"}]},{id:"received_client_credentials",label:"Client Credentials",description:"Authorization Server returns client ID and credentials",from:"authServer",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."}]:void 0}]:[{id:"received_client_credentials",label:"Use Pre-registered Client (2025-03-26)",description:"Client uses pre-configured credentials (skipped DCR)",from:"client",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."},{label:"Note",value:"Pre-registered (no DCR needed)"}]:[{label:"Note",value:"Pre-registered client credentials"}]}],{id:"generate_pkce_parameters",label:"Generate PKCE parameters",description:"Client generates code verifier and challenge (recommended), includes resource parameter",from:"client",to:"client",details:e.codeChallenge?[{label:"code_challenge",value:e.codeChallenge.substring(0,15)+"..."},{label:"method",value:e.codeChallengeMethod||"S256"},{label:"resource",value:e.serverUrl||"—"},{label:"Protocol",value:"2025-03-26"}]:void 0},{id:"authorization_request",label:"Open browser with authorization URL",description:"Client opens browser with authorization URL + code_challenge + resource",from:"client",to:"browser",details:e.authorizationUrl?[{label:"code_challenge",value:e.codeChallenge?.substring(0,12)+"..."||"S256"},{label:"resource",value:e.serverUrl||""}]:void 0},{id:"browser_to_auth_server",label:"Authorization request with resource parameter",description:"Browser navigates to authorization endpoint",from:"browser",to:"authServer",details:e.authorizationUrl?[{label:"Note",value:"User authorizes in browser"}]:void 0},{id:"auth_redirect_to_browser",label:"Redirect to callback with authorization code",description:"Authorization Server redirects browser back to callback URL",from:"authServer",to:"browser",details:e.authorizationCode?[{label:"code",value:e.authorizationCode.substring(0,20)+"..."}]:void 0},{id:"received_authorization_code",label:"Authorization code callback",description:"Browser redirects back to client with authorization code",from:"browser",to:"client",details:e.authorizationCode?[{label:"code",value:e.authorizationCode.substring(0,20)+"..."}]:void 0},{id:"token_request",label:"Token request + code_verifier + resource",description:"Client exchanges authorization code for access token",from:"client",to:"authServer",details:e.codeVerifier?[{label:"grant_type",value:"authorization_code"},{label:"resource",value:e.serverUrl||""}]:void 0},{id:"received_access_token",label:"Access token (+ refresh token)",description:"Authorization Server returns access token",from:"authServer",to:"client",details:e.accessToken?[{label:"token_type",value:e.tokenType||"Bearer"},{label:"expires_in",value:e.expiresIn?.toString()||"3600"}]:void 0},{id:"authenticated_mcp_request",label:"MCP request with access token",description:"Client makes authenticated request to MCP server",from:"client",to:"mcpServer",details:e.accessToken?[{label:"POST",value:"tools/list"},{label:"Authorization",value:"Bearer "+e.accessToken.substring(0,15)+"..."}]:void 0},{id:"complete",label:"MCP response",description:"MCP Server returns successful response",from:"mcpServer",to:"client",details:e.accessToken?[{label:"Status",value:"200 OK"},{label:"Content",value:"tools, resources, prompts"}]:void 0}]}function hKt(e){return new URL(e).origin}function kme(e){const t=new URL(e),n=[];if(t.pathname==="/"||t.pathname==="")n.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString());else{const r=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;n.push(new URL(`/.well-known/oauth-authorization-server${r}`,t.origin).toString()),n.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString())}return n}const mKt=e=>{const{state:t,getState:n,updateState:r,serverUrl:i,serverName:a,redirectUrl:s,fetchFn:o=fetch,customScopes:u,customHeaders:c,registrationStrategy:d="dcr"}=e,f=s||`${window.location.origin}/oauth/callback/debug`,p=(v={})=>({...c,...v}),m=()=>n?n():t,y={state:t,updateState:r,proceedToNextStep:async()=>{const v=m();r({isInitiatingAuth:!0});try{switch(v.currentStep){case"idle":r({currentStep:"discovery_start",serverUrl:i,httpHistory:[],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"request_without_token":if(!v.serverUrl)throw new Error("No server URL available");try{const G=await ua(v.serverUrl,{method:"POST",headers:p({"Content-Type":"application/json"}),body:JSON.stringify({jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCP Inspector",version:"1.0.0"}},id:1})}),P={status:G.status,statusText:G.statusText,headers:G.headers,body:G.body},V=[...v.httpHistory||[]];if(V.length>0){const K=V[V.length-1];K.response=P,K.duration=Date.now()-(K.timestamp||Date.now())}if(G.status===401||G.status===200){const K=G.status===200?yn(v,"discovery_start","optional-auth","Optional Authentication",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"}):v.infoLogs;r({currentStep:"discovery_start",lastResponse:P,httpHistory:V,infoLogs:K,isInitiatingAuth:!1})}else throw r({lastResponse:P,httpHistory:V}),new Error(`Expected 401 or 200 but got HTTP ${G.status}: ${G.body?.error?.message||G.statusText}`)}catch(G){throw new Error(`Failed to request MCP server: ${G instanceof Error?G.message:String(G)}`)}break;case"discovery_start":const x=hKt(v.serverUrl),S={method:"GET",url:kme(x)[0],headers:p({})};r({currentStep:"request_authorization_server_metadata",authorizationServerUrl:x,lastRequest:S,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:S}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"request_authorization_server_metadata":if(!v.authorizationServerUrl)throw new Error("No authorization server URL available");const w=kme(v.authorizationServerUrl);let T=null,N=null,E="",A=null;for(const G of w)try{const P=p({}),V=[...v.httpHistory||[]];V.length>0&&(V[V.length-1].request={method:"GET",url:G,headers:P}),r({lastRequest:{method:"GET",url:G,headers:P},httpHistory:V});const K=await ua(G,{method:"GET",headers:p({"MCP-Protocol-Version":"2025-03-26"})});if(K.ok){T=K.body,E=G,A=K;break}else{if(K.status>=400&&K.status<500)continue;N=new Error(`HTTP ${K.status} from ${G}`)}}catch(P){N=P;continue}if(!T){const G=v.authorizationServerUrl;T={issuer:G,authorization_endpoint:`${G}/authorize`,token_endpoint:`${G}/token`,registration_endpoint:`${G}/register`,response_types_supported:["code"],grant_types_supported:["authorization_code","refresh_token"],code_challenge_methods_supported:["S256"]};const P=yn(m(),"received_authorization_server_metadata","fallback-endpoints","Using Fallback Endpoints",{Note:"Metadata discovery failed, using default endpoints per 2025-03-26 spec","Authorization Endpoint":T.authorization_endpoint,"Token Endpoint":T.token_endpoint,"Registration Endpoint":T.registration_endpoint});r({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:T,infoLogs:P,isInitiatingAuth:!1});break}if(!T.issuer)throw new Error("Authorization server metadata missing required 'issuer' field");if(!T.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!T.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!T.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const I={status:A.status,statusText:A.statusText,headers:A.headers,body:T},M=[...v.httpHistory||[]];if(M.length>0){const G=M[M.length-1];G.response=I,G.duration=Date.now()-(G.timestamp||Date.now())}const $=T.code_challenge_methods_supported||[],O={Issuer:T.issuer,"Authorization Endpoint":T.authorization_endpoint,"Token Endpoint":T.token_endpoint};T.registration_endpoint&&(O["Registration Endpoint"]=T.registration_endpoint),T.code_challenge_methods_supported&&(O["PKCE Methods"]=T.code_challenge_methods_supported),T.grant_types_supported&&(O["Grant Types"]=T.grant_types_supported),T.response_types_supported&&(O["Response Types"]=T.response_types_supported),T.scopes_supported&&(O.Scopes=T.scopes_supported);const R=yn(m(),"received_authorization_server_metadata","as-metadata","Authorization Server Metadata",O);(!$||$.length===0||!$.includes("S256"))&&console.warn("Authorization server may not support PKCE S256 (REQUIRED for 2025-03-26 spec)"),r({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:T,lastResponse:I,httpHistory:M,infoLogs:R,isInitiatingAuth:!1});break;case"received_authorization_server_metadata":if(!v.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(d==="preregistered"){const{clientId:G,clientSecret:P}=FH(a);if(!G){r({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const V={"Client ID":G,"Client Secret":P?"Configured":"Not provided (public client)","Token Auth Method":P?"client_secret_post":"none",Note:"Using pre-registered client credentials (skipped DCR)"},K=yn(m(),"received_client_credentials","dcr","Pre-registered Client",V);r({currentStep:"received_client_credentials",clientId:G,clientSecret:P||void 0,tokenEndpointAuthMethod:P?"client_secret_post":"none",infoLogs:K,isInitiatingAuth:!1})}else if(v.authorizationServerMetadata.registration_endpoint){const G=v.authorizationServerMetadata.scopes_supported,P={client_name:"MCP Inspector Debug Client",redirect_uris:[f],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"};G&&G.length>0&&(P.scope=G.join(" "));const V={method:"POST",url:v.authorizationServerMetadata.registration_endpoint,headers:p({"Content-Type":"application/json"}),body:P};r({currentStep:"request_client_registration",lastRequest:V,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:V}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return}else r({currentStep:"generate_pkce_parameters",clientId:"mock-client-id-for-demo",tokenEndpointAuthMethod:"none",isInitiatingAuth:!1});break;case"request_client_registration":if(!v.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!v.lastRequest?.body)throw new Error("No client metadata in request");try{const G=await ua(v.authorizationServerMetadata.registration_endpoint,{method:"POST",headers:p({"Content-Type":"application/json"}),body:JSON.stringify(v.lastRequest.body)}),P={status:G.status,statusText:G.statusText,headers:G.headers,body:G.body},V=[...v.httpHistory||[]];if(V.length>0){const K=V[V.length-1];K.response=P,K.duration=Date.now()-(K.timestamp||Date.now())}if(!G.ok)r({lastResponse:P,httpHistory:V,error:`Dynamic Client Registration failed (${G.status}). Using fallback client ID.`}),r({currentStep:"received_client_credentials",clientId:"preregistered-client-id",clientSecret:void 0,tokenEndpointAuthMethod:"none",isInitiatingAuth:!1});else{const K=G.body,Q={"Client ID":K.client_id,"Client Name":K.client_name,"Token Auth Method":K.token_endpoint_auth_method||"none","Redirect URIs":K.redirect_uris,"Grant Types":K.grant_types,"Response Types":K.response_types};K.client_secret&&(Q["Client Secret"]=K.client_secret.substring(0,20)+"...",Q.Note="Server issued client_secret - this will be used in token requests");const oe=yn(m(),"received_client_credentials","dcr","Dynamic Client Registration",Q);r({currentStep:"received_client_credentials",clientId:K.client_id,clientSecret:K.client_secret,tokenEndpointAuthMethod:K.token_endpoint_auth_method||"none",lastResponse:P,httpHistory:V,infoLogs:oe,error:void 0,isInitiatingAuth:!1})}}catch(G){const P={status:0,statusText:"Network Error",headers:p({}),body:{error:G instanceof Error?G.message:String(G)}},V=[...v.httpHistory||[]];if(V.length>0){const Q=V[V.length-1];Q.response=P,Q.duration=Date.now()-(Q.timestamp||Date.now())}r({lastResponse:P,httpHistory:V,error:`Client registration failed: ${G instanceof Error?G.message:String(G)}. Using fallback.`}),r({currentStep:"received_client_credentials",clientId:"preregistered-client-id",clientSecret:void 0,tokenEndpointAuthMethod:"none",isInitiatingAuth:!1})}break;case"received_client_credentials":const U=Vm(43),z=await UH(U),F=yn(m(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters (REQUIRED)",{code_challenge:z,method:"S256",resource:v.serverUrl||"Unknown",note:"PKCE is REQUIRED for all clients in 2025-03-26 spec"});r({currentStep:"generate_pkce_parameters",codeVerifier:U,codeChallenge:z,codeChallengeMethod:"S256",state:Vm(16),infoLogs:F,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!v.authorizationServerMetadata?.authorization_endpoint||!v.clientId)throw new Error("Missing authorization endpoint or client ID");const D=new URL(v.authorizationServerMetadata.authorization_endpoint);if(D.searchParams.set("response_type","code"),D.searchParams.set("client_id",v.clientId),D.searchParams.set("redirect_uri",f),D.searchParams.set("code_challenge",v.codeChallenge||""),D.searchParams.set("code_challenge_method","S256"),D.searchParams.set("state",v.state||""),v.serverUrl&&D.searchParams.set("resource",v.serverUrl),u)D.searchParams.set("scope",u);else{const G=v.authorizationServerMetadata.scopes_supported,P=new Set;G&&G.length>0&&G.forEach(V=>P.add(V)),G?.includes("offline_access")&&P.add("offline_access"),P.size>0&&D.searchParams.set("scope",Array.from(P).join(" "))}const W=yn(m(),"authorization_request","auth-url","Authorization URL",{url:D.toString()});r({currentStep:"authorization_request",authorizationUrl:D.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:W,isInitiatingAuth:!1});break;case"authorization_request":r({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":if(!v.authorizationCode||v.authorizationCode.trim()===""){r({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!v.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const q={grant_type:"authorization_code",code:v.authorizationCode,redirect_uri:f};v.clientId&&(q.client_id=v.clientId),v.clientSecret&&(q.client_secret=v.clientSecret),v.codeVerifier&&(q.code_verifier=v.codeVerifier),v.serverUrl&&(q.resource=v.serverUrl);const X={method:"POST",url:v.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded"},body:q};r({currentStep:"token_request",lastRequest:X,lastResponse:void 0,accessToken:void 0,refreshToken:void 0,httpHistory:[...v.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:X}],isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"token_request":if(!v.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!v.authorizationCode)throw new Error("Missing authorization code");if(!v.codeVerifier)throw new Error("PKCE code_verifier is missing - REQUIRED by 2025-03-26 spec for token exchange");try{const G=new URLSearchParams({grant_type:"authorization_code",code:v.authorizationCode,redirect_uri:f,client_id:v.clientId||"",code_verifier:v.codeVerifier||""});v.clientSecret&&G.set("client_secret",v.clientSecret),v.serverUrl&&G.set("resource",v.serverUrl);const P=await ua(v.authorizationServerMetadata.token_endpoint,{method:"POST",headers:p({"Content-Type":"application/x-www-form-urlencoded"}),body:G.toString()}),V={status:P.status,statusText:P.statusText,headers:P.headers,body:P.body},K=[...v.httpHistory||[]];if(K.length>0){const ee=K[K.length-1];ee.response=V,ee.duration=Date.now()-(ee.timestamp||Date.now())}if(!P.ok){r({lastResponse:V,httpHistory:K,authorizationCode:void 0,error:`Token request failed: ${P.body?.error||P.statusText} - ${P.body?.error_description||"Unknown error"}`,isInitiatingAuth:!1});return}const Q=P.body;let re=(m().infoLogs||[]).filter(ee=>ee.id!=="auth-code"&&ee.id!=="oauth-tokens"&&ee.id!=="token");if(v.authorizationCode&&(re=[...re,{id:"auth-code",level:"info",step:"received_authorization_code",label:"Authorization Code",data:{code:v.authorizationCode},timestamp:Date.now()}]),Q.access_token){const ee={access_token:Q.access_token};Q.refresh_token&&(ee.refresh_token=Q.refresh_token),re=[...re,{id:"oauth-tokens",level:"info",step:"received_access_token",label:"OAuth Tokens",data:ee,timestamp:Date.now()}]}if(Q.access_token){const ee=Gm(Q.access_token);if(ee){const le={...ee};le.exp&&(le.exp=`${le.exp} (${Ji(le.exp)})`),le.iat&&(le.iat=`${le.iat} (${Ji(le.iat)})`),le.nbf&&(le.nbf=`${le.nbf} (${Ji(le.nbf)})`);const te={...le};if(le.aud){const Z=v.serverUrl,J=(Array.isArray(le.aud)?le.aud:[le.aud]).some(se=>se===Z);te._validation={expected_audience:Z,audience_matches:J,note:J?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else te._validation={note:"⚠ No audience claim found - server should validate token binding"};re=[...re,{id:"token",step:"received_access_token",level:"info",label:"Access Token (Decoded JWT)",data:te,timestamp:Date.now()}]}}if(Q.id_token){const ee=Gm(Q.id_token);if(ee){const le={...ee};le.exp&&(le.exp=`${le.exp} (${Ji(le.exp)})`),le.iat&&(le.iat=`${le.iat} (${Ji(le.iat)})`),le.nbf&&(le.nbf=`${le.nbf} (${Ji(le.nbf)})`),le.auth_time&&(le.auth_time=`${le.auth_time} (${Ji(le.auth_time)})`),le._note="OIDC ID Token - Used for user identity verification",re=[...re,{id:"id-token",step:"received_access_token",level:"info",label:"ID Token (OIDC - Decoded JWT)",data:le,timestamp:Date.now()}]}}r({currentStep:"received_access_token",accessToken:Q.access_token,refreshToken:Q.refresh_token,tokenType:Q.token_type||"Bearer",expiresIn:Q.expires_in,lastResponse:V,httpHistory:K,infoLogs:re,error:void 0,isInitiatingAuth:!1})}catch(G){const P={status:0,statusText:"Network Error",headers:p({}),body:{error:G instanceof Error?G.message:String(G)}},V=[...v.httpHistory||[]];if(V.length>0){const K=V[V.length-1];K.response=P,K.duration=Date.now()-(K.timestamp||Date.now())}r({lastResponse:P,httpHistory:V,error:`Token exchange failed: ${G instanceof Error?G.message:String(G)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!v.serverUrl||!v.accessToken)throw new Error("Missing server URL or access token");const L={method:"POST",url:v.serverUrl,headers:{Authorization:`Bearer ${v.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"},body:{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCP Inspector",version:"1.0.0"}},id:2}},Y=yn(m(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-03-26",Client:"MCP Inspector v1.0.0",Endpoint:v.serverUrl});r({currentStep:"authenticated_mcp_request",lastRequest:L,lastResponse:void 0,httpHistory:[...v.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:L}],infoLogs:Y,isInitiatingAuth:!1}),setTimeout(()=>y.proceedToNextStep(),50);return;case"authenticated_mcp_request":if(!v.serverUrl||!v.accessToken)throw new Error("Missing server URL or access token");try{const G=await ua(v.serverUrl,{method:"POST",headers:p({Authorization:`Bearer ${v.accessToken}`,"Content-Type":"application/json",Accept:"application/json, text/event-stream"}),body:JSON.stringify({jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2024-11-05",capabilities:{},clientInfo:{name:"MCP Inspector",version:"1.0.0"}},id:2})}),P={status:G.status,statusText:G.statusText,headers:G.headers,body:G.body},V=[...v.httpHistory||[]];if(V.length>0){const ee=V[V.length-1];ee.response=P,ee.duration=Date.now()-(ee.timestamp||Date.now())}if(!G.ok){if(G.status>=400&&G.status<500)try{const ee={method:"GET",url:v.serverUrl,headers:{Authorization:`Bearer ${v.accessToken}`,Accept:"text/event-stream"}},le={step:"complete",timestamp:Date.now(),request:ee};V.push(le);const te=await ua(v.serverUrl,{method:"GET",headers:{Authorization:`Bearer ${v.accessToken}`,Accept:"text/event-stream"}});le.response={status:te.status,statusText:te.statusText,headers:te.headers,body:te.body},le.duration=Date.now()-le.timestamp;const Z=te.body;if(Z&&typeof Z=="object"&&Z.isOldTransport&&Z.endpoint){const ne=Z.endpoint,J=new URL(ne,v.serverUrl).toString(),se=yn(m(),"authenticated_mcp_request","http-sse-detected","HTTP+SSE Transport Detected (2024-11-05)",{Transport:"HTTP+SSE (2024-11-05 - Deprecated)","SSE Stream URL":v.serverUrl,"POST Endpoint":J,"First Event":Z.events?.[0],"Migration Note":"This transport is deprecated. Please update your server to use the 2025-03-26 Streamable HTTP transport.","How It Works":"Client connected via GET for SSE stream. Subsequent requests use POST to: "+J});r({currentStep:"complete",lastResponse:{status:te.status,statusText:"OK - HTTP+SSE Transport",headers:te.headers,body:{transport:"HTTP+SSE (2024-11-05)",sseStreamUrl:v.serverUrl,postEndpoint:J,events:Z.events}},httpHistory:V,infoLogs:se,error:void 0,isInitiatingAuth:!1});return}}catch(ee){console.error("GET fallback failed:",ee)}r({lastResponse:P,httpHistory:V,error:`Authenticated request failed: ${G.status} ${G.statusText}`,isInitiatingAuth:!1});return}let K=m().infoLogs||[];const Q=G.headers["content-type"]||"",oe=Q.includes("text/event-stream");let re=null;if(oe&&G.body?.transport==="sse"?re=G.body.mcpResponse:re=G.body,oe&&re?.result?.protocolVersion){const ee={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":re.result.protocolVersion};re.result.serverInfo&&(ee["Server Name"]=re.result.serverInfo.name,ee["Server Version"]=re.result.serverInfo.version),re.result.capabilities&&(ee.Capabilities=re.result.capabilities),K=yn(m(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",ee)}else if(oe)K=yn(m(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":Q,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:G.body?.events?`${G.body.events.length} events parsed`:"No events parsed"});else if(re?.result?.protocolVersion){const ee={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":re.result.protocolVersion};re.result.serverInfo&&(ee["Server Name"]=re.result.serverInfo.name,ee["Server Version"]=re.result.serverInfo.version),re.result.capabilities&&(ee.Capabilities=re.result.capabilities),K=yn(m(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",ee)}r({currentStep:"complete",lastResponse:P,httpHistory:V,infoLogs:K,error:void 0,isInitiatingAuth:!1})}catch(G){const P=$d(G),V={status:0,statusText:"Network Error",headers:p({}),body:{error:P.message,details:P.details}},K=[...v.httpHistory||[]];if(K.length>0){const re={...K[K.length-1],response:V,duration:Date.now()-(K[K.length-1]?.timestamp||Date.now()),error:P};K[K.length-1]=re}const Q=m(),oe=yn(Q,"authenticated_mcp_request",`error-authenticated_mcp_request-${Date.now()}`,"Authenticated MCP request failed",{request:Q.lastRequest,error:P},{level:"error",error:P});r({lastResponse:V,httpHistory:K,infoLogs:oe,error:`Authenticated MCP request failed: ${P.message}`,isInitiatingAuth:!1})}break;case"complete":r({isInitiatingAuth:!1});break;default:r({isInitiatingAuth:!1});break}}catch(x){const _=m(),S=$d(x),w=yn(_,_.currentStep,`error-${_.currentStep}-${Date.now()}`,"Step failed",{step:_.currentStep,request:_.lastRequest,response:_.lastResponse,error:S},{level:"error",error:S}),T=Rw(_.httpHistory,S),N={error:S.message,infoLogs:w,isInitiatingAuth:!1};T&&(N.httpHistory=T),r(N)}},startGuidedFlow:async()=>{r({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{r({...fKt,lastRequest:void 0,lastResponse:void 0,httpHistory:[],infoLogs:[],authorizationCode:void 0,authorizationUrl:void 0,accessToken:void 0,refreshToken:void 0,codeVerifier:void 0,codeChallenge:void 0,error:void 0})}};return y},G0="https://www.mcpjam.com/.well-known/oauth/client-metadata.json";function AC(e){try{const t=new URL(e);return t.protocol=t.protocol.toLowerCase(),t.hostname=t.hostname.toLowerCase(),t.hash="",t.pathname!=="/"&&t.pathname.endsWith("/")&&(t.pathname=t.pathname.slice(0,-1)),t.toString()}catch(t){return console.warn("Failed to canonicalize resource URL:",e,t),e}}const gKt=PZ;function Eme(e,t){return[{id:"request_without_token",label:"MCP request without token",description:"Client makes initial request without authorization",from:"client",to:"mcpServer",details:e.serverUrl?[{label:"POST",value:e.serverUrl},{label:"method",value:"initialize"}]:void 0},{id:"received_401_unauthorized",label:"HTTP 401 Unauthorized with WWW-Authenticate header",description:"Server returns 401 with WWW-Authenticate header",from:"mcpServer",to:"client",details:e.resourceMetadataUrl?[{label:"Note",value:"Extract resource_metadata URL"}]:void 0},{id:"request_resource_metadata",label:"Request Protected Resource Metadata",description:"Client requests metadata from well-known URI",from:"client",to:"mcpServer",details:e.resourceMetadataUrl?[{label:"GET",value:new URL(e.resourceMetadataUrl).pathname}]:void 0},{id:"received_resource_metadata",label:"Return metadata",description:"Server returns OAuth protected resource metadata",from:"mcpServer",to:"client",details:e.resourceMetadata?.authorization_servers?[{label:"Auth Server",value:e.resourceMetadata.authorization_servers[0]}]:void 0},{id:"request_authorization_server_metadata",label:"GET Authorization server metadata endpoint",description:"Try OAuth path insertion, OIDC path insertion, OIDC path appending",from:"client",to:"authServer",details:e.authorizationServerUrl?[{label:"URL",value:e.authorizationServerUrl},{label:"Protocol",value:"2025-11-25"}]:void 0},{id:"received_authorization_server_metadata",label:"Authorization server metadata response",description:"Authorization Server returns metadata",from:"authServer",to:"client",details:e.authorizationServerMetadata?[{label:"Token",value:new URL(e.authorizationServerMetadata.token_endpoint).pathname},{label:"Auth",value:new URL(e.authorizationServerMetadata.authorization_endpoint).pathname}]:void 0},...t==="cimd"?[{id:"cimd_prepare",label:"Client uses HTTPS URL as client_id",description:"Client prepares to use URL-based client identification",from:"client",to:"client",details:e.clientId?[{label:"client_id (URL)",value:e.clientId.includes("http")?e.clientId:"https://www.mcpjam.com/.well-known/oauth/client-metadata.json"},{label:"Method",value:"Client ID Metadata Document (CIMD)"}]:[{label:"Note",value:"HTTPS URL points to metadata document"}]},{id:"cimd_fetch_request",label:"Fetch metadata from client_id URL",description:"Authorization Server fetches client metadata from the URL",from:"authServer",to:"client",details:[{label:"Action",value:"GET client_id URL"},{label:"Note",value:"Server initiates metadata fetch during authorization"}]},{id:"cimd_metadata_response",label:"JSON metadata document",description:"Client hosting returns metadata with redirect_uris and client info",from:"client",to:"authServer",details:[{label:"Content-Type",value:"application/json"},{label:"Contains",value:"client_id, client_name, redirect_uris, etc."}]},{id:"received_client_credentials",label:"Validate metadata and redirect_uris",description:"Authorization Server validates fetched metadata",from:"authServer",to:"authServer",details:[{label:"Validates",value:"client_id matches URL, redirect_uris are valid"},{label:"Security",value:"SSRF protection, domain trust policies"}]}]:t==="dcr"?[{id:"request_client_registration",label:"POST /register (2025-11-25)",description:"Client registers dynamically with Authorization Server",from:"client",to:"authServer",details:[{label:"Note",value:"Dynamic client registration (DCR)"}]},{id:"received_client_credentials",label:"Client Credentials",description:"Authorization Server returns client ID and credentials",from:"authServer",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."}]:void 0}]:[{id:"received_client_credentials",label:"Use Pre-registered Client (2025-11-25)",description:"Client uses pre-configured credentials (skipped DCR)",from:"client",to:"client",details:e.clientId?[{label:"client_id",value:e.clientId.substring(0,20)+"..."},{label:"Note",value:"Pre-registered (no DCR needed)"}]:[{label:"Note",value:"Pre-registered client credentials"}]}],{id:"generate_pkce_parameters",label:`Generate PKCE (REQUIRED)
|
|
1841
1841
|
Include resource parameter`,description:"Client generates code verifier and challenge (REQUIRED), includes resource parameter",from:"client",to:"client",details:e.codeChallenge?[{label:"code_challenge",value:e.codeChallenge.substring(0,15)+"..."},{label:"method",value:e.codeChallengeMethod||"S256"},{label:"resource",value:e.serverUrl?AC(e.serverUrl):"—"},{label:"Protocol",value:"2025-11-25"}]:void 0},{id:"authorization_request",label:"Open browser with authorization URL",description:"Client opens browser with authorization URL + code_challenge + resource",from:"client",to:"browser",details:e.authorizationUrl?[{label:"code_challenge",value:e.codeChallenge?.substring(0,12)+"..."||"S256"},{label:"resource",value:e.serverUrl?AC(e.serverUrl):""}]:void 0},{id:"browser_to_auth_server",label:"Authorization request with resource parameter",description:"Browser navigates to authorization endpoint",from:"browser",to:"authServer",details:e.authorizationUrl?[{label:"Note",value:"User authorizes in browser"}]:void 0},{id:"auth_redirect_to_browser",label:"Redirect to callback with authorization code",description:"Authorization Server redirects browser back to callback URL",from:"authServer",to:"browser",details:e.authorizationCode?[{label:"code",value:e.authorizationCode.substring(0,20)+"..."}]:void 0},{id:"received_authorization_code",label:"Authorization code callback",description:"Browser redirects back to client with authorization code",from:"browser",to:"client",details:e.authorizationCode?[{label:"code",value:e.authorizationCode.substring(0,20)+"..."}]:void 0},{id:"token_request",label:"Token request + code_verifier + resource",description:"Client exchanges authorization code for access token",from:"client",to:"authServer",details:e.codeVerifier?[{label:"grant_type",value:"authorization_code"},{label:"resource",value:e.serverUrl?AC(e.serverUrl):""}]:void 0},{id:"received_access_token",label:"Access token (+ refresh token)",description:"Authorization Server returns access token",from:"authServer",to:"client",details:e.accessToken?[{label:"token_type",value:e.tokenType||"Bearer"},{label:"expires_in",value:e.expiresIn?.toString()||"3600"}]:void 0},{id:"authenticated_mcp_request",label:"MCP request with access token",description:"Client makes authenticated request to MCP server",from:"client",to:"mcpServer",details:e.accessToken?[{label:"POST",value:"tools/list"},{label:"Authorization",value:"Bearer "+e.accessToken.substring(0,15)+"..."}]:void 0},{id:"complete",label:"MCP response",description:"MCP Server returns successful response",from:"mcpServer",to:"client",details:e.accessToken?[{label:"Status",value:"200 OK"},{label:"Content",value:"tools, resources, prompts"}]:void 0}]}function Tme(e){const t=new URL(e),n=[];if(t.pathname==="/"||t.pathname==="")n.push(new URL("/.well-known/oauth-authorization-server",t.origin).toString()),n.push(new URL("/.well-known/openid-configuration",t.origin).toString());else{const r=t.pathname.endsWith("/")?t.pathname.slice(0,-1):t.pathname;n.push(new URL(`/.well-known/oauth-authorization-server${r}`,t.origin).toString()),n.push(new URL(`/.well-known/openid-configuration${r}`,t.origin).toString()),n.push(new URL(`${r}/.well-known/openid-configuration`,t.origin).toString())}return n}const vKt=e=>{const{state:t,getState:n,updateState:r,serverUrl:i,serverName:a,redirectUrl:s,fetchFn:o=fetch,customScopes:u,customHeaders:c,registrationStrategy:d="cimd"}=e,f=AC(i),p=s||`${window.location.origin}/oauth/callback/debug`,m=(x={})=>({...c,...x}),y=()=>n?n():t,v={state:t,updateState:r,proceedToNextStep:async()=>{const x=y();r({isInitiatingAuth:!0});try{switch(x.currentStep){case"idle":const _=m({"Content-Type":"application/json"}),S={method:"POST",url:i,headers:_,body:{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2025-11-25",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:1}};r({currentStep:"request_without_token",serverUrl:i,lastRequest:S,lastResponse:void 0,httpHistory:[...x.httpHistory||[],{step:"request_without_token",timestamp:Date.now(),request:S}],isInitiatingAuth:!1}),setTimeout(()=>v.proceedToNextStep(),50);return;case"request_without_token":if(!x.serverUrl)throw new Error("No server URL available");try{const J=await ua(x.serverUrl,{method:"POST",headers:m({"Content-Type":"application/json"}),body:JSON.stringify({jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2025-11-25",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:1})}),se={status:J.status,statusText:J.statusText,headers:J.headers,body:J.body},ie=[...x.httpHistory||[]];if(ie.length>0){const he=ie[ie.length-1];he.response=se,he.duration=Date.now()-(he.timestamp||Date.now())}if(J.status===401){const he=J.headers["www-authenticate"],ye=he?yn(x,"received_401_unauthorized","www-authenticate","WWW-Authenticate Header",{header:he,"Received from":x.serverUrl||"Unknown"}):x.infoLogs;r({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:he||void 0,lastResponse:se,httpHistory:ie,infoLogs:ye,isInitiatingAuth:!1})}else if(J.status===200){const he=yn(x,"received_401_unauthorized","optional-auth","Optional Authentication Detected",{message:"Server allows anonymous access",note:"Proceeding with OAuth discovery for authenticated features"});r({currentStep:"received_401_unauthorized",wwwAuthenticateHeader:void 0,lastResponse:se,httpHistory:ie,infoLogs:he,isInitiatingAuth:!1})}else throw r({lastResponse:se,httpHistory:ie}),new Error(`Expected 401 Unauthorized but got HTTP ${J.status}: ${J.body?.error?.message||J.statusText}`)}catch(J){throw new Error(`Failed to request MCP server: ${J instanceof Error?J.message:String(J)}`)}break;case"received_401_unauthorized":let w;if(x.wwwAuthenticateHeader){const J=x.wwwAuthenticateHeader.match(/resource_metadata="([^"]+)"/);J&&(w=J[1])}if(!w&&x.serverUrl&&(w=USe(x.serverUrl)),!w)throw new Error("Could not determine resource metadata URL");const T={method:"GET",url:w,headers:m({})};r({currentStep:"request_resource_metadata",resourceMetadataUrl:w,lastRequest:T,lastResponse:void 0,httpHistory:[...x.httpHistory||[],{step:"request_resource_metadata",timestamp:Date.now(),request:T}],isInitiatingAuth:!1}),setTimeout(()=>v.proceedToNextStep(),50);return;case"request_resource_metadata":if(!x.serverUrl)throw new Error("No server URL available");const N=[...x.httpHistory||[]];let E=N.length>0&&N[N.length-1]?.step==="request_resource_metadata"&&!N[N.length-1]?.response?N.pop():void 0;const A=[],I=J=>J?J instanceof Headers?Object.fromEntries(J.entries()):Array.isArray(J)?Object.fromEntries(J):Object.fromEntries(Object.entries(J).map(([se,ie])=>[se,String(ie)])):{},M=async(J,se={})=>{const ie=typeof J=="string"?J:J.toString(),he=m(I(se.headers)),ye=E?{...E,timestamp:Date.now(),request:{method:se.method||"GET",url:ie,headers:he,body:se.body}}:{step:"request_resource_metadata",timestamp:Date.now(),request:{method:se.method||"GET",url:ie,headers:he,body:se.body}};E=void 0,A.push(ye);try{const Ne=await ua(ie,{method:se.method||"GET",headers:he,body:se.body});ye.response={status:Ne.status,statusText:Ne.statusText,headers:Ne.headers,body:Ne.body},ye.duration=Date.now()-ye.timestamp;const ce={status:Ne.status,statusText:Ne.statusText,headers:Ne.headers},Te=typeof Ne.body=="string"?Ne.body:JSON.stringify(Ne.body??{});return new Response(Te,ce)}catch(Ne){throw ye.error=$d(Ne),ye.duration=Date.now()-ye.timestamp,Ne}};try{const J=x.wwwAuthenticateHeader&&x.resourceMetadataUrl?{resourceMetadataUrl:x.resourceMetadataUrl}:void 0,se=await d3(x.serverUrl,J,M),ie=[...N,...A],he=A[A.length-1],ye=se.authorization_servers?.[0]||i,Ne=yn(x,"received_resource_metadata","authorization-servers","Authorization Servers",{Resource:se.resource,"Authorization Servers":se.authorization_servers});r({currentStep:"received_resource_metadata",resourceMetadata:se,resourceMetadataUrl:he?.request?.url||x.resourceMetadataUrl,authorizationServerUrl:ye,lastRequest:he?.request,lastResponse:he?.response,httpHistory:ie,infoLogs:Ne,isInitiatingAuth:!1})}catch(J){const se=Rw([...N,...A],$d(J));throw r({lastResponse:A[A.length-1]?.response,httpHistory:se}),new Error(`Failed to request resource metadata: ${J instanceof Error?J.message:String(J)}`)}break;case"received_resource_metadata":if(!x.authorizationServerUrl)throw new Error("No authorization server URL available");const O={method:"GET",url:Tme(x.authorizationServerUrl)[0],headers:m({})};r({currentStep:"request_authorization_server_metadata",lastRequest:O,lastResponse:void 0,httpHistory:[...x.httpHistory||[],{step:"request_authorization_server_metadata",timestamp:Date.now(),request:O}],isInitiatingAuth:!1}),setTimeout(()=>v.proceedToNextStep(),50);return;case"request_authorization_server_metadata":if(!x.authorizationServerUrl)throw new Error("No authorization server URL available");const R=Tme(x.authorizationServerUrl);let U=null,z=null,F="",D={},W={},q=null;for(const J of R)try{const se=m({}),ie=[...x.httpHistory||[]];ie.length>0&&(ie[ie.length-1].request={method:"GET",url:J,headers:se}),r({lastRequest:{method:"GET",url:J,headers:se},httpHistory:ie});const he=await ua(J,{method:"GET",headers:m({})});if(he.ok){U=he.body,F=J,D=se,W=he.headers,q=he;break}else{if(he.status>=400&&he.status<500)continue;z=new Error(`HTTP ${he.status} from ${J}`)}}catch(se){z=se;continue}if(!U||!q)throw new Error(`Could not discover authorization server metadata. Last error: ${z instanceof Error?z.message:String(z)}`);if(!U.issuer)throw new Error("Authorization server metadata missing required 'issuer' field");if(!U.authorization_endpoint)throw new Error("Authorization server metadata missing 'authorization_endpoint'");if(!U.token_endpoint)throw new Error("Authorization server metadata missing 'token_endpoint'");if(!U.response_types_supported?.includes("code"))throw new Error("Authorization server does not support 'code' response type");const X={status:q.status,statusText:q.statusText,headers:W,body:U},L=[...x.httpHistory||[]];if(L.length>0){const J=L[L.length-1];J.response=X,J.duration=Date.now()-(J.timestamp||Date.now())}const Y=U.code_challenge_methods_supported||[];if(!Y||Y.length===0)throw new Error("PKCE is REQUIRED for 2025-11-25 protocol, but authorization server does not advertise code_challenge_methods_supported. Server is not compliant with 2025-11-25 spec.");const G={Issuer:U.issuer,"Authorization Endpoint":U.authorization_endpoint,"Token Endpoint":U.token_endpoint};U.registration_endpoint&&(G["Registration Endpoint"]=U.registration_endpoint),U.code_challenge_methods_supported&&(G["PKCE Methods"]=U.code_challenge_methods_supported),U.grant_types_supported&&(G["Grant Types"]=U.grant_types_supported),U.response_types_supported&&(G["Response Types"]=U.response_types_supported),U.scopes_supported&&(G.Scopes=U.scopes_supported);const P=yn(y(),"received_authorization_server_metadata","as-metadata","Authorization Server Metadata",G);Y.includes("S256")?r({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:U,lastResponse:X,httpHistory:L,infoLogs:P,isInitiatingAuth:!1}):(console.warn("Authorization server may not support S256 PKCE method. Supported methods:",Y),r({currentStep:"received_authorization_server_metadata",authorizationServerMetadata:U,lastResponse:X,httpHistory:L,infoLogs:P,error:"Warning: Authorization server may not support S256 PKCE method",isInitiatingAuth:!1}));break;case"received_authorization_server_metadata":if(!x.authorizationServerMetadata)throw new Error("No authorization server metadata available");if(d==="cimd"){r({currentStep:"cimd_prepare",clientId:G0,isInitiatingAuth:!1}),setTimeout(()=>v.proceedToNextStep(),800);return}else if(d==="preregistered"){const{clientId:J,clientSecret:se}=FH(a);if(!J){r({error:"Pre-registered client ID is required. Please configure OAuth credentials in the server settings.",isInitiatingAuth:!1});return}const ie={"Client ID":J,"Client Secret":se?"Configured":"Not provided (public client)","Token Auth Method":se?"client_secret_post":"none",Note:"Using pre-registered client credentials from server config (skipped DCR)"},he=yn(y(),"received_client_credentials","dcr","Pre-registered Client",ie);r({currentStep:"received_client_credentials",clientId:J,clientSecret:se||void 0,tokenEndpointAuthMethod:se?"client_secret_post":"none",infoLogs:he,isInitiatingAuth:!1})}else if(x.authorizationServerMetadata.registration_endpoint){const J=x.resourceMetadata?.scopes_supported||x.authorizationServerMetadata.scopes_supported,se={client_name:"MCPJam Inspector Debug Client",redirect_uris:[p],grant_types:["authorization_code","refresh_token"],response_types:["code"],token_endpoint_auth_method:"none"};J&&J.length>0&&(se.scope=J.join(" "));const ie={method:"POST",url:x.authorizationServerMetadata.registration_endpoint,headers:m({"Content-Type":"application/json"}),body:se};r({currentStep:"request_client_registration",lastRequest:ie,lastResponse:void 0,httpHistory:[...x.httpHistory||[],{step:"request_client_registration",timestamp:Date.now(),request:ie}],isInitiatingAuth:!1}),setTimeout(()=>v.proceedToNextStep(),50);return}else r({currentStep:"generate_pkce_parameters",clientId:"mock-client-id-for-demo",tokenEndpointAuthMethod:"none",isInitiatingAuth:!1});break;case"request_client_registration":if(!x.authorizationServerMetadata?.registration_endpoint)throw new Error("No registration endpoint available");if(!x.lastRequest?.body)throw new Error("No client metadata in request");try{const J=await ua(x.authorizationServerMetadata.registration_endpoint,{method:"POST",headers:m({"Content-Type":"application/json"}),body:JSON.stringify(x.lastRequest.body)}),se={status:J.status,statusText:J.statusText,headers:J.headers,body:J.body},ie=[...x.httpHistory||[]];if(ie.length>0){const he=ie[ie.length-1];he.response=se,he.duration=Date.now()-(he.timestamp||Date.now())}if(!J.ok)r({lastResponse:se,httpHistory:ie,error:`Dynamic Client Registration failed (${J.status}). Using fallback client ID.`}),r({currentStep:"received_client_credentials",clientId:"preregistered-client-id",clientSecret:void 0,tokenEndpointAuthMethod:"none",isInitiatingAuth:!1});else{const he=J.body,ye={"Client ID":he.client_id,"Client Name":he.client_name,"Token Auth Method":he.token_endpoint_auth_method||"none","Redirect URIs":he.redirect_uris,"Grant Types":he.grant_types,"Response Types":he.response_types};he.client_secret&&(ye["Client Secret"]=he.client_secret.substring(0,20)+"...",ye.Note="Server issued client_secret - this will be used in token requests");const Ne=yn(y(),"received_client_credentials","dcr","Dynamic Client Registration",ye);r({currentStep:"received_client_credentials",clientId:he.client_id,clientSecret:he.client_secret,tokenEndpointAuthMethod:he.token_endpoint_auth_method||"none",lastResponse:se,httpHistory:ie,infoLogs:Ne,error:void 0,isInitiatingAuth:!1})}}catch(J){const se={status:0,statusText:"Network Error",headers:m({}),body:{error:J instanceof Error?J.message:String(J)}},ie=[...x.httpHistory||[]];if(ie.length>0){const ye=ie[ie.length-1];ye.response=se,ye.duration=Date.now()-(ye.timestamp||Date.now())}r({lastResponse:se,httpHistory:ie,error:`Client registration failed: ${J instanceof Error?J.message:String(J)}. Using fallback.`}),r({currentStep:"received_client_credentials",clientId:"preregistered-client-id",clientSecret:void 0,tokenEndpointAuthMethod:"none",isInitiatingAuth:!1})}break;case"cimd_prepare":r({currentStep:"cimd_fetch_request",isInitiatingAuth:!1}),setTimeout(()=>v.proceedToNextStep(),800);return;case"cimd_fetch_request":const V=x.authorizationServerMetadata?.client_id_metadata_document_supported;try{const J=await ua(G0,{method:"GET"});if(!J.ok)throw new Error(`CIMD endpoint returned HTTP ${J.status}`);const se=J.body;r({currentStep:"cimd_metadata_response",isInitiatingAuth:!1}),setTimeout(()=>v.proceedToNextStep(),800);return}catch(J){r({error:`CIMD metadata fetch failed: ${J instanceof Error?J.message:String(J)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}case"cimd_metadata_response":try{const J=await ua(G0,{method:"GET"});if(!J.ok)throw new Error(`CIMD endpoint returned HTTP ${J.status}`);const se=J.body;if(se.client_id!==G0)throw new Error("CIMD client_id mismatch");const ie=x.authorizationServerMetadata?.client_id_metadata_document_supported,he={"Client ID":G0,"Registration Method":"Client ID Metadata Document (CIMD)","Client Name":se.client_name||"MCPJam","Redirect URIs":se.redirect_uris||[],"Token Auth Method":se.token_endpoint_auth_method||"none",Validation:"✓ Metadata fetched and validated",Note:"Server fetched and validated client metadata from URL"};ie?he["Server Support"]="✓ Advertised in metadata (client_id_metadata_document_supported: true)":he["Server Support"]="⚠ Not advertised (attempting anyway)";const ye=yn(y(),"received_client_credentials","cimd","Client ID Metadata Document",he);r({currentStep:"received_client_credentials",clientId:G0,clientSecret:void 0,tokenEndpointAuthMethod:"none",infoLogs:ye,isInitiatingAuth:!1})}catch(J){r({error:`CIMD validation failed: ${J instanceof Error?J.message:String(J)}. Try using 'dcr' or 'preregistered' registration strategy instead.`,isInitiatingAuth:!1});return}break;case"received_client_credentials":const K=Vm(43),Q=await UH(K),oe=yn(y(),"generate_pkce_parameters","pkce-generation","Generate PKCE Parameters",{code_challenge:Q,method:"S256",resource:f});r({currentStep:"generate_pkce_parameters",codeVerifier:K,codeChallenge:Q,codeChallengeMethod:"S256",state:Vm(16),infoLogs:oe,isInitiatingAuth:!1});break;case"generate_pkce_parameters":if(!x.authorizationServerMetadata?.authorization_endpoint||!x.clientId)throw new Error("Missing authorization endpoint or client ID");const re=new URL(x.authorizationServerMetadata.authorization_endpoint);if(re.searchParams.set("response_type","code"),re.searchParams.set("client_id",x.clientId),re.searchParams.set("redirect_uri",p),re.searchParams.set("code_challenge",x.codeChallenge||""),re.searchParams.set("code_challenge_method","S256"),re.searchParams.set("state",x.state||""),re.searchParams.set("resource",f),u)re.searchParams.set("scope",u);else{const J=x.resourceMetadata?.scopes_supported||x.authorizationServerMetadata.scopes_supported,se=new Set;J&&J.length>0&&J.forEach(ie=>se.add(ie)),se.size>0&&re.searchParams.set("scope",Array.from(se).join(" "))}const ee=yn(y(),"authorization_request","auth-url","Authorization URL",{url:re.toString()});r({currentStep:"authorization_request",authorizationUrl:re.toString(),authorizationCode:void 0,accessToken:void 0,refreshToken:void 0,tokenType:void 0,expiresIn:void 0,infoLogs:ee,isInitiatingAuth:!1});break;case"authorization_request":r({currentStep:"received_authorization_code",isInitiatingAuth:!1});break;case"received_authorization_code":if(!x.authorizationCode||x.authorizationCode.trim()===""){r({error:"Authorization code is required. Please paste the code you received from the authorization server.",isInitiatingAuth:!1});return}if(!x.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");const le={grant_type:"authorization_code",code:x.authorizationCode,redirect_uri:p};x.clientId&&(le.client_id=x.clientId),x.clientSecret&&(le.client_secret=x.clientSecret),x.codeVerifier&&(le.code_verifier=x.codeVerifier),le.resource=f;const te={method:"POST",url:x.authorizationServerMetadata.token_endpoint,headers:{"Content-Type":"application/x-www-form-urlencoded"},body:le};r({currentStep:"token_request",lastRequest:te,lastResponse:void 0,accessToken:void 0,refreshToken:void 0,httpHistory:[...x.httpHistory||[],{step:"token_request",timestamp:Date.now(),request:te}],isInitiatingAuth:!1}),setTimeout(()=>v.proceedToNextStep(),50);return;case"token_request":if(!x.authorizationServerMetadata?.token_endpoint)throw new Error("Missing token endpoint");if(!x.authorizationCode)throw new Error("Missing authorization code");if(!x.codeVerifier)throw new Error("PKCE code_verifier is missing - cannot exchange token");try{const J=new URLSearchParams({grant_type:"authorization_code",code:x.authorizationCode,redirect_uri:p,client_id:x.clientId||"",code_verifier:x.codeVerifier||""});x.clientSecret&&J.set("client_secret",x.clientSecret),J.set("resource",f);const se=await ua(x.authorizationServerMetadata.token_endpoint,{method:"POST",headers:m({"Content-Type":"application/x-www-form-urlencoded"}),body:J.toString()}),ie={status:se.status,statusText:se.statusText,headers:se.headers,body:se.body},he=[...x.httpHistory||[]];if(he.length>0){const Te=he[he.length-1];Te.response=ie,Te.duration=Date.now()-(Te.timestamp||Date.now())}if(!se.ok){r({lastResponse:ie,httpHistory:he,authorizationCode:void 0,error:`Token request failed: ${se.body?.error||se.statusText} - ${se.body?.error_description||"Unknown error"}`,isInitiatingAuth:!1});return}const ye=se.body;let ce=(y().infoLogs||[]).filter(Te=>Te.id!=="auth-code"&&Te.id!=="oauth-tokens"&&Te.id!=="token");if(x.authorizationCode&&(ce=[...ce,{id:"auth-code",level:"info",step:"authorization_request",label:"Authorization Code",data:{code:x.authorizationCode},timestamp:Date.now()}]),ye.access_token){const Te={access_token:ye.access_token};ye.refresh_token&&(Te.refresh_token=ye.refresh_token),ce=[...ce,{id:"oauth-tokens",level:"info",step:"token_request",label:"OAuth Tokens",data:Te,timestamp:Date.now()}]}if(ye.access_token){const Te=Gm(ye.access_token);if(Te){const we={...Te};we.exp&&(we.exp=`${we.exp} (${Ji(we.exp)})`),we.iat&&(we.iat=`${we.iat} (${Ji(we.iat)})`),we.nbf&&(we.nbf=`${we.nbf} (${Ji(we.nbf)})`);const Oe={...we};if(we.aud){const Ue=x.serverUrl,be=(Array.isArray(we.aud)?we.aud:[we.aud]).some(je=>je===Ue);Oe._validation={expected_audience:Ue,audience_matches:be,note:be?"✓ Token audience matches MCP server":"⚠ Token audience does not match MCP server (security risk)"}}else Oe._validation={note:"⚠ No audience claim found - server should validate token binding"};ce=[...ce,{id:"token",level:"info",step:"token_request",label:"Access Token (Decoded JWT)",data:Oe,timestamp:Date.now()}]}}if(ye.id_token){const Te=Gm(ye.id_token);if(Te){const we={...Te};we.exp&&(we.exp=`${we.exp} (${Ji(we.exp)})`),we.iat&&(we.iat=`${we.iat} (${Ji(we.iat)})`),we.nbf&&(we.nbf=`${we.nbf} (${Ji(we.nbf)})`),we.auth_time&&(we.auth_time=`${we.auth_time} (${Ji(we.auth_time)})`),we._note="OIDC ID Token - Used for user identity verification",ce=[...ce,{id:"id-token",level:"info",step:"token_request",label:"ID Token (OIDC - Decoded JWT)",data:we,timestamp:Date.now()}]}}r({currentStep:"received_access_token",accessToken:ye.access_token,refreshToken:ye.refresh_token,tokenType:ye.token_type||"Bearer",expiresIn:ye.expires_in,lastResponse:ie,httpHistory:he,infoLogs:ce,error:void 0,isInitiatingAuth:!1})}catch(J){const se={status:0,statusText:"Network Error",headers:m({}),body:{error:J instanceof Error?J.message:String(J)}},ie=[...x.httpHistory||[]];if(ie.length>0){const he=ie[ie.length-1];he.response=se,he.duration=Date.now()-(he.timestamp||Date.now())}r({lastResponse:se,httpHistory:ie,error:`Token exchange failed: ${J instanceof Error?J.message:String(J)}`,isInitiatingAuth:!1})}break;case"received_access_token":if(!x.serverUrl||!x.accessToken)throw new Error("Missing server URL or access token");const Z={method:"POST",url:x.serverUrl,headers:{Authorization:`Bearer ${x.accessToken}`,"Content-Type":"application/json","MCP-Protocol-Version":"2025-11-25"},body:{jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2025-11-25",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:2}},ne=yn(y(),"authenticated_mcp_request","authenticated-init","Authenticated MCP Initialize Request",{Request:"MCP initialize with OAuth bearer token","Protocol Version":"2025-11-25",Client:"MCPJam Inspector v1.0.0",Endpoint:x.serverUrl});r({currentStep:"authenticated_mcp_request",lastRequest:Z,lastResponse:void 0,httpHistory:[...x.httpHistory||[],{step:"authenticated_mcp_request",timestamp:Date.now(),request:Z}],infoLogs:ne,isInitiatingAuth:!1}),setTimeout(()=>v.proceedToNextStep(),50);return;case"authenticated_mcp_request":if(!x.serverUrl||!x.accessToken)throw new Error("Missing server URL or access token");try{const J=await ua(x.serverUrl,{method:"POST",headers:m({Authorization:`Bearer ${x.accessToken}`,"Content-Type":"application/json"}),body:JSON.stringify({jsonrpc:"2.0",method:"initialize",params:{protocolVersion:"2025-11-25",capabilities:{},clientInfo:{name:"MCPJam Inspector",version:"1.0.0"}},id:2})}),se={status:J.status,statusText:J.statusText,headers:J.headers,body:J.body},ie=[...x.httpHistory||[]];if(ie.length>0){const Te=ie[ie.length-1];Te.response=se,Te.duration=Date.now()-(Te.timestamp||Date.now())}if(!J.ok){r({lastResponse:se,httpHistory:ie,error:`Authenticated request failed: ${J.status} ${J.statusText}`,isInitiatingAuth:!1});return}let he=y().infoLogs||[];const ye=J.headers["content-type"]||"",Ne=ye.includes("text/event-stream");let ce=null;if(Ne&&J.body?.transport==="sse"?ce=J.body.mcpResponse:ce=J.body,Ne&&ce?.result?.protocolVersion){const Te={Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Protocol Version":ce.result.protocolVersion};ce.result.serverInfo&&(Te["Server Name"]=ce.result.serverInfo.name,Te["Server Version"]=ce.result.serverInfo.version),ce.result.capabilities&&(Te.Capabilities=ce.result.capabilities),he=yn(y(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",Te)}else if(Ne)he=yn(y(),"authenticated_mcp_request","mcp-transport","MCP Transport Detected",{Transport:"Streamable HTTP","Response Format":"Server-Sent Events (streaming)","Content-Type":ye,Note:"Server returned streaming response. Initialize response delivered via SSE stream.",Events:J.body?.events?`${J.body.events.length} events parsed`:"No events parsed"});else if(ce?.result?.protocolVersion){const Te={Transport:"Streamable HTTP","Response Format":"JSON","Protocol Version":ce.result.protocolVersion};ce.result.serverInfo&&(Te["Server Name"]=ce.result.serverInfo.name,Te["Server Version"]=ce.result.serverInfo.version),ce.result.capabilities&&(Te.Capabilities=ce.result.capabilities),he=yn(y(),"authenticated_mcp_request","mcp-protocol","MCP Server Information",Te)}r({currentStep:"complete",lastResponse:se,httpHistory:ie,infoLogs:he,error:void 0,isInitiatingAuth:!1})}catch(J){const se={status:0,statusText:"Network Error",headers:m({}),body:{error:J instanceof Error?J.message:String(J)}},ie=[...x.httpHistory||[]];if(ie.length>0){const he=ie[ie.length-1];he.response=se,he.duration=Date.now()-(he.timestamp||Date.now())}r({lastResponse:se,httpHistory:ie,error:`Authenticated MCP request failed: ${J instanceof Error?J.message:String(J)}`,isInitiatingAuth:!1})}break;case"complete":r({isInitiatingAuth:!1});break;default:r({isInitiatingAuth:!1});break}}catch(_){const S=y(),w=$d(_),T=yn(S,S.currentStep,`error-${S.currentStep}-${Date.now()}`,"Step failed",{step:S.currentStep,request:S.lastRequest,response:S.lastResponse,error:w},{level:"error",error:w}),N=Rw(S.httpHistory,w),E={error:w.message,infoLogs:T,isInitiatingAuth:!1};N&&(E.httpHistory=N),r(E)}},startGuidedFlow:async()=>{r({currentStep:"idle",isInitiatingAuth:!1})},resetFlow:()=>{r({...gKt,lastRequest:void 0,lastResponse:void 0,httpHistory:[],infoLogs:[],authorizationCode:void 0,authorizationUrl:void 0,accessToken:void 0,refreshToken:void 0,codeVerifier:void 0,codeChallenge:void 0,error:void 0})}};return v};function yKt(e){const{protocolVersion:t,...n}=e;switch(t){case"2025-03-26":if(e.registrationStrategy==="cimd")throw new Error("CIMD registration is not supported in 2025-03-26 protocol. Use 'dcr' or 'preregistered' instead.");return mKt(n);case"2025-06-18":if(e.registrationStrategy==="cimd")throw new Error("CIMD registration is not supported in 2025-06-18 protocol. Use 'dcr' or 'preregistered' instead.");return dKt(n);case"2025-11-25":return vKt(n);default:const r=t;throw new Error(`Unknown protocol version: ${r}`)}}function xKt(e){switch(e){case"2025-03-26":return"dcr";case"2025-06-18":return"dcr";case"2025-11-25":return"cimd";default:return"dcr"}}function Nme(e){switch(e){case"2025-03-26":return["dcr","preregistered"];case"2025-06-18":return["dcr","preregistered"];case"2025-11-25":return["cimd","dcr","preregistered"];default:return["dcr","preregistered"]}}function ha(e){if(typeof e=="string"||typeof e=="number")return""+e;let t="";if(Array.isArray(e))for(let n=0,r;n<e.length;n++)(r=ha(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var bKt={value:()=>{}};function IP(){for(var e=0,t=arguments.length,n={},r;e<t;++e){if(!(r=arguments[e]+"")||r in n||/[\s.]/.test(r))throw new Error("illegal type: "+r);n[r]=[]}return new IC(n)}function IC(e){this._=e}function _Kt(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",i=n.indexOf(".");if(i>=0&&(r=n.slice(i+1),n=n.slice(0,i)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}IC.prototype=IP.prototype={constructor:IC,on:function(e,t){var n=this._,r=_Kt(e+"",n),i,a=-1,s=r.length;if(arguments.length<2){for(;++a<s;)if((i=(e=r[a]).type)&&(i=wKt(n[i],e.name)))return i;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<s;)if(i=(e=r[a]).type)n[i]=Cme(n[i],e.name,t);else if(t==null)for(i in n)n[i]=Cme(n[i],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new IC(e)},call:function(e,t){if((i=arguments.length-2)>0)for(var n=new Array(i),r=0,i,a;r<i;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,i=a.length;r<i;++r)a[r].value.apply(t,n)},apply:function(e,t,n){if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(var r=this._[e],i=0,a=r.length;i<a;++i)r[i].value.apply(t,n)}};function wKt(e,t){for(var n=0,r=e.length,i;n<r;++n)if((i=e[n]).name===t)return i.value}function Cme(e,t,n){for(var r=0,i=e.length;r<i;++r)if(e[r].name===t){e[r]=bKt,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var BB="http://www.w3.org/1999/xhtml";const Ame={svg:"http://www.w3.org/2000/svg",xhtml:BB,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function jP(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),Ame.hasOwnProperty(t)?{space:Ame[t],local:e}:e}function SKt(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===BB&&t.documentElement.namespaceURI===BB?t.createElement(e):t.createElementNS(n,e)}}function kKt(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function R5e(e){var t=jP(e);return(t.local?kKt:SKt)(t)}function EKt(){}function $Z(e){return e==null?EKt:function(){return this.querySelector(e)}}function TKt(e){typeof e!="function"&&(e=$Z(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var a=t[i],s=a.length,o=r[i]=new Array(s),u,c,d=0;d<s;++d)(u=a[d])&&(c=e.call(u,u.__data__,d,a))&&("__data__"in u&&(c.__data__=u.__data__),o[d]=c);return new nl(r,this._parents)}function NKt(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function CKt(){return[]}function P5e(e){return e==null?CKt:function(){return this.querySelectorAll(e)}}function AKt(e){return function(){return NKt(e.apply(this,arguments))}}function IKt(e){typeof e=="function"?e=AKt(e):e=P5e(e);for(var t=this._groups,n=t.length,r=[],i=[],a=0;a<n;++a)for(var s=t[a],o=s.length,u,c=0;c<o;++c)(u=s[c])&&(r.push(e.call(u,u.__data__,c,s)),i.push(u));return new nl(r,i)}function $5e(e){return function(){return this.matches(e)}}function M5e(e){return function(t){return t.matches(e)}}var jKt=Array.prototype.find;function OKt(e){return function(){return jKt.call(this.children,e)}}function RKt(){return this.firstElementChild}function PKt(e){return this.select(e==null?RKt:OKt(typeof e=="function"?e:M5e(e)))}var $Kt=Array.prototype.filter;function MKt(){return Array.from(this.children)}function DKt(e){return function(){return $Kt.call(this.children,e)}}function LKt(e){return this.selectAll(e==null?MKt:DKt(typeof e=="function"?e:M5e(e)))}function zKt(e){typeof e!="function"&&(e=$5e(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var a=t[i],s=a.length,o=r[i]=[],u,c=0;c<s;++c)(u=a[c])&&e.call(u,u.__data__,c,a)&&o.push(u);return new nl(r,this._parents)}function D5e(e){return new Array(e.length)}function UKt(){return new nl(this._enter||this._groups.map(D5e),this._parents)}function Lj(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}Lj.prototype={constructor:Lj,appendChild:function(e){return this._parent.insertBefore(e,this._next)},insertBefore:function(e,t){return this._parent.insertBefore(e,t)},querySelector:function(e){return this._parent.querySelector(e)},querySelectorAll:function(e){return this._parent.querySelectorAll(e)}};function FKt(e){return function(){return e}}function BKt(e,t,n,r,i,a){for(var s=0,o,u=t.length,c=a.length;s<c;++s)(o=t[s])?(o.__data__=a[s],r[s]=o):n[s]=new Lj(e,a[s]);for(;s<u;++s)(o=t[s])&&(i[s]=o)}function qKt(e,t,n,r,i,a,s){var o,u,c=new Map,d=t.length,f=a.length,p=new Array(d),m;for(o=0;o<d;++o)(u=t[o])&&(p[o]=m=s.call(u,u.__data__,o,t)+"",c.has(m)?i[o]=u:c.set(m,u));for(o=0;o<f;++o)m=s.call(e,a[o],o,a)+"",(u=c.get(m))?(r[o]=u,u.__data__=a[o],c.delete(m)):n[o]=new Lj(e,a[o]);for(o=0;o<d;++o)(u=t[o])&&c.get(p[o])===u&&(i[o]=u)}function HKt(e){return e.__data__}function VKt(e,t){if(!arguments.length)return Array.from(this,HKt);var n=t?qKt:BKt,r=this._parents,i=this._groups;typeof e!="function"&&(e=FKt(e));for(var a=i.length,s=new Array(a),o=new Array(a),u=new Array(a),c=0;c<a;++c){var d=r[c],f=i[c],p=f.length,m=GKt(e.call(d,d&&d.__data__,c,r)),y=m.length,v=o[c]=new Array(y),x=s[c]=new Array(y),_=u[c]=new Array(p);n(d,f,v,x,_,m,t);for(var S=0,w=0,T,N;S<y;++S)if(T=v[S]){for(S>=w&&(w=S+1);!(N=x[w])&&++w<y;);T._next=N||null}}return s=new nl(s,r),s._enter=o,s._exit=u,s}function GKt(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function WKt(){return new nl(this._exit||this._groups.map(D5e),this._parents)}function KKt(e,t,n){var r=this.enter(),i=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(i=t(i),i&&(i=i.selection())),n==null?a.remove():n(a),r&&i?r.merge(i).order():i}function ZKt(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,i=n.length,a=r.length,s=Math.min(i,a),o=new Array(i),u=0;u<s;++u)for(var c=n[u],d=r[u],f=c.length,p=o[u]=new Array(f),m,y=0;y<f;++y)(m=c[y]||d[y])&&(p[y]=m);for(;u<i;++u)o[u]=n[u];return new nl(o,this._parents)}function YKt(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],i=r.length-1,a=r[i],s;--i>=0;)(s=r[i])&&(a&&s.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(s,a),a=s);return this}function XKt(e){e||(e=JKt);function t(f,p){return f&&p?e(f.__data__,p.__data__):!f-!p}for(var n=this._groups,r=n.length,i=new Array(r),a=0;a<r;++a){for(var s=n[a],o=s.length,u=i[a]=new Array(o),c,d=0;d<o;++d)(c=s[d])&&(u[d]=c);u.sort(t)}return new nl(i,this._parents).order()}function JKt(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function QKt(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function eZt(){return Array.from(this)}function tZt(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],i=0,a=r.length;i<a;++i){var s=r[i];if(s)return s}return null}function nZt(){let e=0;for(const t of this)++e;return e}function rZt(){return!this.node()}function iZt(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var i=t[n],a=0,s=i.length,o;a<s;++a)(o=i[a])&&e.call(o,o.__data__,a,i);return this}function aZt(e){return function(){this.removeAttribute(e)}}function sZt(e){return function(){this.removeAttributeNS(e.space,e.local)}}function oZt(e,t){return function(){this.setAttribute(e,t)}}function lZt(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function uZt(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function cZt(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttributeNS(e.space,e.local):this.setAttributeNS(e.space,e.local,n)}}function dZt(e,t){var n=jP(e);if(arguments.length<2){var r=this.node();return n.local?r.getAttributeNS(n.space,n.local):r.getAttribute(n)}return this.each((t==null?n.local?sZt:aZt:typeof t=="function"?n.local?cZt:uZt:n.local?lZt:oZt)(n,t))}function L5e(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function fZt(e){return function(){this.style.removeProperty(e)}}function pZt(e,t,n){return function(){this.style.setProperty(e,t,n)}}function hZt(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function mZt(e,t,n){return arguments.length>1?this.each((t==null?fZt:typeof t=="function"?hZt:pZt)(e,t,n??"")):Jy(this.node(),e)}function Jy(e,t){return e.style.getPropertyValue(t)||L5e(e).getComputedStyle(e,null).getPropertyValue(t)}function gZt(e){return function(){delete this[e]}}function vZt(e,t){return function(){this[e]=t}}function yZt(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function xZt(e,t){return arguments.length>1?this.each((t==null?gZt:typeof t=="function"?yZt:vZt)(e,t)):this.node()[e]}function z5e(e){return e.trim().split(/^|\s+/)}function MZ(e){return e.classList||new U5e(e)}function U5e(e){this._node=e,this._names=z5e(e.getAttribute("class")||"")}U5e.prototype={add:function(e){var t=this._names.indexOf(e);t<0&&(this._names.push(e),this._node.setAttribute("class",this._names.join(" ")))},remove:function(e){var t=this._names.indexOf(e);t>=0&&(this._names.splice(t,1),this._node.setAttribute("class",this._names.join(" ")))},contains:function(e){return this._names.indexOf(e)>=0}};function F5e(e,t){for(var n=MZ(e),r=-1,i=t.length;++r<i;)n.add(t[r])}function B5e(e,t){for(var n=MZ(e),r=-1,i=t.length;++r<i;)n.remove(t[r])}function bZt(e){return function(){F5e(this,e)}}function _Zt(e){return function(){B5e(this,e)}}function wZt(e,t){return function(){(t.apply(this,arguments)?F5e:B5e)(this,e)}}function SZt(e,t){var n=z5e(e+"");if(arguments.length<2){for(var r=MZ(this.node()),i=-1,a=n.length;++i<a;)if(!r.contains(n[i]))return!1;return!0}return this.each((typeof t=="function"?wZt:t?bZt:_Zt)(n,t))}function kZt(){this.textContent=""}function EZt(e){return function(){this.textContent=e}}function TZt(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function NZt(e){return arguments.length?this.each(e==null?kZt:(typeof e=="function"?TZt:EZt)(e)):this.node().textContent}function CZt(){this.innerHTML=""}function AZt(e){return function(){this.innerHTML=e}}function IZt(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function jZt(e){return arguments.length?this.each(e==null?CZt:(typeof e=="function"?IZt:AZt)(e)):this.node().innerHTML}function OZt(){this.nextSibling&&this.parentNode.appendChild(this)}function RZt(){return this.each(OZt)}function PZt(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function $Zt(){return this.each(PZt)}function MZt(e){var t=typeof e=="function"?e:R5e(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function DZt(){return null}function LZt(e,t){var n=typeof e=="function"?e:R5e(e),r=t==null?DZt:typeof t=="function"?t:$Z(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function zZt(){var e=this.parentNode;e&&e.removeChild(this)}function UZt(){return this.each(zZt)}function FZt(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function BZt(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function qZt(e){return this.select(e?BZt:FZt)}function HZt(e){return arguments.length?this.property("__data__",e):this.node().__data__}function VZt(e){return function(t){e.call(this,t,this.__data__)}}function GZt(e){return e.trim().split(/^|\s+/).map(function(t){var n="",r=t.indexOf(".");return r>=0&&(n=t.slice(r+1),t=t.slice(0,r)),{type:t,name:n}})}function WZt(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,i=t.length,a;n<i;++n)a=t[n],(!e.type||a.type===e.type)&&a.name===e.name?this.removeEventListener(a.type,a.listener,a.options):t[++r]=a;++r?t.length=r:delete this.__on}}}function KZt(e,t,n){return function(){var r=this.__on,i,a=VZt(t);if(r){for(var s=0,o=r.length;s<o;++s)if((i=r[s]).type===e.type&&i.name===e.name){this.removeEventListener(i.type,i.listener,i.options),this.addEventListener(i.type,i.listener=a,i.options=n),i.value=t;return}}this.addEventListener(e.type,a,n),i={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(i):this.__on=[i]}}function ZZt(e,t,n){var r=GZt(e+""),i,a=r.length,s;if(arguments.length<2){var o=this.node().__on;if(o){for(var u=0,c=o.length,d;u<c;++u)for(i=0,d=o[u];i<a;++i)if((s=r[i]).type===d.type&&s.name===d.name)return d.value}return}for(o=t?KZt:WZt,i=0;i<a;++i)this.each(o(r[i],t,n));return this}function q5e(e,t,n){var r=L5e(e),i=r.CustomEvent;typeof i=="function"?i=new i(t,n):(i=r.document.createEvent("Event"),n?(i.initEvent(t,n.bubbles,n.cancelable),i.detail=n.detail):i.initEvent(t,!1,!1)),e.dispatchEvent(i)}function YZt(e,t){return function(){return q5e(this,e,t)}}function XZt(e,t){return function(){return q5e(this,e,t.apply(this,arguments))}}function JZt(e,t){return this.each((typeof t=="function"?XZt:YZt)(e,t))}function*QZt(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],i=0,a=r.length,s;i<a;++i)(s=r[i])&&(yield s)}var H5e=[null];function nl(e,t){this._groups=e,this._parents=t}function xk(){return new nl([[document.documentElement]],H5e)}function eYt(){return this}nl.prototype=xk.prototype={constructor:nl,select:TKt,selectAll:IKt,selectChild:PKt,selectChildren:LKt,filter:zKt,data:VKt,enter:UKt,exit:WKt,join:KKt,merge:ZKt,selection:eYt,order:YKt,sort:XKt,call:QKt,nodes:eZt,node:tZt,size:nZt,empty:rZt,each:iZt,attr:dZt,style:mZt,property:xZt,classed:SZt,text:NZt,html:jZt,raise:RZt,lower:$Zt,append:MZt,insert:LZt,remove:UZt,clone:qZt,datum:HZt,on:ZZt,dispatch:JZt,[Symbol.iterator]:QZt};function Zo(e){return typeof e=="string"?new nl([[document.querySelector(e)]],[document.documentElement]):new nl([[e]],H5e)}function tYt(e){let t;for(;t=e.sourceEvent;)e=t;return e}function uu(e,t){if(e=tYt(e),t===void 0&&(t=e.currentTarget),t){var n=t.ownerSVGElement||t;if(n.createSVGPoint){var r=n.createSVGPoint();return r.x=e.clientX,r.y=e.clientY,r=r.matrixTransform(t.getScreenCTM().inverse()),[r.x,r.y]}if(t.getBoundingClientRect){var i=t.getBoundingClientRect();return[e.clientX-i.left-t.clientLeft,e.clientY-i.top-t.clientTop]}}return[e.pageX,e.pageY]}const nYt={passive:!1},L2={capture:!0,passive:!1};function S8(e){e.stopImmediatePropagation()}function Jv(e){e.preventDefault(),e.stopImmediatePropagation()}function V5e(e){var t=e.document.documentElement,n=Zo(e).on("dragstart.drag",Jv,L2);"onselectstart"in t?n.on("selectstart.drag",Jv,L2):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function G5e(e,t){var n=e.document.documentElement,r=Zo(e).on("dragstart.drag",null);t&&(r.on("click.drag",Jv,L2),setTimeout(function(){r.on("click.drag",null)},0)),"onselectstart"in n?r.on("selectstart.drag",null):(n.style.MozUserSelect=n.__noselect,delete n.__noselect)}const MN=e=>()=>e;function qB(e,{sourceEvent:t,subject:n,target:r,identifier:i,active:a,x:s,y:o,dx:u,dy:c,dispatch:d}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},subject:{value:n,enumerable:!0,configurable:!0},target:{value:r,enumerable:!0,configurable:!0},identifier:{value:i,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:s,enumerable:!0,configurable:!0},y:{value:o,enumerable:!0,configurable:!0},dx:{value:u,enumerable:!0,configurable:!0},dy:{value:c,enumerable:!0,configurable:!0},_:{value:d}})}qB.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function rYt(e){return!e.ctrlKey&&!e.button}function iYt(){return this.parentNode}function aYt(e,t){return t??{x:e.x,y:e.y}}function sYt(){return navigator.maxTouchPoints||"ontouchstart"in this}function W5e(){var e=rYt,t=iYt,n=aYt,r=sYt,i={},a=IP("start","drag","end"),s=0,o,u,c,d,f=0;function p(T){T.on("mousedown.drag",m).filter(r).on("touchstart.drag",x).on("touchmove.drag",_,nYt).on("touchend.drag touchcancel.drag",S).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function m(T,N){if(!(d||!e.call(this,T,N))){var E=w(this,t.call(this,T,N),T,N,"mouse");E&&(Zo(T.view).on("mousemove.drag",y,L2).on("mouseup.drag",v,L2),V5e(T.view),S8(T),c=!1,o=T.clientX,u=T.clientY,E("start",T))}}function y(T){if(Jv(T),!c){var N=T.clientX-o,E=T.clientY-u;c=N*N+E*E>f}i.mouse("drag",T)}function v(T){Zo(T.view).on("mousemove.drag mouseup.drag",null),G5e(T.view,c),Jv(T),i.mouse("end",T)}function x(T,N){if(e.call(this,T,N)){var E=T.changedTouches,A=t.call(this,T,N),I=E.length,M,$;for(M=0;M<I;++M)($=w(this,A,T,N,E[M].identifier,E[M]))&&(S8(T),$("start",T,E[M]))}}function _(T){var N=T.changedTouches,E=N.length,A,I;for(A=0;A<E;++A)(I=i[N[A].identifier])&&(Jv(T),I("drag",T,N[A]))}function S(T){var N=T.changedTouches,E=N.length,A,I;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),A=0;A<E;++A)(I=i[N[A].identifier])&&(S8(T),I("end",T,N[A]))}function w(T,N,E,A,I,M){var $=a.copy(),O=uu(M||E,N),R,U,z;if((z=n.call(T,new qB("beforestart",{sourceEvent:E,target:p,identifier:I,active:s,x:O[0],y:O[1],dx:0,dy:0,dispatch:$}),A))!=null)return R=z.x-O[0]||0,U=z.y-O[1]||0,function F(D,W,q){var X=O,L;switch(D){case"start":i[I]=F,L=s++;break;case"end":delete i[I],--s;case"drag":O=uu(q||W,N),L=s;break}$.call(D,T,new qB(D,{sourceEvent:W,subject:z,target:p,identifier:I,active:L,x:O[0]+R,y:O[1]+U,dx:O[0]-X[0],dy:O[1]-X[1],dispatch:$}),A)}}return p.filter=function(T){return arguments.length?(e=typeof T=="function"?T:MN(!!T),p):e},p.container=function(T){return arguments.length?(t=typeof T=="function"?T:MN(T),p):t},p.subject=function(T){return arguments.length?(n=typeof T=="function"?T:MN(T),p):n},p.touchable=function(T){return arguments.length?(r=typeof T=="function"?T:MN(!!T),p):r},p.on=function(){var T=a.on.apply(a,arguments);return T===a?p:T},p.clickDistance=function(T){return arguments.length?(f=(T=+T)*T,p):Math.sqrt(f)},p}var Qy=0,w1=0,U_=0,K5e=1e3,zj,S1,Uj=0,fg=0,OP=0,z2=typeof performance=="object"&&performance.now?performance:Date,Z5e=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function DZ(){return fg||(Z5e(oYt),fg=z2.now()+OP)}function oYt(){fg=0}function Fj(){this._call=this._time=this._next=null}Fj.prototype=Y5e.prototype={constructor:Fj,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?DZ():+n)+(t==null?0:+t),!this._next&&S1!==this&&(S1?S1._next=this:zj=this,S1=this),this._call=e,this._time=n,HB()},stop:function(){this._call&&(this._call=null,this._time=1/0,HB())}};function Y5e(e,t,n){var r=new Fj;return r.restart(e,t,n),r}function lYt(){DZ(),++Qy;for(var e=zj,t;e;)(t=fg-e._time)>=0&&e._call.call(void 0,t),e=e._next;--Qy}function Ime(){fg=(Uj=z2.now())+OP,Qy=w1=0;try{lYt()}finally{Qy=0,cYt(),fg=0}}function uYt(){var e=z2.now(),t=e-Uj;t>K5e&&(OP-=t,Uj=e)}function cYt(){for(var e,t=zj,n,r=1/0;t;)t._call?(r>t._time&&(r=t._time),e=t,t=t._next):(n=t._next,t._next=null,t=e?e._next=n:zj=n);S1=e,HB(r)}function HB(e){if(!Qy){w1&&(w1=clearTimeout(w1));var t=e-fg;t>24?(e<1/0&&(w1=setTimeout(Ime,e-z2.now()-OP)),U_&&(U_=clearInterval(U_))):(U_||(Uj=z2.now(),U_=setInterval(uYt,K5e)),Qy=1,Z5e(Ime))}}function jme(e,t,n){var r=new Fj;return t=t==null?0:+t,r.restart(i=>{r.stop(),e(i+t)},t,n),r}var dYt=IP("start","end","cancel","interrupt"),fYt=[],X5e=0,Ome=1,VB=2,jC=3,Rme=4,GB=5,OC=6;function RP(e,t,n,r,i,a){var s=e.__transition;if(!s)e.__transition={};else if(n in s)return;pYt(e,n,{name:t,index:r,group:i,on:dYt,tween:fYt,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:X5e})}function LZ(e,t){var n=Bu(e,t);if(n.state>X5e)throw new Error("too late; already scheduled");return n}function Kc(e,t){var n=Bu(e,t);if(n.state>jC)throw new Error("too late; already running");return n}function Bu(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function pYt(e,t,n){var r=e.__transition,i;r[t]=n,n.timer=Y5e(a,0,n.time);function a(c){n.state=Ome,n.timer.restart(s,n.delay,n.time),n.delay<=c&&s(c-n.delay)}function s(c){var d,f,p,m;if(n.state!==Ome)return u();for(d in r)if(m=r[d],m.name===n.name){if(m.state===jC)return jme(s);m.state===Rme?(m.state=OC,m.timer.stop(),m.on.call("interrupt",e,e.__data__,m.index,m.group),delete r[d]):+d<t&&(m.state=OC,m.timer.stop(),m.on.call("cancel",e,e.__data__,m.index,m.group),delete r[d])}if(jme(function(){n.state===jC&&(n.state=Rme,n.timer.restart(o,n.delay,n.time),o(c))}),n.state=VB,n.on.call("start",e,e.__data__,n.index,n.group),n.state===VB){for(n.state=jC,i=new Array(p=n.tween.length),d=0,f=-1;d<p;++d)(m=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(i[++f]=m);i.length=f+1}}function o(c){for(var d=c<n.duration?n.ease.call(null,c/n.duration):(n.timer.restart(u),n.state=GB,1),f=-1,p=i.length;++f<p;)i[f].call(e,d);n.state===GB&&(n.on.call("end",e,e.__data__,n.index,n.group),u())}function u(){n.state=OC,n.timer.stop(),delete r[t];for(var c in r)return;delete e.__transition}}function RC(e,t){var n=e.__transition,r,i,a=!0,s;if(n){t=t==null?null:t+"";for(s in n){if((r=n[s]).name!==t){a=!1;continue}i=r.state>VB&&r.state<GB,r.state=OC,r.timer.stop(),r.on.call(i?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[s]}a&&delete e.__transition}}function hYt(e){return this.each(function(){RC(this,e)})}function mYt(e,t){var n,r;return function(){var i=Kc(this,e),a=i.tween;if(a!==n){r=n=a;for(var s=0,o=r.length;s<o;++s)if(r[s].name===t){r=r.slice(),r.splice(s,1);break}}i.tween=r}}function gYt(e,t,n){var r,i;if(typeof n!="function")throw new Error;return function(){var a=Kc(this,e),s=a.tween;if(s!==r){i=(r=s).slice();for(var o={name:t,value:n},u=0,c=i.length;u<c;++u)if(i[u].name===t){i[u]=o;break}u===c&&i.push(o)}a.tween=i}}function vYt(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=Bu(this.node(),n).tween,i=0,a=r.length,s;i<a;++i)if((s=r[i]).name===e)return s.value;return null}return this.each((t==null?mYt:gYt)(n,e,t))}function zZ(e,t,n){var r=e._id;return e.each(function(){var i=Kc(this,r);(i.value||(i.value={}))[t]=n.apply(this,arguments)}),function(i){return Bu(i,r).value[t]}}function J5e(e,t){var n;return(typeof t=="number"?mu:t instanceof og?JI:(n=og(t))?(t=n,JI):Y4e)(e,t)}function yYt(e){return function(){this.removeAttribute(e)}}function xYt(e){return function(){this.removeAttributeNS(e.space,e.local)}}function bYt(e,t,n){var r,i=n+"",a;return function(){var s=this.getAttribute(e);return s===i?null:s===r?a:a=t(r=s,n)}}function _Yt(e,t,n){var r,i=n+"",a;return function(){var s=this.getAttributeNS(e.space,e.local);return s===i?null:s===r?a:a=t(r=s,n)}}function wYt(e,t,n){var r,i,a;return function(){var s,o=n(this),u;return o==null?void this.removeAttribute(e):(s=this.getAttribute(e),u=o+"",s===u?null:s===r&&u===i?a:(i=u,a=t(r=s,o)))}}function SYt(e,t,n){var r,i,a;return function(){var s,o=n(this),u;return o==null?void this.removeAttributeNS(e.space,e.local):(s=this.getAttributeNS(e.space,e.local),u=o+"",s===u?null:s===r&&u===i?a:(i=u,a=t(r=s,o)))}}function kYt(e,t){var n=jP(e),r=n==="transform"?U6t:J5e;return this.attrTween(e,typeof t=="function"?(n.local?SYt:wYt)(n,r,zZ(this,"attr."+e,t)):t==null?(n.local?xYt:yYt)(n):(n.local?_Yt:bYt)(n,r,t))}function EYt(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function TYt(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function NYt(e,t){var n,r;function i(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&TYt(e,a)),n}return i._value=t,i}function CYt(e,t){var n,r;function i(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&EYt(e,a)),n}return i._value=t,i}function AYt(e,t){var n="attr."+e;if(arguments.length<2)return(n=this.tween(n))&&n._value;if(t==null)return this.tween(n,null);if(typeof t!="function")throw new Error;var r=jP(e);return this.tween(n,(r.local?NYt:CYt)(r,t))}function IYt(e,t){return function(){LZ(this,e).delay=+t.apply(this,arguments)}}function jYt(e,t){return t=+t,function(){LZ(this,e).delay=t}}function OYt(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?IYt:jYt)(t,e)):Bu(this.node(),t).delay}function RYt(e,t){return function(){Kc(this,e).duration=+t.apply(this,arguments)}}function PYt(e,t){return t=+t,function(){Kc(this,e).duration=t}}function $Yt(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?RYt:PYt)(t,e)):Bu(this.node(),t).duration}function MYt(e,t){if(typeof t!="function")throw new Error;return function(){Kc(this,e).ease=t}}function DYt(e){var t=this._id;return arguments.length?this.each(MYt(t,e)):Bu(this.node(),t).ease}function LYt(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Kc(this,e).ease=n}}function zYt(e){if(typeof e!="function")throw new Error;return this.each(LYt(this._id,e))}function UYt(e){typeof e!="function"&&(e=$5e(e));for(var t=this._groups,n=t.length,r=new Array(n),i=0;i<n;++i)for(var a=t[i],s=a.length,o=r[i]=[],u,c=0;c<s;++c)(u=a[c])&&e.call(u,u.__data__,c,a)&&o.push(u);return new of(r,this._parents,this._name,this._id)}function FYt(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,i=n.length,a=Math.min(r,i),s=new Array(r),o=0;o<a;++o)for(var u=t[o],c=n[o],d=u.length,f=s[o]=new Array(d),p,m=0;m<d;++m)(p=u[m]||c[m])&&(f[m]=p);for(;o<r;++o)s[o]=t[o];return new of(s,this._parents,this._name,this._id)}function BYt(e){return(e+"").trim().split(/^|\s+/).every(function(t){var n=t.indexOf(".");return n>=0&&(t=t.slice(0,n)),!t||t==="start"})}function qYt(e,t,n){var r,i,a=BYt(t)?LZ:Kc;return function(){var s=a(this,e),o=s.on;o!==r&&(i=(r=o).copy()).on(t,n),s.on=i}}function HYt(e,t){var n=this._id;return arguments.length<2?Bu(this.node(),n).on.on(e):this.each(qYt(n,e,t))}function VYt(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function GYt(){return this.on("end.remove",VYt(this._id))}function WYt(e){var t=this._name,n=this._id;typeof e!="function"&&(e=$Z(e));for(var r=this._groups,i=r.length,a=new Array(i),s=0;s<i;++s)for(var o=r[s],u=o.length,c=a[s]=new Array(u),d,f,p=0;p<u;++p)(d=o[p])&&(f=e.call(d,d.__data__,p,o))&&("__data__"in d&&(f.__data__=d.__data__),c[p]=f,RP(c[p],t,n,p,c,Bu(d,n)));return new of(a,this._parents,t,n)}function KYt(e){var t=this._name,n=this._id;typeof e!="function"&&(e=P5e(e));for(var r=this._groups,i=r.length,a=[],s=[],o=0;o<i;++o)for(var u=r[o],c=u.length,d,f=0;f<c;++f)if(d=u[f]){for(var p=e.call(d,d.__data__,f,u),m,y=Bu(d,n),v=0,x=p.length;v<x;++v)(m=p[v])&&RP(m,t,n,v,p,y);a.push(p),s.push(d)}return new of(a,s,t,n)}var ZYt=xk.prototype.constructor;function YYt(){return new ZYt(this._groups,this._parents)}function XYt(e,t){var n,r,i;return function(){var a=Jy(this,e),s=(this.style.removeProperty(e),Jy(this,e));return a===s?null:a===n&&s===r?i:i=t(n=a,r=s)}}function Q5e(e){return function(){this.style.removeProperty(e)}}function JYt(e,t,n){var r,i=n+"",a;return function(){var s=Jy(this,e);return s===i?null:s===r?a:a=t(r=s,n)}}function QYt(e,t,n){var r,i,a;return function(){var s=Jy(this,e),o=n(this),u=o+"";return o==null&&(u=o=(this.style.removeProperty(e),Jy(this,e))),s===u?null:s===r&&u===i?a:(i=u,a=t(r=s,o))}}function eXt(e,t){var n,r,i,a="style."+t,s="end."+a,o;return function(){var u=Kc(this,e),c=u.on,d=u.value[a]==null?o||(o=Q5e(t)):void 0;(c!==n||i!==d)&&(r=(n=c).copy()).on(s,i=d),u.on=r}}function tXt(e,t,n){var r=(e+="")=="transform"?z6t:J5e;return t==null?this.styleTween(e,XYt(e,r)).on("end.style."+e,Q5e(e)):typeof t=="function"?this.styleTween(e,QYt(e,r,zZ(this,"style."+e,t))).each(eXt(this._id,e)):this.styleTween(e,JYt(e,r,t),n).on("end.style."+e,null)}function nXt(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function rXt(e,t,n){var r,i;function a(){var s=t.apply(this,arguments);return s!==i&&(r=(i=s)&&nXt(e,s,n)),r}return a._value=t,a}function iXt(e,t,n){var r="style."+(e+="");if(arguments.length<2)return(r=this.tween(r))&&r._value;if(t==null)return this.tween(r,null);if(typeof t!="function")throw new Error;return this.tween(r,rXt(e,t,n??""))}function aXt(e){return function(){this.textContent=e}}function sXt(e){return function(){var t=e(this);this.textContent=t??""}}function oXt(e){return this.tween("text",typeof e=="function"?sXt(zZ(this,"text",e)):aXt(e==null?"":e+""))}function lXt(e){return function(t){this.textContent=e.call(this,t)}}function uXt(e){var t,n;function r(){var i=e.apply(this,arguments);return i!==n&&(t=(n=i)&&lXt(i)),t}return r._value=e,r}function cXt(e){var t="text";if(arguments.length<1)return(t=this.tween(t))&&t._value;if(e==null)return this.tween(t,null);if(typeof e!="function")throw new Error;return this.tween(t,uXt(e))}function dXt(){for(var e=this._name,t=this._id,n=eDe(),r=this._groups,i=r.length,a=0;a<i;++a)for(var s=r[a],o=s.length,u,c=0;c<o;++c)if(u=s[c]){var d=Bu(u,t);RP(u,e,n,c,s,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new of(r,this._parents,e,n)}function fXt(){var e,t,n=this,r=n._id,i=n.size();return new Promise(function(a,s){var o={value:s},u={value:function(){--i===0&&a()}};n.each(function(){var c=Kc(this,r),d=c.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(o),t._.interrupt.push(o),t._.end.push(u)),c.on=t}),i===0&&a()})}var pXt=0;function of(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function eDe(){return++pXt}var _d=xk.prototype;of.prototype={constructor:of,select:WYt,selectAll:KYt,selectChild:_d.selectChild,selectChildren:_d.selectChildren,filter:UYt,merge:FYt,selection:YYt,transition:dXt,call:_d.call,nodes:_d.nodes,node:_d.node,size:_d.size,empty:_d.empty,each:_d.each,on:HYt,attr:kYt,attrTween:AYt,style:tXt,styleTween:iXt,text:oXt,textTween:cXt,remove:GYt,tween:vYt,delay:OYt,duration:$Yt,ease:DYt,easeVarying:zYt,end:fXt,[Symbol.iterator]:_d[Symbol.iterator]};function hXt(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var mXt={time:null,delay:0,duration:250,ease:hXt};function gXt(e,t){for(var n;!(n=e.__transition)||!(n=n[t]);)if(!(e=e.parentNode))throw new Error(`transition ${t} not found`);return n}function vXt(e){var t,n;e instanceof of?(t=e._id,e=e._name):(t=eDe(),(n=mXt).time=DZ(),e=e==null?null:e+"");for(var r=this._groups,i=r.length,a=0;a<i;++a)for(var s=r[a],o=s.length,u,c=0;c<o;++c)(u=s[c])&&RP(u,e,t,c,s,n||gXt(u,t));return new of(r,this._parents,e,t)}xk.prototype.interrupt=hYt;xk.prototype.transition=vXt;const DN=e=>()=>e;function yXt(e,{sourceEvent:t,target:n,transform:r,dispatch:i}){Object.defineProperties(this,{type:{value:e,enumerable:!0,configurable:!0},sourceEvent:{value:t,enumerable:!0,configurable:!0},target:{value:n,enumerable:!0,configurable:!0},transform:{value:r,enumerable:!0,configurable:!0},_:{value:i}})}function Bd(e,t,n){this.k=e,this.x=t,this.y=n}Bd.prototype={constructor:Bd,scale:function(e){return e===1?this:new Bd(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new Bd(this.k,this.x+this.k*e,this.y+this.k*t)},apply:function(e){return[e[0]*this.k+this.x,e[1]*this.k+this.y]},applyX:function(e){return e*this.k+this.x},applyY:function(e){return e*this.k+this.y},invert:function(e){return[(e[0]-this.x)/this.k,(e[1]-this.y)/this.k]},invertX:function(e){return(e-this.x)/this.k},invertY:function(e){return(e-this.y)/this.k},rescaleX:function(e){return e.copy().domain(e.range().map(this.invertX,this).map(e.invert,e))},rescaleY:function(e){return e.copy().domain(e.range().map(this.invertY,this).map(e.invert,e))},toString:function(){return"translate("+this.x+","+this.y+") scale("+this.k+")"}};var PP=new Bd(1,0,0);tDe.prototype=Bd.prototype;function tDe(e){for(;!e.__zoom;)if(!(e=e.parentNode))return PP;return e.__zoom}function k8(e){e.stopImmediatePropagation()}function F_(e){e.preventDefault(),e.stopImmediatePropagation()}function xXt(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function bXt(){var e=this;return e instanceof SVGElement?(e=e.ownerSVGElement||e,e.hasAttribute("viewBox")?(e=e.viewBox.baseVal,[[e.x,e.y],[e.x+e.width,e.y+e.height]]):[[0,0],[e.width.baseVal.value,e.height.baseVal.value]]):[[0,0],[e.clientWidth,e.clientHeight]]}function Pme(){return this.__zoom||PP}function _Xt(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function wXt(){return navigator.maxTouchPoints||"ontouchstart"in this}function SXt(e,t,n){var r=e.invertX(t[0][0])-n[0][0],i=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],s=e.invertY(t[1][1])-n[1][1];return e.translate(i>r?(r+i)/2:Math.min(0,r)||Math.max(0,i),s>a?(a+s)/2:Math.min(0,a)||Math.max(0,s))}function nDe(){var e=xXt,t=bXt,n=SXt,r=_Xt,i=wXt,a=[0,1/0],s=[[-1/0,-1/0],[1/0,1/0]],o=250,u=TC,c=IP("start","zoom","end"),d,f,p,m=500,y=150,v=0,x=10;function _(z){z.property("__zoom",Pme).on("wheel.zoom",I,{passive:!1}).on("mousedown.zoom",M).on("dblclick.zoom",$).filter(i).on("touchstart.zoom",O).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",U).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}_.transform=function(z,F,D,W){var q=z.selection?z.selection():z;q.property("__zoom",Pme),z!==q?N(z,F,D,W):q.interrupt().each(function(){E(this,arguments).event(W).start().zoom(null,typeof F=="function"?F.apply(this,arguments):F).end()})},_.scaleBy=function(z,F,D,W){_.scaleTo(z,function(){var q=this.__zoom.k,X=typeof F=="function"?F.apply(this,arguments):F;return q*X},D,W)},_.scaleTo=function(z,F,D,W){_.transform(z,function(){var q=t.apply(this,arguments),X=this.__zoom,L=D==null?T(q):typeof D=="function"?D.apply(this,arguments):D,Y=X.invert(L),G=typeof F=="function"?F.apply(this,arguments):F;return n(w(S(X,G),L,Y),q,s)},D,W)},_.translateBy=function(z,F,D,W){_.transform(z,function(){return n(this.__zoom.translate(typeof F=="function"?F.apply(this,arguments):F,typeof D=="function"?D.apply(this,arguments):D),t.apply(this,arguments),s)},null,W)},_.translateTo=function(z,F,D,W,q){_.transform(z,function(){var X=t.apply(this,arguments),L=this.__zoom,Y=W==null?T(X):typeof W=="function"?W.apply(this,arguments):W;return n(PP.translate(Y[0],Y[1]).scale(L.k).translate(typeof F=="function"?-F.apply(this,arguments):-F,typeof D=="function"?-D.apply(this,arguments):-D),X,s)},W,q)};function S(z,F){return F=Math.max(a[0],Math.min(a[1],F)),F===z.k?z:new Bd(F,z.x,z.y)}function w(z,F,D){var W=F[0]-D[0]*z.k,q=F[1]-D[1]*z.k;return W===z.x&&q===z.y?z:new Bd(z.k,W,q)}function T(z){return[(+z[0][0]+ +z[1][0])/2,(+z[0][1]+ +z[1][1])/2]}function N(z,F,D,W){z.on("start.zoom",function(){E(this,arguments).event(W).start()}).on("interrupt.zoom end.zoom",function(){E(this,arguments).event(W).end()}).tween("zoom",function(){var q=this,X=arguments,L=E(q,X).event(W),Y=t.apply(q,X),G=D==null?T(Y):typeof D=="function"?D.apply(q,X):D,P=Math.max(Y[1][0]-Y[0][0],Y[1][1]-Y[0][1]),V=q.__zoom,K=typeof F=="function"?F.apply(q,X):F,Q=u(V.invert(G).concat(P/V.k),K.invert(G).concat(P/K.k));return function(oe){if(oe===1)oe=K;else{var re=Q(oe),ee=P/re[2];oe=new Bd(ee,G[0]-re[0]*ee,G[1]-re[1]*ee)}L.zoom(null,oe)}})}function E(z,F,D){return!D&&z.__zooming||new A(z,F)}function A(z,F){this.that=z,this.args=F,this.active=0,this.sourceEvent=null,this.extent=t.apply(z,F),this.taps=0}A.prototype={event:function(z){return z&&(this.sourceEvent=z),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(z,F){return this.mouse&&z!=="mouse"&&(this.mouse[1]=F.invert(this.mouse[0])),this.touch0&&z!=="touch"&&(this.touch0[1]=F.invert(this.touch0[0])),this.touch1&&z!=="touch"&&(this.touch1[1]=F.invert(this.touch1[0])),this.that.__zoom=F,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(z){var F=Zo(this.that).datum();c.call(z,this.that,new yXt(z,{sourceEvent:this.sourceEvent,target:_,transform:this.that.__zoom,dispatch:c}),F)}};function I(z,...F){if(!e.apply(this,arguments))return;var D=E(this,F).event(z),W=this.__zoom,q=Math.max(a[0],Math.min(a[1],W.k*Math.pow(2,r.apply(this,arguments)))),X=uu(z);if(D.wheel)(D.mouse[0][0]!==X[0]||D.mouse[0][1]!==X[1])&&(D.mouse[1]=W.invert(D.mouse[0]=X)),clearTimeout(D.wheel);else{if(W.k===q)return;D.mouse=[X,W.invert(X)],RC(this),D.start()}F_(z),D.wheel=setTimeout(L,y),D.zoom("mouse",n(w(S(W,q),D.mouse[0],D.mouse[1]),D.extent,s));function L(){D.wheel=null,D.end()}}function M(z,...F){if(p||!e.apply(this,arguments))return;var D=z.currentTarget,W=E(this,F,!0).event(z),q=Zo(z.view).on("mousemove.zoom",G,!0).on("mouseup.zoom",P,!0),X=uu(z,D),L=z.clientX,Y=z.clientY;V5e(z.view),k8(z),W.mouse=[X,this.__zoom.invert(X)],RC(this),W.start();function G(V){if(F_(V),!W.moved){var K=V.clientX-L,Q=V.clientY-Y;W.moved=K*K+Q*Q>v}W.event(V).zoom("mouse",n(w(W.that.__zoom,W.mouse[0]=uu(V,D),W.mouse[1]),W.extent,s))}function P(V){q.on("mousemove.zoom mouseup.zoom",null),G5e(V.view,W.moved),F_(V),W.event(V).end()}}function $(z,...F){if(e.apply(this,arguments)){var D=this.__zoom,W=uu(z.changedTouches?z.changedTouches[0]:z,this),q=D.invert(W),X=D.k*(z.shiftKey?.5:2),L=n(w(S(D,X),W,q),t.apply(this,F),s);F_(z),o>0?Zo(this).transition().duration(o).call(N,L,W,z):Zo(this).call(_.transform,L,W,z)}}function O(z,...F){if(e.apply(this,arguments)){var D=z.touches,W=D.length,q=E(this,F,z.changedTouches.length===W).event(z),X,L,Y,G;for(k8(z),L=0;L<W;++L)Y=D[L],G=uu(Y,this),G=[G,this.__zoom.invert(G),Y.identifier],q.touch0?!q.touch1&&q.touch0[2]!==G[2]&&(q.touch1=G,q.taps=0):(q.touch0=G,X=!0,q.taps=1+!!d);d&&(d=clearTimeout(d)),X&&(q.taps<2&&(f=G[0],d=setTimeout(function(){d=null},m)),RC(this),q.start())}}function R(z,...F){if(this.__zooming){var D=E(this,F).event(z),W=z.changedTouches,q=W.length,X,L,Y,G;for(F_(z),X=0;X<q;++X)L=W[X],Y=uu(L,this),D.touch0&&D.touch0[2]===L.identifier?D.touch0[0]=Y:D.touch1&&D.touch1[2]===L.identifier&&(D.touch1[0]=Y);if(L=D.that.__zoom,D.touch1){var P=D.touch0[0],V=D.touch0[1],K=D.touch1[0],Q=D.touch1[1],oe=(oe=K[0]-P[0])*oe+(oe=K[1]-P[1])*oe,re=(re=Q[0]-V[0])*re+(re=Q[1]-V[1])*re;L=S(L,Math.sqrt(oe/re)),Y=[(P[0]+K[0])/2,(P[1]+K[1])/2],G=[(V[0]+Q[0])/2,(V[1]+Q[1])/2]}else if(D.touch0)Y=D.touch0[0],G=D.touch0[1];else return;D.zoom("touch",n(w(L,Y,G),D.extent,s))}}function U(z,...F){if(this.__zooming){var D=E(this,F).event(z),W=z.changedTouches,q=W.length,X,L;for(k8(z),p&&clearTimeout(p),p=setTimeout(function(){p=null},m),X=0;X<q;++X)L=W[X],D.touch0&&D.touch0[2]===L.identifier?delete D.touch0:D.touch1&&D.touch1[2]===L.identifier&&delete D.touch1;if(D.touch1&&!D.touch0&&(D.touch0=D.touch1,delete D.touch1),D.touch0)D.touch0[1]=this.__zoom.invert(D.touch0[0]);else if(D.end(),D.taps===2&&(L=uu(L,this),Math.hypot(f[0]-L[0],f[1]-L[1])<x)){var Y=Zo(this).on("dblclick.zoom");Y&&Y.apply(this,arguments)}}}return _.wheelDelta=function(z){return arguments.length?(r=typeof z=="function"?z:DN(+z),_):r},_.filter=function(z){return arguments.length?(e=typeof z=="function"?z:DN(!!z),_):e},_.touchable=function(z){return arguments.length?(i=typeof z=="function"?z:DN(!!z),_):i},_.extent=function(z){return arguments.length?(t=typeof z=="function"?z:DN([[+z[0][0],+z[0][1]],[+z[1][0],+z[1][1]]]),_):t},_.scaleExtent=function(z){return arguments.length?(a[0]=+z[0],a[1]=+z[1],_):[a[0],a[1]]},_.translateExtent=function(z){return arguments.length?(s[0][0]=+z[0][0],s[1][0]=+z[1][0],s[0][1]=+z[0][1],s[1][1]=+z[1][1],_):[[s[0][0],s[0][1]],[s[1][0],s[1][1]]]},_.constrain=function(z){return arguments.length?(n=z,_):n},_.duration=function(z){return arguments.length?(o=+z,_):o},_.interpolate=function(z){return arguments.length?(u=z,_):u},_.on=function(){var z=c.on.apply(c,arguments);return z===c?_:z},_.clickDistance=function(z){return arguments.length?(v=(z=+z)*z,_):Math.sqrt(v)},_.tapDistance=function(z){return arguments.length?(x=+z,_):x},_}const Dc={error001:()=>"[React Flow]: Seems like you have not used zustand provider as an ancestor. Help: https://reactflow.dev/error#001",error002:()=>"It looks like you've created a new nodeTypes or edgeTypes object. If this wasn't on purpose please define the nodeTypes/edgeTypes outside of the component or memoize them.",error003:e=>`Node type "${e}" not found. Using fallback type "default".`,error004:()=>"The React Flow parent container needs a width and a height to render the graph.",error005:()=>"Only child nodes can use a parent extent.",error006:()=>"Can't create edge. An edge needs a source and a target.",error007:e=>`The old edge with id=${e} does not exist.`,error009:e=>`Marker type "${e}" doesn't exist.`,error008:(e,{id:t,sourceHandle:n,targetHandle:r})=>`Couldn't create edge for ${e} handle id: "${e==="source"?n:r}", edge id: ${t}.`,error010:()=>"Handle: No node id found. Make sure to only use a Handle inside a custom Node.",error011:e=>`Edge type "${e}" not found. Using fallback type "default".`,error012:e=>`Node with id "${e}" does not exist, it may have been removed. This can happen when a node is deleted before the "onNodeClick" handler is called.`,error013:(e="react")=>`It seems that you haven't loaded the styles. Please import '@xyflow/${e}/dist/style.css' or base.css to make sure everything is working properly.`,error014:()=>"useNodeConnections: No node ID found. Call useNodeConnections inside a custom Node or provide a node ID.",error015:()=>"It seems that you are trying to drag a node that is not initialized. Please use onNodesChange as explained in the docs."},U2=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],rDe=["Enter"," ","Escape"],iDe={"node.a11yDescription.default":"Press enter or space to select a node. Press delete to remove it and escape to cancel.","node.a11yDescription.keyboardDisabled":"Press enter or space to select a node. You can then use the arrow keys to move the node around. Press delete to remove it and escape to cancel.","node.a11yDescription.ariaLiveMessage":({direction:e,x:t,y:n})=>`Moved selected node ${e}. New position, x: ${t}, y: ${n}`,"edge.a11yDescription.default":"Press enter or space to select an edge. You can then press delete to remove it or escape to cancel.","controls.ariaLabel":"Control Panel","controls.zoomIn.ariaLabel":"Zoom In","controls.zoomOut.ariaLabel":"Zoom Out","controls.fitView.ariaLabel":"Fit View","controls.interactive.ariaLabel":"Toggle Interactivity","minimap.ariaLabel":"Mini Map","handle.ariaLabel":"Handle"};var ex;(function(e){e.Strict="strict",e.Loose="loose"})(ex||(ex={}));var Cm;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(Cm||(Cm={}));var F2;(function(e){e.Partial="partial",e.Full="full"})(F2||(F2={}));const aDe={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var bp;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(bp||(bp={}));var Bj;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(Bj||(Bj={}));var Ut;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(Ut||(Ut={}));const $me={[Ut.Left]:Ut.Right,[Ut.Right]:Ut.Left,[Ut.Top]:Ut.Bottom,[Ut.Bottom]:Ut.Top};function sDe(e){return e===null?null:e?"valid":"invalid"}const oDe=e=>"id"in e&&"source"in e&&"target"in e,kXt=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),UZ=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),bk=(e,t=[0,0])=>{const{width:n,height:r}=wf(e),i=e.origin??t,a=n*i[0],s=r*i[1];return{x:e.position.x-a,y:e.position.y-s}},EXt=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,i)=>{const a=typeof i=="string";let s=!t.nodeLookup&&!a?i:void 0;t.nodeLookup&&(s=a?t.nodeLookup.get(i):UZ(i)?i:t.nodeLookup.get(i.id));const o=s?qj(s,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return $P(r,o)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return MP(n)},_k=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(i=>{(t.filter===void 0||t.filter(i))&&(n=$P(n,qj(i)),r=!0)}),r?MP(n):{x:0,y:0,width:0,height:0}},FZ=(e,t,[n,r,i]=[0,0,1],a=!1,s=!1)=>{const o={...Sk(t,[n,r,i]),width:t.width/i,height:t.height/i},u=[];for(const c of e.values()){const{measured:d,selectable:f=!0,hidden:p=!1}=c;if(s&&!f||p)continue;const m=d.width??c.width??c.initialWidth??null,y=d.height??c.height??c.initialHeight??null,v=B2(o,nx(c)),x=(m??0)*(y??0),_=a&&v>0;(!c.internals.handleBounds||_||v>=x||c.dragging)&&u.push(c)}return u},TXt=(e,t)=>{const n=new Set;return e.forEach(r=>{n.add(r.id)}),t.filter(r=>n.has(r.source)||n.has(r.target))};function NXt(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map(i=>i.id)):null;return e.forEach(i=>{i.measured.width&&i.measured.height&&(t?.includeHiddenNodes||!i.hidden)&&(!r||r.has(i.id))&&n.set(i.id,i)}),n}async function CXt({nodes:e,width:t,height:n,panZoom:r,minZoom:i,maxZoom:a},s){if(e.size===0)return Promise.resolve(!0);const o=NXt(e,s),u=_k(o),c=BZ(u,t,n,s?.minZoom??i,s?.maxZoom??a,s?.padding??.1);return await r.setViewport(c,{duration:s?.duration,ease:s?.ease,interpolate:s?.interpolate}),Promise.resolve(!0)}function lDe({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:i,onError:a}){const s=n.get(e),o=s.parentId?n.get(s.parentId):void 0,{x:u,y:c}=o?o.internals.positionAbsolute:{x:0,y:0},d=s.origin??r;let f=s.extent||i;if(s.extent==="parent"&&!s.expandParent)if(!o)a?.("005",Dc.error005());else{const m=o.measured.width,y=o.measured.height;m&&y&&(f=[[u,c],[u+m,c+y]])}else o&&rx(s.extent)&&(f=[[s.extent[0][0]+u,s.extent[0][1]+c],[s.extent[1][0]+u,s.extent[1][1]+c]]);const p=rx(f)?pg(t,f,s.measured):t;return(s.measured.width===void 0||s.measured.height===void 0)&&a?.("015",Dc.error015()),{position:{x:p.x-u+(s.measured.width??0)*d[0],y:p.y-c+(s.measured.height??0)*d[1]},positionAbsolute:p}}async function AXt({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:i}){const a=new Set(e.map(p=>p.id)),s=[];for(const p of n){if(p.deletable===!1)continue;const m=a.has(p.id),y=!m&&p.parentId&&s.find(v=>v.id===p.parentId);(m||y)&&s.push(p)}const o=new Set(t.map(p=>p.id)),u=r.filter(p=>p.deletable!==!1),d=TXt(s,u);for(const p of u)o.has(p.id)&&!d.find(y=>y.id===p.id)&&d.push(p);if(!i)return{edges:d,nodes:s};const f=await i({nodes:s,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:s}:{edges:[],nodes:[]}:f}const tx=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),pg=(e={x:0,y:0},t,n)=>({x:tx(e.x,t[0][0],t[1][0]-(n?.width??0)),y:tx(e.y,t[0][1],t[1][1]-(n?.height??0))});function uDe(e,t,n){const{width:r,height:i}=wf(n),{x:a,y:s}=n.internals.positionAbsolute;return pg(e,[[a,s],[a+r,s+i]],t)}const Mme=(e,t,n)=>e<t?tx(Math.abs(e-t),1,t)/t:e>n?-tx(Math.abs(e-n),1,t)/t:0,cDe=(e,t,n=15,r=40)=>{const i=Mme(e.x,r,t.width-r)*n,a=Mme(e.y,r,t.height-r)*n;return[i,a]},$P=(e,t)=>({x:Math.min(e.x,t.x),y:Math.min(e.y,t.y),x2:Math.max(e.x2,t.x2),y2:Math.max(e.y2,t.y2)}),WB=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),MP=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),nx=(e,t=[0,0])=>{const{x:n,y:r}=UZ(e)?e.internals.positionAbsolute:bk(e,t);return{x:n,y:r,width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}},qj=(e,t=[0,0])=>{const{x:n,y:r}=UZ(e)?e.internals.positionAbsolute:bk(e,t);return{x:n,y:r,x2:n+(e.measured?.width??e.width??e.initialWidth??0),y2:r+(e.measured?.height??e.height??e.initialHeight??0)}},dDe=(e,t)=>MP($P(WB(e),WB(t))),B2=(e,t)=>{const n=Math.max(0,Math.min(e.x+e.width,t.x+t.width)-Math.max(e.x,t.x)),r=Math.max(0,Math.min(e.y+e.height,t.y+t.height)-Math.max(e.y,t.y));return Math.ceil(n*r)},Dme=e=>_u(e.width)&&_u(e.height)&&_u(e.x)&&_u(e.y),_u=e=>!isNaN(e)&&isFinite(e),IXt=(e,t)=>{},wk=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),Sk=({x:e,y:t},[n,r,i],a=!1,s=[1,1])=>{const o={x:(e-n)/i,y:(t-r)/i};return a?wk(o,s):o},Hj=({x:e,y:t},[n,r,i])=>({x:e*i+n,y:t*i+r});function W0(e,t){if(typeof e=="number")return Math.floor((t-t/(1+e))*.5);if(typeof e=="string"&&e.endsWith("px")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(n)}if(typeof e=="string"&&e.endsWith("%")){const n=parseFloat(e);if(!Number.isNaN(n))return Math.floor(t*n*.01)}return console.error(`[React Flow] The padding value "${e}" is invalid. Please provide a number or a string with a valid unit (px or %).`),0}function jXt(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=W0(e,n),i=W0(e,t);return{top:r,right:i,bottom:r,left:i,x:i*2,y:r*2}}if(typeof e=="object"){const r=W0(e.top??e.y??0,n),i=W0(e.bottom??e.y??0,n),a=W0(e.left??e.x??0,t),s=W0(e.right??e.x??0,t);return{top:r,right:s,bottom:i,left:a,x:a+s,y:r+i}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function OXt(e,t,n,r,i,a){const{x:s,y:o}=Hj(e,[t,n,r]),{x:u,y:c}=Hj({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=i-u,f=a-c;return{left:Math.floor(s),top:Math.floor(o),right:Math.floor(d),bottom:Math.floor(f)}}const BZ=(e,t,n,r,i,a)=>{const s=jXt(a,t,n),o=(t-s.x)/e.width,u=(n-s.y)/e.height,c=Math.min(o,u),d=tx(c,r,i),f=e.x+e.width/2,p=e.y+e.height/2,m=t/2-f*d,y=n/2-p*d,v=OXt(e,m,y,d,t,n),x={left:Math.min(v.left-s.left,0),top:Math.min(v.top-s.top,0),right:Math.min(v.right-s.right,0),bottom:Math.min(v.bottom-s.bottom,0)};return{x:m-x.left+x.right,y:y-x.top+x.bottom,zoom:d}},q2=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function rx(e){return e!=null&&e!=="parent"}function wf(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function fDe(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function pDe(e,t={width:0,height:0},n,r,i){const a={...e},s=r.get(n);if(s){const o=s.origin||i;a.x+=s.internals.positionAbsolute.x-(t.width??0)*o[0],a.y+=s.internals.positionAbsolute.y-(t.height??0)*o[1]}return a}function Lme(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function RXt(){let e,t;return{promise:new Promise((r,i)=>{e=r,t=i}),resolve:e,reject:t}}function PXt(e){return{...iDe,...e||{}}}function ow(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:i}){const{x:a,y:s}=wu(e),o=Sk({x:a-(i?.left??0),y:s-(i?.top??0)},r),{x:u,y:c}=n?wk(o,t):o;return{xSnapped:u,ySnapped:c,...o}}const qZ=e=>({width:e.offsetWidth,height:e.offsetHeight}),hDe=e=>e?.getRootNode?.()||window?.document,$Xt=["INPUT","SELECT","TEXTAREA"];function mDe(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:$Xt.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const gDe=e=>"clientX"in e,wu=(e,t)=>{const n=gDe(e),r=n?e.clientX:e.touches?.[0].clientX,i=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:i-(t?.top??0)}},zme=(e,t,n,r,i)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(s=>{const o=s.getBoundingClientRect();return{id:s.getAttribute("data-handleid"),type:e,nodeId:i,position:s.getAttribute("data-handlepos"),x:(o.left-n.left)/r,y:(o.top-n.top)/r,...qZ(s)}})};function vDe({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:i,sourceControlY:a,targetControlX:s,targetControlY:o}){const u=e*.125+i*.375+s*.375+n*.125,c=t*.125+a*.375+o*.375+r*.125,d=Math.abs(u-e),f=Math.abs(c-t);return[u,c,d,f]}function LN(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function Ume({pos:e,x1:t,y1:n,x2:r,y2:i,c:a}){switch(e){case Ut.Left:return[t-LN(t-r,a),n];case Ut.Right:return[t+LN(r-t,a),n];case Ut.Top:return[t,n-LN(n-i,a)];case Ut.Bottom:return[t,n+LN(i-n,a)]}}function yDe({sourceX:e,sourceY:t,sourcePosition:n=Ut.Bottom,targetX:r,targetY:i,targetPosition:a=Ut.Top,curvature:s=.25}){const[o,u]=Ume({pos:n,x1:e,y1:t,x2:r,y2:i,c:s}),[c,d]=Ume({pos:a,x1:r,y1:i,x2:e,y2:t,c:s}),[f,p,m,y]=vDe({sourceX:e,sourceY:t,targetX:r,targetY:i,sourceControlX:o,sourceControlY:u,targetControlX:c,targetControlY:d});return[`M${e},${t} C${o},${u} ${c},${d} ${r},${i}`,f,p,m,y]}function xDe({sourceX:e,sourceY:t,targetX:n,targetY:r}){const i=Math.abs(n-e)/2,a=n<e?n+i:n-i,s=Math.abs(r-t)/2,o=r<t?r+s:r-s;return[a,o,i,s]}function MXt({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:i=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const s=i&&n?r+1e3:r,o=Math.max(e.parentId||i&&e.selected?e.internals.z:0,t.parentId||i&&t.selected?t.internals.z:0);return s+o}function DXt({sourceNode:e,targetNode:t,width:n,height:r,transform:i}){const a=$P(qj(e),qj(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const s={x:-i[0]/i[2],y:-i[1]/i[2],width:n/i[2],height:r/i[2]};return B2(s,MP(a))>0}const LXt=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,zXt=(e,t)=>t.some(n=>n.source===e.source&&n.target===e.target&&(n.sourceHandle===e.sourceHandle||!n.sourceHandle&&!e.sourceHandle)&&(n.targetHandle===e.targetHandle||!n.targetHandle&&!e.targetHandle)),UXt=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||LXt;let i;return oDe(e)?i={...e}:i={...e,id:r(e)},zXt(i,t)?t:(i.sourceHandle===null&&delete i.sourceHandle,i.targetHandle===null&&delete i.targetHandle,t.concat(i))};function bDe({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[i,a,s,o]=xDe({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,i,a,s,o]}const Fme={[Ut.Left]:{x:-1,y:0},[Ut.Right]:{x:1,y:0},[Ut.Top]:{x:0,y:-1},[Ut.Bottom]:{x:0,y:1}},FXt=({source:e,sourcePosition:t=Ut.Bottom,target:n})=>t===Ut.Left||t===Ut.Right?e.x<n.x?{x:1,y:0}:{x:-1,y:0}:e.y<n.y?{x:0,y:1}:{x:0,y:-1},Bme=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function BXt({source:e,sourcePosition:t=Ut.Bottom,target:n,targetPosition:r=Ut.Top,center:i,offset:a,stepPosition:s}){const o=Fme[t],u=Fme[r],c={x:e.x+o.x*a,y:e.y+o.y*a},d={x:n.x+u.x*a,y:n.y+u.y*a},f=FXt({source:c,sourcePosition:t,target:d}),p=f.x!==0?"x":"y",m=f[p];let y=[],v,x;const _={x:0,y:0},S={x:0,y:0},[,,w,T]=xDe({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(o[p]*u[p]===-1){p==="x"?(v=i.x??c.x+(d.x-c.x)*s,x=i.y??(c.y+d.y)/2):(v=i.x??(c.x+d.x)/2,x=i.y??c.y+(d.y-c.y)*s);const E=[{x:v,y:c.y},{x:v,y:d.y}],A=[{x:c.x,y:x},{x:d.x,y:x}];o[p]===m?y=p==="x"?E:A:y=p==="x"?A:E}else{const E=[{x:c.x,y:d.y}],A=[{x:d.x,y:c.y}];if(p==="x"?y=o.x===m?A:E:y=o.y===m?E:A,t===r){const R=Math.abs(e[p]-n[p]);if(R<=a){const U=Math.min(a-1,a-R);o[p]===m?_[p]=(c[p]>e[p]?-1:1)*U:S[p]=(d[p]>n[p]?-1:1)*U}}if(t!==r){const R=p==="x"?"y":"x",U=o[p]===u[R],z=c[R]>d[R],F=c[R]<d[R];(o[p]===1&&(!U&&z||U&&F)||o[p]!==1&&(!U&&F||U&&z))&&(y=p==="x"?E:A)}const I={x:c.x+_.x,y:c.y+_.y},M={x:d.x+S.x,y:d.y+S.y},$=Math.max(Math.abs(I.x-y[0].x),Math.abs(M.x-y[0].x)),O=Math.max(Math.abs(I.y-y[0].y),Math.abs(M.y-y[0].y));$>=O?(v=(I.x+M.x)/2,x=y[0].y):(v=y[0].x,x=(I.y+M.y)/2)}return[[e,{x:c.x+_.x,y:c.y+_.y},...y,{x:d.x+S.x,y:d.y+S.y},n],v,x,w,T]}function qXt(e,t,n,r){const i=Math.min(Bme(e,t)/2,Bme(t,n)/2,r),{x:a,y:s}=t;if(e.x===a&&a===n.x||e.y===s&&s===n.y)return`L${a} ${s}`;if(e.y===s){const c=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+i*c},${s}Q ${a},${s} ${a},${s+i*d}`}const o=e.x<n.x?1:-1,u=e.y<n.y?-1:1;return`L ${a},${s+i*u}Q ${a},${s} ${a+i*o},${s}`}function KB({sourceX:e,sourceY:t,sourcePosition:n=Ut.Bottom,targetX:r,targetY:i,targetPosition:a=Ut.Top,borderRadius:s=5,centerX:o,centerY:u,offset:c=20,stepPosition:d=.5}){const[f,p,m,y,v]=BXt({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:i},targetPosition:a,center:{x:o,y:u},offset:c,stepPosition:d});return[f.reduce((_,S,w)=>{let T="";return w>0&&w<f.length-1?T=qXt(f[w-1],S,f[w+1],s):T=`${w===0?"M":"L"}${S.x} ${S.y}`,_+=T,_},""),p,m,y,v]}function qme(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function HXt(e){const{sourceNode:t,targetNode:n}=e;if(!qme(t)||!qme(n))return null;const r=t.internals.handleBounds||Hme(t.handles),i=n.internals.handleBounds||Hme(n.handles),a=Vme(r?.source??[],e.sourceHandle),s=Vme(e.connectionMode===ex.Strict?i?.target??[]:(i?.target??[]).concat(i?.source??[]),e.targetHandle);if(!a||!s)return e.onError?.("008",Dc.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const o=a?.position||Ut.Bottom,u=s?.position||Ut.Top,c=hg(t,a,o),d=hg(n,s,u);return{sourceX:c.x,sourceY:c.y,targetX:d.x,targetY:d.y,sourcePosition:o,targetPosition:u}}function Hme(e){if(!e)return null;const t=[],n=[];for(const r of e)r.width=r.width??1,r.height=r.height??1,r.type==="source"?t.push(r):r.type==="target"&&n.push(r);return{source:t,target:n}}function hg(e,t,n=Ut.Left,r=!1){const i=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:s,height:o}=t??wf(e);if(r)return{x:i+s/2,y:a+o/2};switch(t?.position??n){case Ut.Top:return{x:i+s/2,y:a};case Ut.Right:return{x:i+s,y:a+o/2};case Ut.Bottom:return{x:i+s/2,y:a+o};case Ut.Left:return{x:i,y:a+o/2}}}function Vme(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function ZB(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function VXt(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:i}){const a=new Set;return e.reduce((s,o)=>([o.markerStart||r,o.markerEnd||i].forEach(u=>{if(u&&typeof u=="object"){const c=ZB(u,t);a.has(c)||(s.push({id:c,color:u.color||n,...u}),a.add(c))}}),s),[]).sort((s,o)=>s.id.localeCompare(o.id))}const _De=1e3,GXt=10,HZ={nodeOrigin:[0,0],nodeExtent:U2,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},WXt={...HZ,checkEquality:!0};function VZ(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function KXt(e,t,n){const r=VZ(HZ,n);for(const i of e.values())if(i.parentId)WZ(i,e,t,r);else{const a=bk(i,r.nodeOrigin),s=rx(i.extent)?i.extent:r.nodeExtent,o=pg(a,s,wf(i));i.internals.positionAbsolute=o}}function ZXt(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const i of e.handles){const a={id:i.id,width:i.width??1,height:i.height??1,nodeId:e.id,x:i.x,y:i.y,position:i.position,type:i.type};i.type==="source"?n.push(a):i.type==="target"&&r.push(a)}return{source:n,target:r}}function GZ(e){return e==="manual"}function YB(e,t,n,r={}){const i=VZ(WXt,r),a={i:0},s=new Map(t),o=i?.elevateNodesOnSelect&&!GZ(i.zIndexMode)?_De:0;let u=e.length>0;t.clear(),n.clear();for(const c of e){let d=s.get(c.id);if(i.checkEquality&&c===d?.internals.userNode)t.set(c.id,d);else{const f=bk(c,i.nodeOrigin),p=rx(c.extent)?c.extent:i.nodeExtent,m=pg(f,p,wf(c));d={...i.defaults,...c,measured:{width:c.measured?.width,height:c.measured?.height},internals:{positionAbsolute:m,handleBounds:ZXt(c,d),z:wDe(c,o,i.zIndexMode),userNode:c}},t.set(c.id,d)}(d.measured===void 0||d.measured.width===void 0||d.measured.height===void 0)&&!d.hidden&&(u=!1),c.parentId&&WZ(d,t,n,r,a)}return u}function YXt(e,t){if(!e.parentId)return;const n=t.get(e.parentId);n?n.set(e.id,e):t.set(e.parentId,new Map([[e.id,e]]))}function WZ(e,t,n,r,i){const{elevateNodesOnSelect:a,nodeOrigin:s,nodeExtent:o,zIndexMode:u}=VZ(HZ,r),c=e.parentId,d=t.get(c);if(!d){console.warn(`Parent node ${c} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}YXt(e,n),i&&!d.parentId&&d.internals.rootParentIndex===void 0&&u==="auto"&&(d.internals.rootParentIndex=++i.i,d.internals.z=d.internals.z+i.i*GXt),i&&d.internals.rootParentIndex!==void 0&&(i.i=d.internals.rootParentIndex);const f=a&&!GZ(u)?_De:0,{x:p,y:m,z:y}=XXt(e,d,s,o,f,u),{positionAbsolute:v}=e.internals,x=p!==v.x||m!==v.y;(x||y!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:x?{x:p,y:m}:v,z:y}})}function wDe(e,t,n){const r=_u(e.zIndex)?e.zIndex:0;return GZ(n)?r:r+(e.selected?t:0)}function XXt(e,t,n,r,i,a){const{x:s,y:o}=t.internals.positionAbsolute,u=wf(e),c=bk(e,n),d=rx(e.extent)?pg(c,e.extent,u):c;let f=pg({x:s+d.x,y:o+d.y},r,u);e.extent==="parent"&&(f=uDe(f,u,t));const p=wDe(e,i,a),m=t.internals.z??0;return{x:f.x,y:f.y,z:m>=p?m+1:p}}function KZ(e,t,n,r=[0,0]){const i=[],a=new Map;for(const s of e){const o=t.get(s.parentId);if(!o)continue;const u=a.get(s.parentId)?.expandedRect??nx(o),c=dDe(u,s.rect);a.set(s.parentId,{expandedRect:c,parent:o})}return a.size>0&&a.forEach(({expandedRect:s,parent:o},u)=>{const c=o.internals.positionAbsolute,d=wf(o),f=o.origin??r,p=s.x<c.x?Math.round(Math.abs(c.x-s.x)):0,m=s.y<c.y?Math.round(Math.abs(c.y-s.y)):0,y=Math.max(d.width,Math.round(s.width)),v=Math.max(d.height,Math.round(s.height)),x=(y-d.width)*f[0],_=(v-d.height)*f[1];(p>0||m>0||x||_)&&(i.push({id:u,type:"position",position:{x:o.position.x-p+x,y:o.position.y-m+_}}),n.get(u)?.forEach(S=>{e.some(w=>w.id===S.id)||i.push({id:S.id,type:"position",position:{x:S.position.x+p,y:S.position.y+m}})})),(d.width<s.width||d.height<s.height||p||m)&&i.push({id:u,type:"dimensions",setAttributes:!0,dimensions:{width:y+(p?f[0]*p-x:0),height:v+(m?f[1]*m-_:0)}})}),i}function JXt(e,t,n,r,i,a,s){const o=r?.querySelector(".xyflow__viewport");let u=!1;if(!o)return{changes:[],updatedInternals:u};const c=[],d=window.getComputedStyle(o),{m22:f}=new window.DOMMatrixReadOnly(d.transform),p=[];for(const m of e.values()){const y=t.get(m.id);if(!y)continue;if(y.hidden){t.set(y.id,{...y,internals:{...y.internals,handleBounds:void 0}}),u=!0;continue}const v=qZ(m.nodeElement),x=y.measured.width!==v.width||y.measured.height!==v.height;if(!!(v.width&&v.height&&(x||!y.internals.handleBounds||m.force))){const S=m.nodeElement.getBoundingClientRect(),w=rx(y.extent)?y.extent:a;let{positionAbsolute:T}=y.internals;y.parentId&&y.extent==="parent"?T=uDe(T,v,t.get(y.parentId)):w&&(T=pg(T,w,v));const N={...y,measured:v,internals:{...y.internals,positionAbsolute:T,handleBounds:{source:zme("source",m.nodeElement,S,f,y.id),target:zme("target",m.nodeElement,S,f,y.id)}}};t.set(y.id,N),y.parentId&&WZ(N,t,n,{nodeOrigin:i,zIndexMode:s}),u=!0,x&&(c.push({id:y.id,type:"dimensions",dimensions:v}),y.expandParent&&y.parentId&&p.push({id:y.id,parentId:y.parentId,rect:nx(N,i)}))}}if(p.length>0){const m=KZ(p,t,n,i);c.push(...m)}return{changes:c,updatedInternals:u}}async function QXt({delta:e,panZoom:t,transform:n,translateExtent:r,width:i,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const s=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[i,a]],r),o=!!s&&(s.x!==n[0]||s.y!==n[1]||s.k!==n[2]);return Promise.resolve(o)}function Gme(e,t,n,r,i,a){let s=i;const o=r.get(s)||new Map;r.set(s,o.set(n,t)),s=`${i}-${e}`;const u=r.get(s)||new Map;if(r.set(s,u.set(n,t)),a){s=`${i}-${e}-${a}`;const c=r.get(s)||new Map;r.set(s,c.set(n,t))}}function SDe(e,t,n){e.clear(),t.clear();for(const r of n){const{source:i,target:a,sourceHandle:s=null,targetHandle:o=null}=r,u={edgeId:r.id,source:i,target:a,sourceHandle:s,targetHandle:o},c=`${i}-${s}--${a}-${o}`,d=`${a}-${o}--${i}-${s}`;Gme("source",u,d,e,i,s),Gme("target",u,c,e,a,o),t.set(r.id,r)}}function kDe(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:kDe(n,t):!1}function Wme(e,t,n){let r=e;do{if(r?.matches?.(t))return!0;if(r===n)return!1;r=r?.parentElement}while(r);return!1}function eJt(e,t,n,r){const i=new Map;for(const[a,s]of e)if((s.selected||s.id===r)&&(!s.parentId||!kDe(s,e))&&(s.draggable||t&&typeof s.draggable>"u")){const o=e.get(a);o&&i.set(a,{id:a,position:o.position||{x:0,y:0},distance:{x:n.x-o.internals.positionAbsolute.x,y:n.y-o.internals.positionAbsolute.y},extent:o.extent,parentId:o.parentId,origin:o.origin,expandParent:o.expandParent,internals:{positionAbsolute:o.internals.positionAbsolute||{x:0,y:0}},measured:{width:o.measured.width??0,height:o.measured.height??0}})}return i}function E8({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const i=[];for(const[s,o]of t){const u=n.get(s)?.internals.userNode;u&&i.push({...u,position:o.position,dragging:r})}if(!e)return[i[0],i];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:i[0],i]}function tJt({dragItems:e,snapGrid:t,x:n,y:r}){const i=e.values().next().value;if(!i)return null;const a={x:n-i.distance.x,y:r-i.distance.y},s=wk(a,t);return{x:s.x-a.x,y:s.y-a.y}}function nJt({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:i}){let a={x:null,y:null},s=0,o=new Map,u=!1,c={x:0,y:0},d=null,f=!1,p=null,m=!1,y=!1,v=null;function x({noDragClassName:S,handleSelector:w,domNode:T,isSelectable:N,nodeId:E,nodeClickDistance:A=0}){p=Zo(T);function I({x:R,y:U}){const{nodeLookup:z,nodeExtent:F,snapGrid:D,snapToGrid:W,nodeOrigin:q,onNodeDrag:X,onSelectionDrag:L,onError:Y,updateNodePositions:G}=t();a={x:R,y:U};let P=!1;const V=o.size>1,K=V&&F?WB(_k(o)):null,Q=V&&W?tJt({dragItems:o,snapGrid:D,x:R,y:U}):null;for(const[oe,re]of o){if(!z.has(oe))continue;let ee={x:R-re.distance.x,y:U-re.distance.y};W&&(ee=Q?{x:Math.round(ee.x+Q.x),y:Math.round(ee.y+Q.y)}:wk(ee,D));let le=null;if(V&&F&&!re.extent&&K){const{positionAbsolute:ne}=re.internals,J=ne.x-K.x+F[0][0],se=ne.x+re.measured.width-K.x2+F[1][0],ie=ne.y-K.y+F[0][1],he=ne.y+re.measured.height-K.y2+F[1][1];le=[[J,ie],[se,he]]}const{position:te,positionAbsolute:Z}=lDe({nodeId:oe,nextPosition:ee,nodeLookup:z,nodeExtent:le||F,nodeOrigin:q,onError:Y});P=P||re.position.x!==te.x||re.position.y!==te.y,re.position=te,re.internals.positionAbsolute=Z}if(y=y||P,!!P&&(G(o,!0),v&&(r||X||!E&&L))){const[oe,re]=E8({nodeId:E,dragItems:o,nodeLookup:z});r?.(v,o,oe,re),X?.(v,oe,re),E||L?.(v,re)}}async function M(){if(!d)return;const{transform:R,panBy:U,autoPanSpeed:z,autoPanOnNodeDrag:F}=t();if(!F){u=!1,cancelAnimationFrame(s);return}const[D,W]=cDe(c,d,z);(D!==0||W!==0)&&(a.x=(a.x??0)-D/R[2],a.y=(a.y??0)-W/R[2],await U({x:D,y:W})&&I(a)),s=requestAnimationFrame(M)}function $(R){const{nodeLookup:U,multiSelectionActive:z,nodesDraggable:F,transform:D,snapGrid:W,snapToGrid:q,selectNodesOnDrag:X,onNodeDragStart:L,onSelectionDragStart:Y,unselectNodesAndEdges:G}=t();f=!0,(!X||!N)&&!z&&E&&(U.get(E)?.selected||G()),N&&X&&E&&e?.(E);const P=ow(R.sourceEvent,{transform:D,snapGrid:W,snapToGrid:q,containerBounds:d});if(a=P,o=eJt(U,F,P,E),o.size>0&&(n||L||!E&&Y)){const[V,K]=E8({nodeId:E,dragItems:o,nodeLookup:U});n?.(R.sourceEvent,o,V,K),L?.(R.sourceEvent,V,K),E||Y?.(R.sourceEvent,K)}}const O=W5e().clickDistance(A).on("start",R=>{const{domNode:U,nodeDragThreshold:z,transform:F,snapGrid:D,snapToGrid:W}=t();d=U?.getBoundingClientRect()||null,m=!1,y=!1,v=R.sourceEvent,z===0&&$(R),a=ow(R.sourceEvent,{transform:F,snapGrid:D,snapToGrid:W,containerBounds:d}),c=wu(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:U,transform:z,snapGrid:F,snapToGrid:D,nodeDragThreshold:W,nodeLookup:q}=t(),X=ow(R.sourceEvent,{transform:z,snapGrid:F,snapToGrid:D,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||E&&!q.has(E))&&(m=!0),!m){if(!u&&U&&f&&(u=!0,M()),!f){const L=wu(R.sourceEvent,d),Y=L.x-c.x,G=L.y-c.y;Math.sqrt(Y*Y+G*G)>W&&$(R)}(a.x!==X.xSnapped||a.y!==X.ySnapped)&&o&&f&&(c=wu(R.sourceEvent,d),I(X))}}).on("end",R=>{if(!(!f||m)&&(u=!1,f=!1,cancelAnimationFrame(s),o.size>0)){const{nodeLookup:U,updateNodePositions:z,onNodeDragStop:F,onSelectionDragStop:D}=t();if(y&&(z(o,!1),y=!1),i||F||!E&&D){const[W,q]=E8({nodeId:E,dragItems:o,nodeLookup:U,dragging:!1});i?.(R.sourceEvent,o,W,q),F?.(R.sourceEvent,W,q),E||D?.(R.sourceEvent,q)}}}).filter(R=>{const U=R.target;return!R.button&&(!S||!Wme(U,`.${S}`,T))&&(!w||Wme(U,w,T))});p.call(O)}function _(){p?.on(".drag",null)}return{update:x,destroy:_}}function rJt(e,t,n){const r=[],i={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())B2(i,nx(a))>0&&r.push(a);return r}const iJt=250;function aJt(e,t,n,r){let i=[],a=1/0;const s=rJt(e,n,t+iJt);for(const o of s){const u=[...o.internals.handleBounds?.source??[],...o.internals.handleBounds?.target??[]];for(const c of u){if(r.nodeId===c.nodeId&&r.type===c.type&&r.id===c.id)continue;const{x:d,y:f}=hg(o,c,c.position,!0),p=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));p>t||(p<a?(i=[{...c,x:d,y:f}],a=p):p===a&&i.push({...c,x:d,y:f}))}}if(!i.length)return null;if(i.length>1){const o=r.type==="source"?"target":"source";return i.find(u=>u.type===o)??i[0]}return i[0]}function EDe(e,t,n,r,i,a=!1){const s=r.get(e);if(!s)return null;const o=i==="strict"?s.internals.handleBounds?.[t]:[...s.internals.handleBounds?.source??[],...s.internals.handleBounds?.target??[]],u=(n?o?.find(c=>c.id===n):o?.[0])??null;return u&&a?{...u,...hg(s,u,u.position,!0)}:u}function TDe(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function sJt(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const NDe=()=>!0;function oJt(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:i,edgeUpdaterType:a,isTarget:s,domNode:o,nodeLookup:u,lib:c,autoPanOnConnect:d,flowId:f,panBy:p,cancelConnection:m,onConnectStart:y,onConnect:v,onConnectEnd:x,isValidConnection:_=NDe,onReconnectEnd:S,updateConnection:w,getTransform:T,getFromHandle:N,autoPanSpeed:E,dragThreshold:A=1,handleDomNode:I}){const M=hDe(e.target);let $=0,O;const{x:R,y:U}=wu(e),z=TDe(a,I),F=o?.getBoundingClientRect();let D=!1;if(!F||!z)return;const W=EDe(i,z,r,u,t);if(!W)return;let q=wu(e,F),X=!1,L=null,Y=!1,G=null;function P(){if(!d||!F)return;const[te,Z]=cDe(q,F,E);p({x:te,y:Z}),$=requestAnimationFrame(P)}const V={...W,nodeId:i,type:z,position:W.position},K=u.get(i);let oe={inProgress:!0,isValid:null,from:hg(K,V,Ut.Left,!0),fromHandle:V,fromPosition:V.position,fromNode:K,to:q,toHandle:null,toPosition:$me[V.position],toNode:null,pointer:q};function re(){D=!0,w(oe),y?.(e,{nodeId:i,handleId:r,handleType:z})}A===0&&re();function ee(te){if(!D){const{x:he,y:ye}=wu(te),Ne=he-R,ce=ye-U;if(!(Ne*Ne+ce*ce>A*A))return;re()}if(!N()||!V){le(te);return}const Z=T();q=wu(te,F),O=aJt(Sk(q,Z,!1,[1,1]),n,u,V),X||(P(),X=!0);const ne=CDe(te,{handle:O,connectionMode:t,fromNodeId:i,fromHandleId:r,fromType:s?"target":"source",isValidConnection:_,doc:M,lib:c,flowId:f,nodeLookup:u});G=ne.handleDomNode,L=ne.connection,Y=sJt(!!O,ne.isValid);const J=u.get(i),se=J?hg(J,V,Ut.Left,!0):oe.from,ie={...oe,from:se,isValid:Y,to:ne.toHandle&&Y?Hj({x:ne.toHandle.x,y:ne.toHandle.y},Z):q,toHandle:ne.toHandle,toPosition:Y&&ne.toHandle?ne.toHandle.position:$me[V.position],toNode:ne.toHandle?u.get(ne.toHandle.nodeId):null,pointer:q};w(ie),oe=ie}function le(te){if(!("touches"in te&&te.touches.length>0)){if(D){(O||G)&&L&&Y&&v?.(L);const{inProgress:Z,...ne}=oe,J={...ne,toPosition:oe.toHandle?oe.toPosition:null};x?.(te,J),a&&S?.(te,J)}m(),cancelAnimationFrame($),X=!1,Y=!1,L=null,G=null,M.removeEventListener("mousemove",ee),M.removeEventListener("mouseup",le),M.removeEventListener("touchmove",ee),M.removeEventListener("touchend",le)}}M.addEventListener("mousemove",ee),M.addEventListener("mouseup",le),M.addEventListener("touchmove",ee),M.addEventListener("touchend",le)}function CDe(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:i,fromType:a,doc:s,lib:o,flowId:u,isValidConnection:c=NDe,nodeLookup:d}){const f=a==="target",p=t?s.querySelector(`.${o}-flow__handle[data-id="${u}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:m,y}=wu(e),v=s.elementFromPoint(m,y),x=v?.classList.contains(`${o}-flow__handle`)?v:p,_={handleDomNode:x,isValid:!1,connection:null,toHandle:null};if(x){const S=TDe(void 0,x),w=x.getAttribute("data-nodeid"),T=x.getAttribute("data-handleid"),N=x.classList.contains("connectable"),E=x.classList.contains("connectableend");if(!w||!S)return _;const A={source:f?w:r,sourceHandle:f?T:i,target:f?r:w,targetHandle:f?i:T};_.connection=A;const M=N&&E&&(n===ex.Strict?f&&S==="source"||!f&&S==="target":w!==r||T!==i);_.isValid=M&&c(A),_.toHandle=EDe(w,S,T,d,n,!0)}return _}const XB={onPointerDown:oJt,isValid:CDe};function lJt({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const i=Zo(e);function a({translateExtent:o,width:u,height:c,zoomStep:d=1,pannable:f=!0,zoomable:p=!0,inversePan:m=!1}){const y=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const T=n(),N=w.sourceEvent.ctrlKey&&q2()?10:1,E=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,A=T[2]*Math.pow(2,E*N);t.scaleTo(A)};let v=[0,0];const x=w=>{(w.sourceEvent.type==="mousedown"||w.sourceEvent.type==="touchstart")&&(v=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY])},_=w=>{const T=n();if(w.sourceEvent.type!=="mousemove"&&w.sourceEvent.type!=="touchmove"||!t)return;const N=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],E=[N[0]-v[0],N[1]-v[1]];v=N;const A=r()*Math.max(T[2],Math.log(T[2]))*(m?-1:1),I={x:T[0]-E[0]*A,y:T[1]-E[1]*A},M=[[0,0],[u,c]];t.setViewportConstrained({x:I.x,y:I.y,zoom:T[2]},M,o)},S=nDe().on("start",x).on("zoom",f?_:null).on("zoom.wheel",p?y:null);i.call(S,{})}function s(){i.on("zoom",null)}return{update:a,destroy:s,pointer:uu}}const DP=e=>({x:e.x,y:e.y,zoom:e.k}),T8=({x:e,y:t,zoom:n})=>PP.translate(e,t).scale(n),Cv=(e,t)=>e.target.closest(`.${t}`),ADe=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),uJt=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,N8=(e,t=0,n=uJt,r=()=>{})=>{const i=typeof t=="number"&&t>0;return i||r(),i?e.transition().duration(t).ease(n).on("end",r):e},IDe=e=>{const t=e.ctrlKey&&q2()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function cJt({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:i,panOnScrollSpeed:a,zoomOnPinch:s,onPanZoomStart:o,onPanZoom:u,onPanZoomEnd:c}){return d=>{if(Cv(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&s){const x=uu(d),_=IDe(d),S=f*Math.pow(2,_);r.scaleTo(n,S,x,d);return}const p=d.deltaMode===1?20:1;let m=i===Cm.Vertical?0:d.deltaX*p,y=i===Cm.Horizontal?0:d.deltaY*p;!q2()&&d.shiftKey&&i!==Cm.Vertical&&(m=d.deltaY*p,y=0),r.translateBy(n,-(m/f)*a,-(y/f)*a,{internal:!0});const v=DP(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(u?.(d,v),e.panScrollTimeout=setTimeout(()=>{c?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,o?.(d,v))}}function dJt({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,i){const a=r.type==="wheel",s=!t&&a&&!r.ctrlKey,o=Cv(r,e);if(r.ctrlKey&&a&&o&&r.preventDefault(),s||o)return null;r.preventDefault(),n.call(this,r,i)}}function fJt({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const i=DP(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=i,r.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(r.sourceEvent,i)}}function pJt({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:i}){return a=>{e.usedRightMouseButton=!!(n&&ADe(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),i&&!a.sourceEvent?.internal&&i?.(a.sourceEvent,DP(a.transform))}}function hJt({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:i,onPaneContextMenu:a}){return s=>{if(!s.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&ADe(t,e.mouseButton??0)&&!e.usedRightMouseButton&&s.sourceEvent&&a(s.sourceEvent),e.usedRightMouseButton=!1,r(!1),i)){const o=DP(s.transform);e.prevViewport=o,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{i?.(s.sourceEvent,o)},n?150:0)}}}function mJt({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:i,zoomOnDoubleClick:a,userSelectionActive:s,noWheelClassName:o,noPanClassName:u,lib:c,connectionInProgress:d}){return f=>{const p=e||t,m=n&&f.ctrlKey,y=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(Cv(f,`${c}-flow__node`)||Cv(f,`${c}-flow__edge`)))return!0;if(!r&&!p&&!i&&!a&&!n||s||d&&!y||Cv(f,o)&&y||Cv(f,u)&&(!y||i&&y&&!e)||!n&&f.ctrlKey&&y)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!p&&!i&&!m&&y||!r&&(f.type==="mousedown"||f.type==="touchstart")||Array.isArray(r)&&!r.includes(f.button)&&f.type==="mousedown")return!1;const v=Array.isArray(r)&&r.includes(f.button)||!f.button||f.button<=1;return(!f.ctrlKey||y)&&v}}function gJt({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:i,onPanZoom:a,onPanZoomStart:s,onPanZoomEnd:o,onDraggingChange:u}){const c={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=nDe().scaleExtent([t,n]).translateExtent(r),p=Zo(e).call(f);S({x:i.x,y:i.y,zoom:tx(i.zoom,t,n)},[[0,0],[d.width,d.height]],r);const m=p.on("wheel.zoom"),y=p.on("dblclick.zoom");f.wheelDelta(IDe);function v(O,R){return p?new Promise(U=>{f?.interpolate(R?.interpolate==="linear"?Kd:TC).transform(N8(p,R?.duration,R?.ease,()=>U(!0)),O)}):Promise.resolve(!1)}function x({noWheelClassName:O,noPanClassName:R,onPaneContextMenu:U,userSelectionActive:z,panOnScroll:F,panOnDrag:D,panOnScrollMode:W,panOnScrollSpeed:q,preventScrolling:X,zoomOnPinch:L,zoomOnScroll:Y,zoomOnDoubleClick:G,zoomActivationKeyPressed:P,lib:V,onTransformChange:K,connectionInProgress:Q,paneClickDistance:oe,selectionOnDrag:re}){z&&!c.isZoomingOrPanning&&_();const ee=F&&!P&&!z;f.clickDistance(re?1/0:!_u(oe)||oe<0?0:oe);const le=ee?cJt({zoomPanValues:c,noWheelClassName:O,d3Selection:p,d3Zoom:f,panOnScrollMode:W,panOnScrollSpeed:q,zoomOnPinch:L,onPanZoomStart:s,onPanZoom:a,onPanZoomEnd:o}):dJt({noWheelClassName:O,preventScrolling:X,d3ZoomHandler:m});if(p.on("wheel.zoom",le,{passive:!1}),!z){const Z=fJt({zoomPanValues:c,onDraggingChange:u,onPanZoomStart:s});f.on("start",Z);const ne=pJt({zoomPanValues:c,panOnDrag:D,onPaneContextMenu:!!U,onPanZoom:a,onTransformChange:K});f.on("zoom",ne);const J=hJt({zoomPanValues:c,panOnDrag:D,panOnScroll:F,onPaneContextMenu:U,onPanZoomEnd:o,onDraggingChange:u});f.on("end",J)}const te=mJt({zoomActivationKeyPressed:P,panOnDrag:D,zoomOnScroll:Y,panOnScroll:F,zoomOnDoubleClick:G,zoomOnPinch:L,userSelectionActive:z,noPanClassName:R,noWheelClassName:O,lib:V,connectionInProgress:Q});f.filter(te),G?p.on("dblclick.zoom",y):p.on("dblclick.zoom",null)}function _(){f.on("zoom",null)}async function S(O,R,U){const z=T8(O),F=f?.constrain()(z,R,U);return F&&await v(F),new Promise(D=>D(F))}async function w(O,R){const U=T8(O);return await v(U,R),new Promise(z=>z(U))}function T(O){if(p){const R=T8(O),U=p.property("__zoom");(U.k!==O.zoom||U.x!==O.x||U.y!==O.y)&&f?.transform(p,R,null,{sync:!0})}}function N(){const O=p?tDe(p.node()):{x:0,y:0,k:1};return{x:O.x,y:O.y,zoom:O.k}}function E(O,R){return p?new Promise(U=>{f?.interpolate(R?.interpolate==="linear"?Kd:TC).scaleTo(N8(p,R?.duration,R?.ease,()=>U(!0)),O)}):Promise.resolve(!1)}function A(O,R){return p?new Promise(U=>{f?.interpolate(R?.interpolate==="linear"?Kd:TC).scaleBy(N8(p,R?.duration,R?.ease,()=>U(!0)),O)}):Promise.resolve(!1)}function I(O){f?.scaleExtent(O)}function M(O){f?.translateExtent(O)}function $(O){const R=!_u(O)||O<0?0:O;f?.clickDistance(R)}return{update:x,destroy:_,setViewport:w,setViewportConstrained:S,getViewport:N,scaleTo:E,scaleBy:A,setScaleExtent:I,setTranslateExtent:M,syncViewport:T,setClickDistance:$}}var ix;(function(e){e.Line="line",e.Handle="handle"})(ix||(ix={}));function vJt({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:i,affectsY:a}){const s=e-t,o=n-r,u=[s>0?1:s<0?-1:0,o>0?1:o<0?-1:0];return s&&i&&(u[0]=u[0]*-1),o&&a&&(u[1]=u[1]*-1),u}function Kme(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),i=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:i}}function Jf(e,t){return Math.max(0,t-e)}function Qf(e,t){return Math.max(0,e-t)}function zN(e,t,n){return Math.max(0,t-e,e-n)}function Zme(e,t){return e?!t:t}function yJt(e,t,n,r,i,a,s,o){let{affectsX:u,affectsY:c}=t;const{isHorizontal:d,isVertical:f}=t,p=d&&f,{xSnapped:m,ySnapped:y}=n,{minWidth:v,maxWidth:x,minHeight:_,maxHeight:S}=r,{x:w,y:T,width:N,height:E,aspectRatio:A}=e;let I=Math.floor(d?m-e.pointerX:0),M=Math.floor(f?y-e.pointerY:0);const $=N+(u?-I:I),O=E+(c?-M:M),R=-a[0]*N,U=-a[1]*E;let z=zN($,v,x),F=zN(O,_,S);if(s){let q=0,X=0;u&&I<0?q=Jf(w+I+R,s[0][0]):!u&&I>0&&(q=Qf(w+$+R,s[1][0])),c&&M<0?X=Jf(T+M+U,s[0][1]):!c&&M>0&&(X=Qf(T+O+U,s[1][1])),z=Math.max(z,q),F=Math.max(F,X)}if(o){let q=0,X=0;u&&I>0?q=Qf(w+I,o[0][0]):!u&&I<0&&(q=Jf(w+$,o[1][0])),c&&M>0?X=Qf(T+M,o[0][1]):!c&&M<0&&(X=Jf(T+O,o[1][1])),z=Math.max(z,q),F=Math.max(F,X)}if(i){if(d){const q=zN($/A,_,S)*A;if(z=Math.max(z,q),s){let X=0;!u&&!c||u&&!c&&p?X=Qf(T+U+$/A,s[1][1])*A:X=Jf(T+U+(u?I:-I)/A,s[0][1])*A,z=Math.max(z,X)}if(o){let X=0;!u&&!c||u&&!c&&p?X=Jf(T+$/A,o[1][1])*A:X=Qf(T+(u?I:-I)/A,o[0][1])*A,z=Math.max(z,X)}}if(f){const q=zN(O*A,v,x)/A;if(F=Math.max(F,q),s){let X=0;!u&&!c||c&&!u&&p?X=Qf(w+O*A+R,s[1][0])/A:X=Jf(w+(c?M:-M)*A+R,s[0][0])/A,F=Math.max(F,X)}if(o){let X=0;!u&&!c||c&&!u&&p?X=Jf(w+O*A,o[1][0])/A:X=Qf(w+(c?M:-M)*A,o[0][0])/A,F=Math.max(F,X)}}}M=M+(M<0?F:-F),I=I+(I<0?z:-z),i&&(p?$>O*A?M=(Zme(u,c)?-I:I)/A:I=(Zme(u,c)?-M:M)*A:d?(M=I/A,c=u):(I=M*A,u=c));const D=u?w+I:w,W=c?T+M:T;return{width:N+(u?-I:I),height:E+(c?-M:M),x:a[0]*I*(u?-1:1)+D,y:a[1]*M*(c?-1:1)+W}}const jDe={width:0,height:0,x:0,y:0},xJt={...jDe,pointerX:0,pointerY:0,aspectRatio:1};function bJt(e){return[[0,0],[e.measured.width,e.measured.height]]}function _Jt(e,t,n){const r=t.position.x+e.position.x,i=t.position.y+e.position.y,a=e.measured.width??0,s=e.measured.height??0,o=n[0]*a,u=n[1]*s;return[[r-o,i-u],[r+a-o,i+s-u]]}function wJt({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:i}){const a=Zo(e);let s={controlDirection:Kme("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function o({controlPosition:c,boundaries:d,keepAspectRatio:f,resizeDirection:p,onResizeStart:m,onResize:y,onResizeEnd:v,shouldResize:x}){let _={...jDe},S={...xJt};s={boundaries:d,resizeDirection:p,keepAspectRatio:f,controlDirection:Kme(c)};let w,T=null,N=[],E,A,I,M=!1;const $=W5e().on("start",O=>{const{nodeLookup:R,transform:U,snapGrid:z,snapToGrid:F,nodeOrigin:D,paneDomNode:W}=n();if(w=R.get(t),!w)return;T=W?.getBoundingClientRect()??null;const{xSnapped:q,ySnapped:X}=ow(O.sourceEvent,{transform:U,snapGrid:z,snapToGrid:F,containerBounds:T});_={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},S={..._,pointerX:q,pointerY:X,aspectRatio:_.width/_.height},E=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(E=R.get(w.parentId),A=E&&w.extent==="parent"?bJt(E):void 0),N=[],I=void 0;for(const[L,Y]of R)if(Y.parentId===t&&(N.push({id:L,position:{...Y.position},extent:Y.extent}),Y.extent==="parent"||Y.expandParent)){const G=_Jt(Y,w,Y.origin??D);I?I=[[Math.min(G[0][0],I[0][0]),Math.min(G[0][1],I[0][1])],[Math.max(G[1][0],I[1][0]),Math.max(G[1][1],I[1][1])]]:I=G}m?.(O,{..._})}).on("drag",O=>{const{transform:R,snapGrid:U,snapToGrid:z,nodeOrigin:F}=n(),D=ow(O.sourceEvent,{transform:R,snapGrid:U,snapToGrid:z,containerBounds:T}),W=[];if(!w)return;const{x:q,y:X,width:L,height:Y}=_,G={},P=w.origin??F,{width:V,height:K,x:Q,y:oe}=yJt(S,s.controlDirection,D,s.boundaries,s.keepAspectRatio,P,A,I),re=V!==L,ee=K!==Y,le=Q!==q&&re,te=oe!==X&ⅇif(!le&&!te&&!re&&!ee)return;if((le||te||P[0]===1||P[1]===1)&&(G.x=le?Q:_.x,G.y=te?oe:_.y,_.x=G.x,_.y=G.y,N.length>0)){const se=Q-q,ie=oe-X;for(const he of N)he.position={x:he.position.x-se+P[0]*(V-L),y:he.position.y-ie+P[1]*(K-Y)},W.push(he)}if((re||ee)&&(G.width=re&&(!s.resizeDirection||s.resizeDirection==="horizontal")?V:_.width,G.height=ee&&(!s.resizeDirection||s.resizeDirection==="vertical")?K:_.height,_.width=G.width,_.height=G.height),E&&w.expandParent){const se=P[0]*(G.width??0);G.x&&G.x<se&&(_.x=se,S.x=S.x-(G.x-se));const ie=P[1]*(G.height??0);G.y&&G.y<ie&&(_.y=ie,S.y=S.y-(G.y-ie))}const Z=vJt({width:_.width,prevWidth:L,height:_.height,prevHeight:Y,affectsX:s.controlDirection.affectsX,affectsY:s.controlDirection.affectsY}),ne={..._,direction:Z};x?.(O,ne)!==!1&&(M=!0,y?.(O,ne),r(G,W))}).on("end",O=>{M&&(v?.(O,{..._}),i?.({..._}),M=!1)});a.call($)}function u(){a.on(".drag",null)}return{update:o,destroy:u}}var C8={exports:{}},A8={};var Yme;function SJt(){if(Yme)return A8;Yme=1;var e=X2(),t=Uye();function n(c,d){return c===d&&(c!==0||1/c===1/d)||c!==c&&d!==d}var r=typeof Object.is=="function"?Object.is:n,i=t.useSyncExternalStore,a=e.useRef,s=e.useEffect,o=e.useMemo,u=e.useDebugValue;return A8.useSyncExternalStoreWithSelector=function(c,d,f,p,m){var y=a(null);if(y.current===null){var v={hasValue:!1,value:null};y.current=v}else v=y.current;y=o(function(){function _(E){if(!S){if(S=!0,w=E,E=p(E),m!==void 0&&v.hasValue){var A=v.value;if(m(A,E))return T=A}return T=E}if(A=T,r(w,E))return A;var I=p(E);return m!==void 0&&m(A,I)?(w=E,A):(w=E,T=I)}var S=!1,w,T,N=f===void 0?null:f;return[function(){return _(d())},N===null?void 0:function(){return _(N())}]},[d,f,p,m]);var x=i(c,y[0],y[1]);return s(function(){v.hasValue=!0,v.value=x},[x]),u(x),x},A8}var Xme;function kJt(){return Xme||(Xme=1,C8.exports=SJt()),C8.exports}var EJt=kJt();const TJt=Jn(EJt),NJt={},Jme=e=>{let t;const n=new Set,r=(d,f)=>{const p=typeof d=="function"?d(t):d;if(!Object.is(p,t)){const m=t;t=f??(typeof p!="object"||p===null)?p:Object.assign({},t,p),n.forEach(y=>y(t,m))}},i=()=>t,u={setState:r,getState:i,getInitialState:()=>c,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(NJt?"production":void 0)!=="production"&&console.warn("[DEPRECATED] The `destroy` method will be unsupported in a future version. Instead use unsubscribe function returned by subscribe. Everything will be garbage-collected if store is garbage-collected."),n.clear()}},c=t=e(r,i,u);return u},CJt=e=>e?Jme(e):Jme,{useDebugValue:AJt}=de,{useSyncExternalStoreWithSelector:IJt}=TJt,jJt=e=>e;function ODe(e,t=jJt,n){const r=IJt(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return AJt(r),r}const Qme=(e,t)=>{const n=CJt(e),r=(i,a=t)=>ODe(n,i,a);return Object.assign(r,n),r},OJt=(e,t)=>e?Qme(e,t):Qme;function Ei(e,t){if(Object.is(e,t))return!0;if(typeof e!="object"||e===null||typeof t!="object"||t===null)return!1;if(e instanceof Map&&t instanceof Map){if(e.size!==t.size)return!1;for(const[r,i]of e)if(!Object.is(i,t.get(r)))return!1;return!0}if(e instanceof Set&&t instanceof Set){if(e.size!==t.size)return!1;for(const r of e)if(!t.has(r))return!1;return!0}const n=Object.keys(e);if(n.length!==Object.keys(t).length)return!1;for(const r of n)if(!Object.prototype.hasOwnProperty.call(t,r)||!Object.is(e[r],t[r]))return!1;return!0}const LP=b.createContext(null),RJt=LP.Provider,RDe=Dc.error001();function rr(e,t){const n=b.useContext(LP);if(n===null)throw new Error(RDe);return ODe(n,e,t)}function Ci(){const e=b.useContext(LP);if(e===null)throw new Error(RDe);return b.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const ege={display:"none"},PJt={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},PDe="react-flow__node-desc",$De="react-flow__edge-desc",$Jt="react-flow__aria-live",MJt=e=>e.ariaLiveMessage,DJt=e=>e.ariaLabelConfig;function LJt({rfId:e}){const t=rr(MJt);return l.jsx("div",{id:`${$Jt}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:PJt,children:t})}function zJt({rfId:e,disableKeyboardA11y:t}){const n=rr(DJt);return l.jsxs(l.Fragment,{children:[l.jsx("div",{id:`${PDe}-${e}`,style:ege,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),l.jsx("div",{id:`${$De}-${e}`,style:ege,children:n["edge.a11yDescription.default"]}),!t&&l.jsx(LJt,{rfId:e})]})}const zP=b.forwardRef(({position:e="top-left",children:t,className:n,style:r,...i},a)=>{const s=`${e}`.split("-");return l.jsx("div",{className:ha(["react-flow__panel",n,...s]),style:r,ref:a,...i,children:t})});zP.displayName="Panel";function UJt({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:l.jsx(zP,{position:t,className:"react-flow__attribution","data-message":"Please only hide this attribution when you are subscribed to React Flow Pro: https://pro.reactflow.dev",children:l.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const FJt=e=>{const t=[],n=[];for(const[,r]of e.nodeLookup)r.selected&&t.push(r.internals.userNode);for(const[,r]of e.edgeLookup)r.selected&&n.push(r);return{selectedNodes:t,selectedEdges:n}},UN=e=>e.id;function BJt(e,t){return Ei(e.selectedNodes.map(UN),t.selectedNodes.map(UN))&&Ei(e.selectedEdges.map(UN),t.selectedEdges.map(UN))}function qJt({onSelectionChange:e}){const t=Ci(),{selectedNodes:n,selectedEdges:r}=rr(FJt,BJt);return b.useEffect(()=>{const i={nodes:n,edges:r};e?.(i),t.getState().onSelectionChangeHandlers.forEach(a=>a(i))},[n,r,e]),null}const HJt=e=>!!e.onSelectionChangeHandlers;function VJt({onSelectionChange:e}){const t=rr(HJt);return e||t?l.jsx(qJt,{onSelectionChange:e}):null}const MDe=[0,0],GJt={x:0,y:0,zoom:1},WJt=["nodes","edges","defaultNodes","defaultEdges","onConnect","onConnectStart","onConnectEnd","onClickConnectStart","onClickConnectEnd","nodesDraggable","autoPanOnNodeFocus","nodesConnectable","nodesFocusable","edgesFocusable","edgesReconnectable","elevateNodesOnSelect","elevateEdgesOnSelect","minZoom","maxZoom","nodeExtent","onNodesChange","onEdgesChange","elementsSelectable","connectionMode","snapGrid","snapToGrid","translateExtent","connectOnClick","defaultEdgeOptions","fitView","fitViewOptions","onNodesDelete","onEdgesDelete","onDelete","onNodeDrag","onNodeDragStart","onNodeDragStop","onSelectionDrag","onSelectionDragStart","onSelectionDragStop","onMoveStart","onMove","onMoveEnd","noPanClassName","nodeOrigin","autoPanOnConnect","autoPanOnNodeDrag","onError","connectionRadius","isValidConnection","selectNodesOnDrag","nodeDragThreshold","connectionDragThreshold","onBeforeDelete","debug","autoPanSpeed","ariaLabelConfig","zIndexMode"],tge=[...WJt,"rfId"],KJt=e=>({setNodes:e.setNodes,setEdges:e.setEdges,setMinZoom:e.setMinZoom,setMaxZoom:e.setMaxZoom,setTranslateExtent:e.setTranslateExtent,setNodeExtent:e.setNodeExtent,reset:e.reset,setDefaultNodesAndEdges:e.setDefaultNodesAndEdges}),nge={translateExtent:U2,nodeOrigin:MDe,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function ZJt(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:i,setTranslateExtent:a,setNodeExtent:s,reset:o,setDefaultNodesAndEdges:u}=rr(KJt,Ei),c=Ci();b.useEffect(()=>(u(e.defaultNodes,e.defaultEdges),()=>{d.current=nge,o()}),[]);const d=b.useRef(nge);return b.useEffect(()=>{for(const f of tge){const p=e[f],m=d.current[f];p!==m&&(typeof e[f]>"u"||(f==="nodes"?t(p):f==="edges"?n(p):f==="minZoom"?r(p):f==="maxZoom"?i(p):f==="translateExtent"?a(p):f==="nodeExtent"?s(p):f==="ariaLabelConfig"?c.setState({ariaLabelConfig:PXt(p)}):f==="fitView"?c.setState({fitViewQueued:p}):f==="fitViewOptions"?c.setState({fitViewOptions:p}):c.setState({[f]:p})))}d.current=e},tge.map(f=>e[f])),null}function rge(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function YJt(e){const[t,n]=b.useState(e==="system"?null:e);return b.useEffect(()=>{if(e!=="system"){n(e);return}const r=rge(),i=()=>n(r?.matches?"dark":"light");return i(),r?.addEventListener("change",i),()=>{r?.removeEventListener("change",i)}},[e]),t!==null?t:rge()?.matches?"dark":"light"}const ige=typeof document<"u"?document:null;function H2(e=null,t={target:ige,actInsideInputWithModifier:!0}){const[n,r]=b.useState(!1),i=b.useRef(!1),a=b.useRef(new Set([])),[s,o]=b.useMemo(()=>{if(e!==null){const c=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
|
|
1842
1842
|
`).replace(`
|
|
1843
1843
|
|
|
@@ -1939,5 +1939,5 @@ Error:`,i)}}function Asn(){return csn(e=>{eb("cls",{metric:e}),RLe=e},{reportAll
|
|
|
1939
1939
|
now you can use replayer.getMirror() to access the mirror instance of a replayer,\r
|
|
1940
1940
|
or you can use record.mirror to access the mirror instance during recording.`;let O0e={map:{},getId(){return console.error(dv),-1},getNode(){return console.error(dv),null},removeNodeFromMap(){console.error(dv)},has(){return console.error(dv),!1},reset(){console.error(dv)}};typeof window<"u"&&window.Proxy&&window.Reflect&&(O0e=new Proxy(O0e,{get(e,t,n){return t==="map"&&console.error(dv),Reflect.get(e,t,n)}}));function Z2(e,t,n={}){let r=null,i=0;return function(...a){const s=Date.now();!i&&n.leading===!1&&(i=s);const o=t-(s-i),u=this;o<=0||o>t?(r&&(sun(r),r=null),i=s,e.apply(u,a)):!r&&n.trailing!==!1&&(r=t4(()=>{i=n.leading===!1?0:Date.now(),r=null,e.apply(u,a)},o))}}function ize(e,t,n,r,i=window){const a=i.Object.getOwnPropertyDescriptor(e,t);return i.Object.defineProperty(e,t,r?n:{set(s){t4(()=>{n.set.call(this,s)},0),a&&a.set&&a.set.call(this,s)}}),()=>ize(e,t,a||{},!0)}function xY(e,t,n){try{if(!(t in e))return()=>{};const r=e[t],i=n(r);return typeof i=="function"&&(i.prototype=i.prototype||{},Object.defineProperties(i,{__rrweb_original__:{enumerable:!1,value:r}})),e[t]=i,()=>{e[t]=r}}catch{return()=>{}}}let aO=Date.now;/[1-9][0-9]{12}/.test(Date.now().toString())||(aO=()=>new Date().getTime());function aze(e){const t=e.document;return{left:t.scrollingElement?t.scrollingElement.scrollLeft:e.pageXOffset!==void 0?e.pageXOffset:pp([t,"optionalAccess",n=>n.documentElement,"access",n=>n.scrollLeft])||pp([t,"optionalAccess",n=>n.body,"optionalAccess",n=>n.parentElement,"optionalAccess",n=>n.scrollLeft])||pp([t,"optionalAccess",n=>n.body,"optionalAccess",n=>n.scrollLeft])||0,top:t.scrollingElement?t.scrollingElement.scrollTop:e.pageYOffset!==void 0?e.pageYOffset:pp([t,"optionalAccess",n=>n.documentElement,"access",n=>n.scrollTop])||pp([t,"optionalAccess",n=>n.body,"optionalAccess",n=>n.parentElement,"optionalAccess",n=>n.scrollTop])||pp([t,"optionalAccess",n=>n.body,"optionalAccess",n=>n.scrollTop])||0}}function sze(){return window.innerHeight||document.documentElement&&document.documentElement.clientHeight||document.body&&document.body.clientHeight}function oze(){return window.innerWidth||document.documentElement&&document.documentElement.clientWidth||document.body&&document.body.clientWidth}function lze(e){return e?e.nodeType===e.ELEMENT_NODE?e:e.parentElement:null}function Vo(e,t,n,r,i){if(!e)return!1;const a=lze(e);if(!a)return!1;const s=Ov(t,n);if(!i){const c=r&&a.matches(r);return s(a)&&!c}const o=xm(a,s);let u=-1;return o<0?!1:(r&&(u=xm(a,Ov(null,r))),o>-1&&u<0?!0:o<u)}function eun(e,t){return t.getId(e)!==-1}function H8(e,t){return t.getId(e)===K2}function uze(e,t){if(dw(e))return!1;const n=t.getId(e);return t.has(n)?e.parentNode&&e.parentNode.nodeType===e.DOCUMENT_NODE?!1:e.parentNode?uze(e.parentNode,t):!0:!0}function T9(e){return!!e.changedTouches}function tun(e=window){"NodeList"in e&&!e.NodeList.prototype.forEach&&(e.NodeList.prototype.forEach=Array.prototype.forEach),"DOMTokenList"in e&&!e.DOMTokenList.prototype.forEach&&(e.DOMTokenList.prototype.forEach=Array.prototype.forEach),Node.prototype.contains||(Node.prototype.contains=(...t)=>{let n=t[0];if(!(0 in t))throw new TypeError("1 argument is required");do if(this===n)return!0;while(n=n&&n.parentNode);return!1})}function cze(e,t){return!!(e.nodeName==="IFRAME"&&t.getMeta(e))}function dze(e,t){return!!(e.nodeName==="LINK"&&e.nodeType===e.ELEMENT_NODE&&e.getAttribute&&e.getAttribute("rel")==="stylesheet"&&t.getMeta(e))}function N9(e){return!!pp([e,"optionalAccess",t=>t.shadowRoot])}class nun{constructor(){this.id=1,this.styleIDMap=new WeakMap,this.idStyleMap=new Map}getId(t){return Uan(this.styleIDMap.get(t),()=>-1)}has(t){return this.styleIDMap.has(t)}add(t,n){if(this.has(t))return this.getId(t);let r;return n===void 0?r=this.id++:r=n,this.styleIDMap.set(t,r),this.idStyleMap.set(r,t),r}getStyle(t){return this.idStyleMap.get(t)||null}reset(){this.styleIDMap=new WeakMap,this.idStyleMap=new Map,this.id=1}generateId(){return this.id++}}function fze(e){let t=null;return pp([e,"access",n=>n.getRootNode,"optionalCall",n=>n(),"optionalAccess",n=>n.nodeType])===Node.DOCUMENT_FRAGMENT_NODE&&e.getRootNode().host&&(t=e.getRootNode().host),t}function run(e){let t=e,n;for(;n=fze(t);)t=n;return t}function iun(e){const t=e.ownerDocument;if(!t)return!1;const n=run(e);return t.contains(n)}function pze(e){const t=e.ownerDocument;return t?t.contains(e)||iun(e):!1}const R0e={};function bY(e){const t=R0e[e];if(t)return t;const n=window.document;let r=window[e];if(n&&typeof n.createElement=="function")try{const i=n.createElement("iframe");i.hidden=!0,n.head.appendChild(i);const a=i.contentWindow;a&&a[e]&&(r=a[e]),n.head.removeChild(i)}catch{}return R0e[e]=r.bind(window)}function aun(...e){return bY("requestAnimationFrame")(...e)}function t4(...e){return bY("setTimeout")(...e)}function sun(...e){return bY("clearTimeout")(...e)}var On=(e=>(e[e.DomContentLoaded=0]="DomContentLoaded",e[e.Load=1]="Load",e[e.FullSnapshot=2]="FullSnapshot",e[e.IncrementalSnapshot=3]="IncrementalSnapshot",e[e.Meta=4]="Meta",e[e.Custom=5]="Custom",e[e.Plugin=6]="Plugin",e))(On||{}),un=(e=>(e[e.Mutation=0]="Mutation",e[e.MouseMove=1]="MouseMove",e[e.MouseInteraction=2]="MouseInteraction",e[e.Scroll=3]="Scroll",e[e.ViewportResize=4]="ViewportResize",e[e.Input=5]="Input",e[e.TouchMove=6]="TouchMove",e[e.MediaInteraction=7]="MediaInteraction",e[e.StyleSheetRule=8]="StyleSheetRule",e[e.CanvasMutation=9]="CanvasMutation",e[e.Font=10]="Font",e[e.Log=11]="Log",e[e.Drag=12]="Drag",e[e.StyleDeclaration=13]="StyleDeclaration",e[e.Selection=14]="Selection",e[e.AdoptedStyleSheet=15]="AdoptedStyleSheet",e[e.CustomElement=16]="CustomElement",e))(un||{}),Fs=(e=>(e[e.MouseUp=0]="MouseUp",e[e.MouseDown=1]="MouseDown",e[e.Click=2]="Click",e[e.ContextMenu=3]="ContextMenu",e[e.DblClick=4]="DblClick",e[e.Focus=5]="Focus",e[e.Blur=6]="Blur",e[e.TouchStart=7]="TouchStart",e[e.TouchMove_Departed=8]="TouchMove_Departed",e[e.TouchEnd=9]="TouchEnd",e[e.TouchCancel=10]="TouchCancel",e))(Fs||{}),Sd=(e=>(e[e.Mouse=0]="Mouse",e[e.Pen=1]="Pen",e[e.Touch=2]="Touch",e))(Sd||{}),P0e;(function(e){e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment"})(P0e||(P0e={}));var $0e;(function(e){e[e.PLACEHOLDER=0]="PLACEHOLDER",e[e.ELEMENT_NODE=1]="ELEMENT_NODE",e[e.ATTRIBUTE_NODE=2]="ATTRIBUTE_NODE",e[e.TEXT_NODE=3]="TEXT_NODE",e[e.CDATA_SECTION_NODE=4]="CDATA_SECTION_NODE",e[e.ENTITY_REFERENCE_NODE=5]="ENTITY_REFERENCE_NODE",e[e.ENTITY_NODE=6]="ENTITY_NODE",e[e.PROCESSING_INSTRUCTION_NODE=7]="PROCESSING_INSTRUCTION_NODE",e[e.COMMENT_NODE=8]="COMMENT_NODE",e[e.DOCUMENT_NODE=9]="DOCUMENT_NODE",e[e.DOCUMENT_TYPE_NODE=10]="DOCUMENT_TYPE_NODE",e[e.DOCUMENT_FRAGMENT_NODE=11]="DOCUMENT_FRAGMENT_NODE"})($0e||($0e={}));function _Y(e){try{return e.contentDocument}catch{}}function oun(e){try{return e.contentWindow}catch{}}function lun(e){let t,n=e[0],r=1;for(;r<e.length;){const i=e[r],a=e[r+1];if(r+=2,(i==="optionalAccess"||i==="optionalCall")&&n==null)return;i==="access"||i==="optionalAccess"?(t=n,n=a(n)):(i==="call"||i==="optionalCall")&&(n=a((...s)=>n.call(t,...s)),t=void 0)}return n}function M0e(e){return"__ln"in e}class uun{constructor(){this.length=0,this.head=null,this.tail=null}get(t){if(t>=this.length)throw new Error("Position outside of list range");let n=this.head;for(let r=0;r<t;r++)n=lun([n,"optionalAccess",i=>i.next])||null;return n}addNode(t){const n={value:t,previous:null,next:null};if(t.__ln=n,t.previousSibling&&M0e(t.previousSibling)){const r=t.previousSibling.__ln.next;n.next=r,n.previous=t.previousSibling.__ln,t.previousSibling.__ln.next=n,r&&(r.previous=n)}else if(t.nextSibling&&M0e(t.nextSibling)&&t.nextSibling.__ln.previous){const r=t.nextSibling.__ln.previous;n.previous=r,n.next=t.nextSibling.__ln,t.nextSibling.__ln.previous=n,r&&(r.next=n)}else this.head&&(this.head.previous=n),n.next=this.head,this.head=n;n.next===null&&(this.tail=n),this.length++}removeNode(t){const n=t.__ln;this.head&&(n.previous?(n.previous.next=n.next,n.next?n.next.previous=n.previous:this.tail=n.previous):(this.head=n.next,this.head?this.head.previous=null:this.tail=null),t.__ln&&delete t.__ln,this.length--)}}const D0e=(e,t)=>`${e}@${t}`;class cun{constructor(){this.frozen=!1,this.locked=!1,this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.mapRemoves=[],this.movedMap={},this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.processMutations=t=>{t.forEach(this.processMutation),this.emit()},this.emit=()=>{if(this.frozen||this.locked)return;const t=[],n=new Set,r=new uun,i=u=>{let c=u,d=K2;for(;d===K2;)c=c&&c.nextSibling,d=c&&this.mirror.getId(c);return d},a=u=>{if(!u.parentNode||!pze(u))return;const c=dw(u.parentNode)?this.mirror.getId(fze(u)):this.mirror.getId(u.parentNode),d=i(u);if(c===-1||d===-1)return r.addNode(u);const f=Rv(u,{doc:this.doc,mirror:this.mirror,blockClass:this.blockClass,blockSelector:this.blockSelector,maskAllText:this.maskAllText,unblockSelector:this.unblockSelector,maskTextClass:this.maskTextClass,unmaskTextClass:this.unmaskTextClass,maskTextSelector:this.maskTextSelector,unmaskTextSelector:this.unmaskTextSelector,skipChild:!0,newlyAddedElement:!0,inlineStylesheet:this.inlineStylesheet,maskInputOptions:this.maskInputOptions,maskAttributeFn:this.maskAttributeFn,maskTextFn:this.maskTextFn,maskInputFn:this.maskInputFn,slimDOMOptions:this.slimDOMOptions,dataURLOptions:this.dataURLOptions,recordCanvas:this.recordCanvas,inlineImages:this.inlineImages,onSerialize:p=>{cze(p,this.mirror)&&!Vo(p,this.blockClass,this.blockSelector,this.unblockSelector,!1)&&this.iframeManager.addIframe(p),dze(p,this.mirror)&&this.stylesheetManager.trackLinkElement(p),N9(u)&&this.shadowDomManager.addShadowRoot(u.shadowRoot,this.doc)},onIframeLoad:(p,m)=>{Vo(p,this.blockClass,this.blockSelector,this.unblockSelector,!1)||(this.iframeManager.attachIframe(p,m),p.contentWindow&&this.canvasManager.addWindow(p.contentWindow),this.shadowDomManager.observeAttachShadow(p))},onStylesheetLoad:(p,m)=>{this.stylesheetManager.attachLinkElement(p,m)}});f&&(t.push({parentId:c,nextId:d,node:f}),n.add(f.id))};for(;this.mapRemoves.length;)this.mirror.removeNodeFromMap(this.mapRemoves.shift());for(const u of this.movedSet)L0e(this.removes,u,this.mirror)&&!this.movedSet.has(u.parentNode)||a(u);for(const u of this.addedSet)!z0e(this.droppedSet,u)&&!L0e(this.removes,u,this.mirror)||z0e(this.movedSet,u)?a(u):this.droppedSet.add(u);let s=null;for(;r.length;){let u=null;if(s){const c=this.mirror.getId(s.value.parentNode),d=i(s.value);c!==-1&&d!==-1&&(u=s)}if(!u){let c=r.tail;for(;c;){const d=c;if(c=c.previous,d){const f=this.mirror.getId(d.value.parentNode);if(i(d.value)===-1)continue;if(f!==-1){u=d;break}else{const m=d.value;if(m.parentNode&&m.parentNode.nodeType===Node.DOCUMENT_FRAGMENT_NODE){const y=m.parentNode.host;if(this.mirror.getId(y)!==-1){u=d;break}}}}}}if(!u){for(;r.head;)r.removeNode(r.head.value);break}s=u.previous,r.removeNode(u.value),a(u.value)}const o={texts:this.texts.map(u=>({id:this.mirror.getId(u.node),value:u.value})).filter(u=>!n.has(u.id)).filter(u=>this.mirror.has(u.id)),attributes:this.attributes.map(u=>{const{attributes:c}=u;if(typeof c.style=="string"){const d=JSON.stringify(u.styleDiff),f=JSON.stringify(u._unchangedStyles);d.length<c.style.length&&(d+f).split("var(").length===c.style.split("var(").length&&(c.style=u.styleDiff)}return{id:this.mirror.getId(u.node),attributes:c}}).filter(u=>!n.has(u.id)).filter(u=>this.mirror.has(u.id)),removes:this.removes,adds:t};!o.texts.length&&!o.attributes.length&&!o.removes.length&&!o.adds.length||(this.texts=[],this.attributes=[],this.attributeMap=new WeakMap,this.removes=[],this.addedSet=new Set,this.movedSet=new Set,this.droppedSet=new Set,this.movedMap={},this.mutationCb(o))},this.processMutation=t=>{if(!H8(t.target,this.mirror))switch(t.type){case"characterData":{const n=t.target.textContent;!Vo(t.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)&&n!==t.oldValue&&this.texts.push({value:px(t.target,this.maskTextClass,this.maskTextSelector,this.unmaskTextClass,this.unmaskTextSelector,this.maskAllText)&&n?this.maskTextFn?this.maskTextFn(n,lze(t.target)):n.replace(/[\S]/g,"*"):n,node:t.target});break}case"attributes":{const n=t.target;let r=t.attributeName,i=t.target.getAttribute(r);if(r==="value"){const s=vY(n),o=n.tagName;i=rO(n,o,s);const u=QP({maskInputOptions:this.maskInputOptions,tagName:o,type:s}),c=px(t.target,this.maskTextClass,this.maskTextSelector,this.unmaskTextClass,this.unmaskTextSelector,u);i=W2({isMasked:c,element:n,value:i,maskInputFn:this.maskInputFn})}if(Vo(t.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)||i===t.oldValue)return;let a=this.attributeMap.get(t.target);if(n.tagName==="IFRAME"&&r==="src"&&!this.keepIframeSrcFn(i))if(!_Y(n))r="rr_src";else return;if(a||(a={node:t.target,attributes:{},styleDiff:{},_unchangedStyles:{}},this.attributes.push(a),this.attributeMap.set(t.target,a)),r==="type"&&n.tagName==="INPUT"&&(t.oldValue||"").toLowerCase()==="password"&&n.setAttribute("data-rr-is-password","true"),!rze(n.tagName,r)&&(a.attributes[r]=nze(this.doc,fx(n.tagName),fx(r),i,n,this.maskAttributeFn),r==="style")){if(!this.unattachedDoc)try{this.unattachedDoc=document.implementation.createHTMLDocument()}catch{this.unattachedDoc=this.doc}const s=this.unattachedDoc.createElement("span");t.oldValue&&s.setAttribute("style",t.oldValue);for(const o of Array.from(n.style)){const u=n.style.getPropertyValue(o),c=n.style.getPropertyPriority(o);u!==s.style.getPropertyValue(o)||c!==s.style.getPropertyPriority(o)?c===""?a.styleDiff[o]=u:a.styleDiff[o]=[u,c]:a._unchangedStyles[o]=[u,c]}for(const o of Array.from(s.style))n.style.getPropertyValue(o)===""&&(a.styleDiff[o]=!1)}break}case"childList":{if(Vo(t.target,this.blockClass,this.blockSelector,this.unblockSelector,!0))return;t.addedNodes.forEach(n=>this.genAdds(n,t.target)),t.removedNodes.forEach(n=>{const r=this.mirror.getId(n),i=dw(t.target)?this.mirror.getId(t.target.host):this.mirror.getId(t.target);Vo(t.target,this.blockClass,this.blockSelector,this.unblockSelector,!1)||H8(n,this.mirror)||!eun(n,this.mirror)||(this.addedSet.has(n)?(C9(this.addedSet,n),this.droppedSet.add(n)):this.addedSet.has(t.target)&&r===-1||uze(t.target,this.mirror)||(this.movedSet.has(n)&&this.movedMap[D0e(r,i)]?C9(this.movedSet,n):this.removes.push({parentId:i,id:r,isShadow:dw(t.target)&&fw(t.target)?!0:void 0})),this.mapRemoves.push(n))});break}}},this.genAdds=(t,n)=>{if(!this.processedNodeManager.inOtherBuffer(t,this)&&!(this.addedSet.has(t)||this.movedSet.has(t))){if(this.mirror.hasNode(t)){if(H8(t,this.mirror))return;this.movedSet.add(t);let r=null;n&&this.mirror.hasNode(n)&&(r=this.mirror.getId(n)),r&&r!==-1&&(this.movedMap[D0e(this.mirror.getId(t),r)]=!0)}else this.addedSet.add(t),this.droppedSet.delete(t);Vo(t,this.blockClass,this.blockSelector,this.unblockSelector,!1)||(t.childNodes.forEach(r=>this.genAdds(r)),N9(t)&&t.shadowRoot.childNodes.forEach(r=>{this.processedNodeManager.add(r,this),this.genAdds(r,t)}))}}}init(t){["mutationCb","blockClass","blockSelector","unblockSelector","maskAllText","maskTextClass","unmaskTextClass","maskTextSelector","unmaskTextSelector","inlineStylesheet","maskInputOptions","maskAttributeFn","maskTextFn","maskInputFn","keepIframeSrcFn","recordCanvas","inlineImages","slimDOMOptions","dataURLOptions","doc","mirror","iframeManager","stylesheetManager","shadowDomManager","canvasManager","processedNodeManager"].forEach(n=>{this[n]=t[n]})}freeze(){this.frozen=!0,this.canvasManager.freeze()}unfreeze(){this.frozen=!1,this.canvasManager.unfreeze(),this.emit()}isFrozen(){return this.frozen}lock(){this.locked=!0,this.canvasManager.lock()}unlock(){this.locked=!1,this.canvasManager.unlock(),this.emit()}reset(){this.shadowDomManager.reset(),this.canvasManager.reset()}}function C9(e,t){e.delete(t),t.childNodes.forEach(n=>C9(e,n))}function L0e(e,t,n){return e.length===0?!1:dun(e,t,n)}function dun(e,t,n){let r=t.parentNode;for(;r;){const i=n.getId(r);if(e.some(a=>a.id===i))return!0;r=r.parentNode}return!1}function z0e(e,t){return e.size===0?!1:hze(e,t)}function hze(e,t){const{parentNode:n}=t;return n?e.has(n)?!0:hze(e,n):!1}let pw;function fun(e){pw=e}function pun(){pw=void 0}const sr=e=>pw?((...n)=>{try{return e(...n)}catch(r){if(pw&&pw(r)===!0)return()=>{};throw r}}):e;function vu(e){let t,n=e[0],r=1;for(;r<e.length;){const i=e[r],a=e[r+1];if(r+=2,(i==="optionalAccess"||i==="optionalCall")&&n==null)return;i==="access"||i==="optionalAccess"?(t=n,n=a(n)):(i==="call"||i==="optionalCall")&&(n=a((...s)=>n.call(t,...s)),t=void 0)}return n}const Pv=[];function Ok(e){try{if("composedPath"in e){const t=e.composedPath();if(t.length)return t[0]}else if("path"in e&&e.path.length)return e.path[0]}catch{}return e&&e.target}function mze(e,t){const n=new cun;Pv.push(n),n.init(e);let r=window.MutationObserver||window.__rrMutationObserver;const i=vu([window,"optionalAccess",s=>s.Zone,"optionalAccess",s=>s.__symbol__,"optionalCall",s=>s("MutationObserver")]);i&&window[i]&&(r=window[i]);const a=new r(sr(s=>{e.onMutation&&e.onMutation(s)===!1||n.processMutations.bind(n)(s)}));return a.observe(t,{attributes:!0,attributeOldValue:!0,characterData:!0,characterDataOldValue:!0,childList:!0,subtree:!0}),a}function hun({mousemoveCb:e,sampling:t,doc:n,mirror:r}){if(t.mousemove===!1)return()=>{};const i=typeof t.mousemove=="number"?t.mousemove:50,a=typeof t.mousemoveCallback=="number"?t.mousemoveCallback:500;let s=[],o;const u=Z2(sr(f=>{const p=Date.now()-o;e(s.map(m=>(m.timeOffset-=p,m)),f),s=[],o=null}),a),c=sr(Z2(sr(f=>{const p=Ok(f),{clientX:m,clientY:y}=T9(f)?f.changedTouches[0]:f;o||(o=aO()),s.push({x:m,y,id:r.getId(p),timeOffset:aO()-o}),u(typeof DragEvent<"u"&&f instanceof DragEvent?un.Drag:f instanceof MouseEvent?un.MouseMove:un.TouchMove)}),i,{trailing:!1})),d=[Hs("mousemove",c,n),Hs("touchmove",c,n),Hs("drag",c,n)];return sr(()=>{d.forEach(f=>f())})}function mun({mouseInteractionCb:e,doc:t,mirror:n,blockClass:r,blockSelector:i,unblockSelector:a,sampling:s}){if(s.mouseInteraction===!1)return()=>{};const o=s.mouseInteraction===!0||s.mouseInteraction===void 0?{}:s.mouseInteraction,u=[];let c=null;const d=f=>p=>{const m=Ok(p);if(Vo(m,r,i,a,!0))return;let y=null,v=f;if("pointerType"in p){switch(p.pointerType){case"mouse":y=Sd.Mouse;break;case"touch":y=Sd.Touch;break;case"pen":y=Sd.Pen;break}y===Sd.Touch?Fs[f]===Fs.MouseDown?v="TouchStart":Fs[f]===Fs.MouseUp&&(v="TouchEnd"):Sd.Pen}else T9(p)&&(y=Sd.Touch);y!==null?(c=y,(v.startsWith("Touch")&&y===Sd.Touch||v.startsWith("Mouse")&&y===Sd.Mouse)&&(y=null)):Fs[f]===Fs.Click&&(y=c,c=null);const x=T9(p)?p.changedTouches[0]:p;if(!x)return;const _=n.getId(m),{clientX:S,clientY:w}=x;sr(e)({type:Fs[v],id:_,x:S,y:w,...y!==null&&{pointerType:y}})};return Object.keys(Fs).filter(f=>Number.isNaN(Number(f))&&!f.endsWith("_Departed")&&o[f]!==!1).forEach(f=>{let p=fx(f);const m=d(f);if(window.PointerEvent)switch(Fs[f]){case Fs.MouseDown:case Fs.MouseUp:p=p.replace("mouse","pointer");break;case Fs.TouchStart:case Fs.TouchEnd:return}u.push(Hs(p,m,t))}),sr(()=>{u.forEach(f=>f())})}function gze({scrollCb:e,doc:t,mirror:n,blockClass:r,blockSelector:i,unblockSelector:a,sampling:s}){const o=sr(Z2(sr(u=>{const c=Ok(u);if(!c||Vo(c,r,i,a,!0))return;const d=n.getId(c);if(c===t&&t.defaultView){const f=aze(t.defaultView);e({id:d,x:f.left,y:f.top})}else e({id:d,x:c.scrollLeft,y:c.scrollTop})}),s.scroll||100));return Hs("scroll",o,t)}function gun({viewportResizeCb:e},{win:t}){let n=-1,r=-1;const i=sr(Z2(sr(()=>{const a=sze(),s=oze();(n!==a||r!==s)&&(e({width:Number(s),height:Number(a)}),n=a,r=s)}),200));return Hs("resize",i,t)}const vun=["INPUT","TEXTAREA","SELECT"],U0e=new WeakMap;function yun({inputCb:e,doc:t,mirror:n,blockClass:r,blockSelector:i,unblockSelector:a,ignoreClass:s,ignoreSelector:o,maskInputOptions:u,maskInputFn:c,sampling:d,userTriggeredOnInput:f,maskTextClass:p,unmaskTextClass:m,maskTextSelector:y,unmaskTextSelector:v}){function x(A){let I=Ok(A);const M=A.isTrusted,$=I&&k9(I.tagName);if($==="OPTION"&&(I=I.parentElement),!I||!$||vun.indexOf($)<0||Vo(I,r,i,a,!0))return;const O=I;if(O.classList.contains(s)||o&&O.matches(o))return;const R=vY(I);let U=rO(O,$,R),z=!1;const F=QP({maskInputOptions:u,tagName:$,type:R}),D=px(I,p,y,m,v,F);(R==="radio"||R==="checkbox")&&(z=I.checked),U=W2({isMasked:D,element:I,value:U,maskInputFn:c}),_(I,f?{text:U,isChecked:z,userTriggered:M}:{text:U,isChecked:z});const W=I.name;R==="radio"&&W&&z&&t.querySelectorAll(`input[type="radio"][name="${W}"]`).forEach(q=>{if(q!==I){const X=W2({isMasked:D,element:q,value:rO(q,$,R),maskInputFn:c});_(q,f?{text:X,isChecked:!z,userTriggered:!1}:{text:X,isChecked:!z})}})}function _(A,I){const M=U0e.get(A);if(!M||M.text!==I.text||M.isChecked!==I.isChecked){U0e.set(A,I);const $=n.getId(A);sr(e)({...I,id:$})}}const w=(d.input==="last"?["change"]:["input","change"]).map(A=>Hs(A,sr(x),t)),T=t.defaultView;if(!T)return()=>{w.forEach(A=>A())};const N=T.Object.getOwnPropertyDescriptor(T.HTMLInputElement.prototype,"value"),E=[[T.HTMLInputElement.prototype,"value"],[T.HTMLInputElement.prototype,"checked"],[T.HTMLSelectElement.prototype,"value"],[T.HTMLTextAreaElement.prototype,"value"],[T.HTMLSelectElement.prototype,"selectedIndex"],[T.HTMLOptionElement.prototype,"selected"]];return N&&N.set&&w.push(...E.map(A=>ize(A[0],A[1],{set(){sr(x)({target:this,isTrusted:!1})}},!1,T))),sr(()=>{w.forEach(A=>A())})}function sO(e){const t=[];function n(r,i){if(tC("CSSGroupingRule")&&r.parentRule instanceof CSSGroupingRule||tC("CSSMediaRule")&&r.parentRule instanceof CSSMediaRule||tC("CSSSupportsRule")&&r.parentRule instanceof CSSSupportsRule||tC("CSSConditionRule")&&r.parentRule instanceof CSSConditionRule){const s=Array.from(r.parentRule.cssRules).indexOf(r);i.unshift(s)}else if(r.parentStyleSheet){const s=Array.from(r.parentStyleSheet.cssRules).indexOf(r);i.unshift(s)}return i}return n(e,t)}function hp(e,t,n){let r,i;return e?(e.ownerNode?r=t.getId(e.ownerNode):i=n.getId(e),{styleId:i,id:r}):{}}function xun({styleSheetRuleCb:e,mirror:t,stylesheetManager:n},{win:r}){if(!r.CSSStyleSheet||!r.CSSStyleSheet.prototype)return()=>{};const i=r.CSSStyleSheet.prototype.insertRule;r.CSSStyleSheet.prototype.insertRule=new Proxy(i,{apply:sr((d,f,p)=>{const[m,y]=p,{id:v,styleId:x}=hp(f,t,n.styleMirror);return(v&&v!==-1||x&&x!==-1)&&e({id:v,styleId:x,adds:[{rule:m,index:y}]}),d.apply(f,p)})});const a=r.CSSStyleSheet.prototype.deleteRule;r.CSSStyleSheet.prototype.deleteRule=new Proxy(a,{apply:sr((d,f,p)=>{const[m]=p,{id:y,styleId:v}=hp(f,t,n.styleMirror);return(y&&y!==-1||v&&v!==-1)&&e({id:y,styleId:v,removes:[{index:m}]}),d.apply(f,p)})});let s;r.CSSStyleSheet.prototype.replace&&(s=r.CSSStyleSheet.prototype.replace,r.CSSStyleSheet.prototype.replace=new Proxy(s,{apply:sr((d,f,p)=>{const[m]=p,{id:y,styleId:v}=hp(f,t,n.styleMirror);return(y&&y!==-1||v&&v!==-1)&&e({id:y,styleId:v,replace:m}),d.apply(f,p)})}));let o;r.CSSStyleSheet.prototype.replaceSync&&(o=r.CSSStyleSheet.prototype.replaceSync,r.CSSStyleSheet.prototype.replaceSync=new Proxy(o,{apply:sr((d,f,p)=>{const[m]=p,{id:y,styleId:v}=hp(f,t,n.styleMirror);return(y&&y!==-1||v&&v!==-1)&&e({id:y,styleId:v,replaceSync:m}),d.apply(f,p)})}));const u={};nC("CSSGroupingRule")?u.CSSGroupingRule=r.CSSGroupingRule:(nC("CSSMediaRule")&&(u.CSSMediaRule=r.CSSMediaRule),nC("CSSConditionRule")&&(u.CSSConditionRule=r.CSSConditionRule),nC("CSSSupportsRule")&&(u.CSSSupportsRule=r.CSSSupportsRule));const c={};return Object.entries(u).forEach(([d,f])=>{c[d]={insertRule:f.prototype.insertRule,deleteRule:f.prototype.deleteRule},f.prototype.insertRule=new Proxy(c[d].insertRule,{apply:sr((p,m,y)=>{const[v,x]=y,{id:_,styleId:S}=hp(m.parentStyleSheet,t,n.styleMirror);return(_&&_!==-1||S&&S!==-1)&&e({id:_,styleId:S,adds:[{rule:v,index:[...sO(m),x||0]}]}),p.apply(m,y)})}),f.prototype.deleteRule=new Proxy(c[d].deleteRule,{apply:sr((p,m,y)=>{const[v]=y,{id:x,styleId:_}=hp(m.parentStyleSheet,t,n.styleMirror);return(x&&x!==-1||_&&_!==-1)&&e({id:x,styleId:_,removes:[{index:[...sO(m),v]}]}),p.apply(m,y)})})}),sr(()=>{r.CSSStyleSheet.prototype.insertRule=i,r.CSSStyleSheet.prototype.deleteRule=a,s&&(r.CSSStyleSheet.prototype.replace=s),o&&(r.CSSStyleSheet.prototype.replaceSync=o),Object.entries(u).forEach(([d,f])=>{f.prototype.insertRule=c[d].insertRule,f.prototype.deleteRule=c[d].deleteRule})})}function vze({mirror:e,stylesheetManager:t},n){let r=null;n.nodeName==="#document"?r=e.getId(n):r=e.getId(n.host);const i=n.nodeName==="#document"?vu([n,"access",s=>s.defaultView,"optionalAccess",s=>s.Document]):vu([n,"access",s=>s.ownerDocument,"optionalAccess",s=>s.defaultView,"optionalAccess",s=>s.ShadowRoot]),a=vu([i,"optionalAccess",s=>s.prototype])?Object.getOwnPropertyDescriptor(vu([i,"optionalAccess",s=>s.prototype]),"adoptedStyleSheets"):void 0;return r===null||r===-1||!i||!a?()=>{}:(Object.defineProperty(n,"adoptedStyleSheets",{configurable:a.configurable,enumerable:a.enumerable,get(){return vu([a,"access",s=>s.get,"optionalAccess",s=>s.call,"call",s=>s(this)])},set(s){const o=vu([a,"access",u=>u.set,"optionalAccess",u=>u.call,"call",u=>u(this,s)]);if(r!==null&&r!==-1)try{t.adoptStyleSheets(s,r)}catch{}return o}}),sr(()=>{Object.defineProperty(n,"adoptedStyleSheets",{configurable:a.configurable,enumerable:a.enumerable,get:a.get,set:a.set})}))}function bun({styleDeclarationCb:e,mirror:t,ignoreCSSAttributes:n,stylesheetManager:r},{win:i}){const a=i.CSSStyleDeclaration.prototype.setProperty;i.CSSStyleDeclaration.prototype.setProperty=new Proxy(a,{apply:sr((o,u,c)=>{const[d,f,p]=c;if(n.has(d))return a.apply(u,[d,f,p]);const{id:m,styleId:y}=hp(vu([u,"access",v=>v.parentRule,"optionalAccess",v=>v.parentStyleSheet]),t,r.styleMirror);return(m&&m!==-1||y&&y!==-1)&&e({id:m,styleId:y,set:{property:d,value:f,priority:p},index:sO(u.parentRule)}),o.apply(u,c)})});const s=i.CSSStyleDeclaration.prototype.removeProperty;return i.CSSStyleDeclaration.prototype.removeProperty=new Proxy(s,{apply:sr((o,u,c)=>{const[d]=c;if(n.has(d))return s.apply(u,[d]);const{id:f,styleId:p}=hp(vu([u,"access",m=>m.parentRule,"optionalAccess",m=>m.parentStyleSheet]),t,r.styleMirror);return(f&&f!==-1||p&&p!==-1)&&e({id:f,styleId:p,remove:{property:d},index:sO(u.parentRule)}),o.apply(u,c)})}),sr(()=>{i.CSSStyleDeclaration.prototype.setProperty=a,i.CSSStyleDeclaration.prototype.removeProperty=s})}function _un({mediaInteractionCb:e,blockClass:t,blockSelector:n,unblockSelector:r,mirror:i,sampling:a,doc:s}){const o=sr(c=>Z2(sr(d=>{const f=Ok(d);if(!f||Vo(f,t,n,r,!0))return;const{currentTime:p,volume:m,muted:y,playbackRate:v}=f;e({type:c,id:i.getId(f),currentTime:p,volume:m,muted:y,playbackRate:v})}),a.media||500)),u=[Hs("play",o(0),s),Hs("pause",o(1),s),Hs("seeked",o(2),s),Hs("volumechange",o(3),s),Hs("ratechange",o(4),s)];return sr(()=>{u.forEach(c=>c())})}function wun({fontCb:e,doc:t}){const n=t.defaultView;if(!n)return()=>{};const r=[],i=new WeakMap,a=n.FontFace;n.FontFace=function(u,c,d){const f=new a(u,c,d);return i.set(f,{family:u,buffer:typeof c!="string",descriptors:d,fontSource:typeof c=="string"?c:JSON.stringify(Array.from(new Uint8Array(c)))}),f};const s=xY(t.fonts,"add",function(o){return function(u){return t4(sr(()=>{const c=i.get(u);c&&(e(c),i.delete(u))}),0),o.apply(this,[u])}});return r.push(()=>{n.FontFace=a}),r.push(s),sr(()=>{r.forEach(o=>o())})}function Sun(e){const{doc:t,mirror:n,blockClass:r,blockSelector:i,unblockSelector:a,selectionCb:s}=e;let o=!0;const u=sr(()=>{const c=t.getSelection();if(!c||o&&vu([c,"optionalAccess",p=>p.isCollapsed]))return;o=c.isCollapsed||!1;const d=[],f=c.rangeCount||0;for(let p=0;p<f;p++){const m=c.getRangeAt(p),{startContainer:y,startOffset:v,endContainer:x,endOffset:_}=m;Vo(y,r,i,a,!0)||Vo(x,r,i,a,!0)||d.push({start:n.getId(y),startOffset:v,end:n.getId(x),endOffset:_})}s({ranges:d})});return u(),Hs("selectionchange",u)}function kun({doc:e,customElementCb:t}){const n=e.defaultView;return!n||!n.customElements?()=>{}:xY(n.customElements,"define",function(i){return function(a,s,o){try{t({define:{name:a}})}catch{}return i.apply(this,[a,s,o])}})}function Eun(e,t={}){const n=e.doc.defaultView;if(!n)return()=>{};let r;e.recordDOM&&(r=mze(e,e.doc));const i=hun(e),a=mun(e),s=gze(e),o=gun(e,{win:n}),u=yun(e),c=_un(e);let d=()=>{},f=()=>{},p=()=>{},m=()=>{};e.recordDOM&&(d=xun(e,{win:n}),f=vze(e,e.doc),p=bun(e,{win:n}),e.collectFonts&&(m=wun(e)));const y=Sun(e),v=kun(e),x=[];for(const _ of e.plugins)x.push(_.observer(_.callback,n,_.options));return sr(()=>{Pv.forEach(_=>_.reset()),vu([r,"optionalAccess",_=>_.disconnect,"call",_=>_()]),i(),a(),s(),o(),u(),c(),d(),f(),p(),m(),y(),v(),x.forEach(_=>_())})}function tC(e){return typeof window[e]<"u"}function nC(e){return!!(typeof window[e]<"u"&&window[e].prototype&&"insertRule"in window[e].prototype&&"deleteRule"in window[e].prototype)}class A9{constructor(t){this.generateIdFn=t,this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap}getId(t,n,r,i){const a=r||this.getIdToRemoteIdMap(t),s=i||this.getRemoteIdToIdMap(t);let o=a.get(n);return o||(o=this.generateIdFn(),a.set(n,o),s.set(o,n)),o}getIds(t,n){const r=this.getIdToRemoteIdMap(t),i=this.getRemoteIdToIdMap(t);return n.map(a=>this.getId(t,a,r,i))}getRemoteId(t,n,r){const i=r||this.getRemoteIdToIdMap(t);if(typeof n!="number")return n;const a=i.get(n);return a||-1}getRemoteIds(t,n){const r=this.getRemoteIdToIdMap(t);return n.map(i=>this.getRemoteId(t,i,r))}reset(t){if(!t){this.iframeIdToRemoteIdMap=new WeakMap,this.iframeRemoteIdToIdMap=new WeakMap;return}this.iframeIdToRemoteIdMap.delete(t),this.iframeRemoteIdToIdMap.delete(t)}getIdToRemoteIdMap(t){let n=this.iframeIdToRemoteIdMap.get(t);return n||(n=new Map,this.iframeIdToRemoteIdMap.set(t,n)),n}getRemoteIdToIdMap(t){let n=this.iframeRemoteIdToIdMap.get(t);return n||(n=new Map,this.iframeRemoteIdToIdMap.set(t,n)),n}}function F0e(e){let t,n=e[0],r=1;for(;r<e.length;){const i=e[r],a=e[r+1];if(r+=2,(i==="optionalAccess"||i==="optionalCall")&&n==null)return;i==="access"||i==="optionalAccess"?(t=n,n=a(n)):(i==="call"||i==="optionalCall")&&(n=a((...s)=>n.call(t,...s)),t=void 0)}return n}class Tun{constructor(){this.crossOriginIframeMirror=new A9(yY),this.crossOriginIframeRootIdMap=new WeakMap}addIframe(){}addLoadListener(){}attachIframe(){}}class Nun{constructor(t){this.iframes=new WeakMap,this.crossOriginIframeMap=new WeakMap,this.crossOriginIframeMirror=new A9(yY),this.crossOriginIframeRootIdMap=new WeakMap,this.mutationCb=t.mutationCb,this.wrappedEmit=t.wrappedEmit,this.stylesheetManager=t.stylesheetManager,this.recordCrossOriginIframes=t.recordCrossOriginIframes,this.crossOriginIframeStyleMirror=new A9(this.stylesheetManager.styleMirror.generateId.bind(this.stylesheetManager.styleMirror)),this.mirror=t.mirror,this.recordCrossOriginIframes&&window.addEventListener("message",this.handleMessage.bind(this))}addIframe(t){this.iframes.set(t,!0),t.contentWindow&&this.crossOriginIframeMap.set(t.contentWindow,t)}addLoadListener(t){this.loadListener=t}attachIframe(t,n){this.mutationCb({adds:[{parentId:this.mirror.getId(t),nextId:null,node:n}],removes:[],texts:[],attributes:[],isAttachIframe:!0}),F0e([this,"access",i=>i.loadListener,"optionalCall",i=>i(t)]);const r=_Y(t);r&&r.adoptedStyleSheets&&r.adoptedStyleSheets.length>0&&this.stylesheetManager.adoptStyleSheets(r.adoptedStyleSheets,this.mirror.getId(r))}handleMessage(t){const n=t;if(n.data.type!=="rrweb"||n.origin!==n.data.origin||!t.source)return;const i=this.crossOriginIframeMap.get(t.source);if(!i)return;const a=this.transformCrossOriginEvent(i,n.data.event);a&&this.wrappedEmit(a,n.data.isCheckout)}transformCrossOriginEvent(t,n){switch(n.type){case On.FullSnapshot:{this.crossOriginIframeMirror.reset(t),this.crossOriginIframeStyleMirror.reset(t),this.replaceIdOnNode(n.data.node,t);const r=n.data.node.id;return this.crossOriginIframeRootIdMap.set(t,r),this.patchRootIdOnNode(n.data.node,r),{timestamp:n.timestamp,type:On.IncrementalSnapshot,data:{source:un.Mutation,adds:[{parentId:this.mirror.getId(t),nextId:null,node:n.data.node}],removes:[],texts:[],attributes:[],isAttachIframe:!0}}}case On.Meta:case On.Load:case On.DomContentLoaded:return!1;case On.Plugin:return n;case On.Custom:return this.replaceIds(n.data.payload,t,["id","parentId","previousId","nextId"]),n;case On.IncrementalSnapshot:switch(n.data.source){case un.Mutation:return n.data.adds.forEach(r=>{this.replaceIds(r,t,["parentId","nextId","previousId"]),this.replaceIdOnNode(r.node,t);const i=this.crossOriginIframeRootIdMap.get(t);i&&this.patchRootIdOnNode(r.node,i)}),n.data.removes.forEach(r=>{this.replaceIds(r,t,["parentId","id"])}),n.data.attributes.forEach(r=>{this.replaceIds(r,t,["id"])}),n.data.texts.forEach(r=>{this.replaceIds(r,t,["id"])}),n;case un.Drag:case un.TouchMove:case un.MouseMove:return n.data.positions.forEach(r=>{this.replaceIds(r,t,["id"])}),n;case un.ViewportResize:return!1;case un.MediaInteraction:case un.MouseInteraction:case un.Scroll:case un.CanvasMutation:case un.Input:return this.replaceIds(n.data,t,["id"]),n;case un.StyleSheetRule:case un.StyleDeclaration:return this.replaceIds(n.data,t,["id"]),this.replaceStyleIds(n.data,t,["styleId"]),n;case un.Font:return n;case un.Selection:return n.data.ranges.forEach(r=>{this.replaceIds(r,t,["start","end"])}),n;case un.AdoptedStyleSheet:return this.replaceIds(n.data,t,["id"]),this.replaceStyleIds(n.data,t,["styleIds"]),F0e([n,"access",r=>r.data,"access",r=>r.styles,"optionalAccess",r=>r.forEach,"call",r=>r(i=>{this.replaceStyleIds(i,t,["styleId"])})]),n}}return!1}replace(t,n,r,i){for(const a of i)!Array.isArray(n[a])&&typeof n[a]!="number"||(Array.isArray(n[a])?n[a]=t.getIds(r,n[a]):n[a]=t.getId(r,n[a]));return n}replaceIds(t,n,r){return this.replace(this.crossOriginIframeMirror,t,n,r)}replaceStyleIds(t,n,r){return this.replace(this.crossOriginIframeStyleMirror,t,n,r)}replaceIdOnNode(t,n){this.replaceIds(t,n,["id","rootId"]),"childNodes"in t&&t.childNodes.forEach(r=>{this.replaceIdOnNode(r,n)})}patchRootIdOnNode(t,n){t.type!==_a.Document&&!t.rootId&&(t.rootId=n),"childNodes"in t&&t.childNodes.forEach(r=>{this.patchRootIdOnNode(r,n)})}}class Cun{init(){}addShadowRoot(){}observeAttachShadow(){}reset(){}}class Aun{constructor(t){this.shadowDoms=new WeakSet,this.restoreHandlers=[],this.mutationCb=t.mutationCb,this.scrollCb=t.scrollCb,this.bypassOptions=t.bypassOptions,this.mirror=t.mirror,this.init()}init(){this.reset(),this.patchAttachShadow(Element,document)}addShadowRoot(t,n){if(!fw(t)||this.shadowDoms.has(t))return;this.shadowDoms.add(t),this.bypassOptions.canvasManager.addShadowRoot(t);const r=mze({...this.bypassOptions,doc:n,mutationCb:this.mutationCb,mirror:this.mirror,shadowDomManager:this},t);this.restoreHandlers.push(()=>r.disconnect()),this.restoreHandlers.push(gze({...this.bypassOptions,scrollCb:this.scrollCb,doc:t,mirror:this.mirror})),t4(()=>{t.adoptedStyleSheets&&t.adoptedStyleSheets.length>0&&this.bypassOptions.stylesheetManager.adoptStyleSheets(t.adoptedStyleSheets,this.mirror.getId(t.host)),this.restoreHandlers.push(vze({mirror:this.mirror,stylesheetManager:this.bypassOptions.stylesheetManager},t))},0)}observeAttachShadow(t){const n=_Y(t),r=oun(t);!n||!r||this.patchAttachShadow(r.Element,n)}patchAttachShadow(t,n){const r=this;this.restoreHandlers.push(xY(t.prototype,"attachShadow",function(i){return function(a){const s=i.call(this,a);return this.shadowRoot&&pze(this)&&r.addShadowRoot(this.shadowRoot,n),s}}))}reset(){this.restoreHandlers.forEach(t=>{try{t()}catch{}}),this.restoreHandlers=[],this.shadowDoms=new WeakSet,this.bypassOptions.canvasManager.resetShadowRoots()}}class B0e{reset(){}freeze(){}unfreeze(){}lock(){}unlock(){}snapshot(){}addWindow(){}addShadowRoot(){}resetShadowRoots(){}}class Iun{constructor(t){this.trackedLinkElements=new WeakSet,this.styleMirror=new nun,this.mutationCb=t.mutationCb,this.adoptedStyleSheetCb=t.adoptedStyleSheetCb}attachLinkElement(t,n){"_cssText"in n.attributes&&this.mutationCb({adds:[],removes:[],texts:[],attributes:[{id:n.id,attributes:n.attributes}]}),this.trackLinkElement(t)}trackLinkElement(t){this.trackedLinkElements.has(t)||(this.trackedLinkElements.add(t),this.trackStylesheetInLinkElement(t))}adoptStyleSheets(t,n){if(t.length===0)return;const r={id:n,styleIds:[]},i=[];for(const a of t){let s;this.styleMirror.has(a)?s=this.styleMirror.getId(a):(s=this.styleMirror.add(a),i.push({styleId:s,rules:Array.from(a.rules||CSSRule,(o,u)=>({rule:YLe(o),index:u}))})),r.styleIds.push(s)}i.length>0&&(r.styles=i),this.adoptedStyleSheetCb(r)}reset(){this.styleMirror.reset(),this.trackedLinkElements=new WeakSet}trackStylesheetInLinkElement(t){}}class jun{constructor(){this.nodeMap=new WeakMap,this.active=!1}inOtherBuffer(t,n){const r=this.nodeMap.get(t);return r&&Array.from(r).some(i=>i!==n)}add(t,n){this.active||(this.active=!0,aun(()=>{this.nodeMap=new WeakMap,this.active=!1})),this.nodeMap.set(t,(this.nodeMap.get(t)||new Set).add(n))}destroy(){}}let Mi,oO;try{if(Array.from([1],e=>e*2)[0]!==2){const e=document.createElement("iframe");document.body.appendChild(e),Array.from=LC([e,"access",t=>t.contentWindow,"optionalAccess",t=>t.Array,"access",t=>t.from])||Array.from,document.body.removeChild(e)}}catch(e){console.debug("Unable to override Array.from",e)}const su=Iln();function Jd(e={}){const{emit:t,checkoutEveryNms:n,checkoutEveryNth:r,blockClass:i="rr-block",blockSelector:a=null,unblockSelector:s=null,ignoreClass:o="rr-ignore",ignoreSelector:u=null,maskAllText:c=!1,maskTextClass:d="rr-mask",unmaskTextClass:f=null,maskTextSelector:p=null,unmaskTextSelector:m=null,inlineStylesheet:y=!0,maskAllInputs:v,maskInputOptions:x,slimDOMOptions:_,maskAttributeFn:S,maskInputFn:w,maskTextFn:T,maxCanvasSize:N=null,packFn:E,sampling:A={},dataURLOptions:I={},mousemoveWait:M,recordDOM:$=!0,recordCanvas:O=!1,recordCrossOriginIframes:R=!1,recordAfter:U=e.recordAfter==="DOMContentLoaded"?e.recordAfter:"load",userTriggeredOnInput:z=!1,collectFonts:F=!1,inlineImages:D=!1,plugins:W,keepIframeSrcFn:q=()=>!1,ignoreCSSAttributes:X=new Set([]),errorHandler:L,onMutation:Y,getCanvasManager:G}=e;fun(L);const P=R?window.parent===window:!0;let V=!1;if(!P)try{window.parent.document&&(V=!1)}catch{V=!0}if(P&&!t)throw new Error("emit function is required");if(!P&&!V)return()=>{};M!==void 0&&A.mousemove===void 0&&(A.mousemove=M),su.reset();const K=v===!0?{color:!0,date:!0,"datetime-local":!0,email:!0,month:!0,number:!0,range:!0,search:!0,tel:!0,text:!0,time:!0,url:!0,week:!0,textarea:!0,select:!0,radio:!0,checkbox:!0}:x!==void 0?x:{},Q=_===!0||_==="all"?{script:!0,comment:!0,headFavicon:!0,headWhitespace:!0,headMetaSocial:!0,headMetaRobots:!0,headMetaHttpEquiv:!0,headMetaVerification:!0,headMetaAuthorship:_==="all",headMetaDescKeywords:_==="all"}:_||{};tun();let oe,re=0;const ee=ce=>{for(const Te of W||[])Te.eventProcessor&&(ce=Te.eventProcessor(ce));return E&&!V&&(ce=E(ce)),ce};Mi=(ce,Te)=>{const we=ce;if(we.timestamp=aO(),LC([Pv,"access",Oe=>Oe[0],"optionalAccess",Oe=>Oe.isFrozen,"call",Oe=>Oe()])&&we.type!==On.FullSnapshot&&!(we.type===On.IncrementalSnapshot&&we.data.source===un.Mutation)&&Pv.forEach(Oe=>Oe.unfreeze()),P)LC([t,"optionalCall",Oe=>Oe(ee(we),Te)]);else if(V){const Oe={type:"rrweb",event:ee(we),origin:window.location.origin,isCheckout:Te};window.parent.postMessage(Oe,"*")}if(we.type===On.FullSnapshot)oe=we,re=0;else if(we.type===On.IncrementalSnapshot){if(we.data.source===un.Mutation&&we.data.isAttachIframe)return;re++;const Oe=r&&re>=r,Ue=n&&oe&&we.timestamp-oe.timestamp>n;(Oe||Ue)&&Ne(!0)}};const le=ce=>{Mi({type:On.IncrementalSnapshot,data:{source:un.Mutation,...ce}})},te=ce=>Mi({type:On.IncrementalSnapshot,data:{source:un.Scroll,...ce}}),Z=ce=>Mi({type:On.IncrementalSnapshot,data:{source:un.CanvasMutation,...ce}}),ne=ce=>Mi({type:On.IncrementalSnapshot,data:{source:un.AdoptedStyleSheet,...ce}}),J=new Iun({mutationCb:le,adoptedStyleSheetCb:ne}),se=typeof __RRWEB_EXCLUDE_IFRAME__=="boolean"&&__RRWEB_EXCLUDE_IFRAME__?new Tun:new Nun({mirror:su,mutationCb:le,stylesheetManager:J,recordCrossOriginIframes:R,wrappedEmit:Mi});for(const ce of W||[])ce.getMirror&&ce.getMirror({nodeMirror:su,crossOriginIframeMirror:se.crossOriginIframeMirror,crossOriginIframeStyleMirror:se.crossOriginIframeStyleMirror});const ie=new jun,he=Run(G,{mirror:su,win:window,mutationCb:ce=>Mi({type:On.IncrementalSnapshot,data:{source:un.CanvasMutation,...ce}}),recordCanvas:O,blockClass:i,blockSelector:a,unblockSelector:s,maxCanvasSize:N,sampling:A.canvas,dataURLOptions:I,errorHandler:L}),ye=typeof __RRWEB_EXCLUDE_SHADOW_DOM__=="boolean"&&__RRWEB_EXCLUDE_SHADOW_DOM__?new Cun:new Aun({mutationCb:le,scrollCb:te,bypassOptions:{onMutation:Y,blockClass:i,blockSelector:a,unblockSelector:s,maskAllText:c,maskTextClass:d,unmaskTextClass:f,maskTextSelector:p,unmaskTextSelector:m,inlineStylesheet:y,maskInputOptions:K,dataURLOptions:I,maskAttributeFn:S,maskTextFn:T,maskInputFn:w,recordCanvas:O,inlineImages:D,sampling:A,slimDOMOptions:Q,iframeManager:se,stylesheetManager:J,canvasManager:he,keepIframeSrcFn:q,processedNodeManager:ie},mirror:su}),Ne=(ce=!1)=>{if(!$)return;Mi({type:On.Meta,data:{href:window.location.href,width:oze(),height:sze()}},ce),J.reset(),ye.init(),Pv.forEach(we=>we.lock());const Te=Qln(document,{mirror:su,blockClass:i,blockSelector:a,unblockSelector:s,maskAllText:c,maskTextClass:d,unmaskTextClass:f,maskTextSelector:p,unmaskTextSelector:m,inlineStylesheet:y,maskAllInputs:K,maskAttributeFn:S,maskInputFn:w,maskTextFn:T,slimDOM:Q,dataURLOptions:I,recordCanvas:O,inlineImages:D,onSerialize:we=>{cze(we,su)&&se.addIframe(we),dze(we,su)&&J.trackLinkElement(we),N9(we)&&ye.addShadowRoot(we.shadowRoot,document)},onIframeLoad:(we,Oe)=>{se.attachIframe(we,Oe),we.contentWindow&&he.addWindow(we.contentWindow),ye.observeAttachShadow(we)},onStylesheetLoad:(we,Oe)=>{J.attachLinkElement(we,Oe)},keepIframeSrcFn:q});if(!Te)return console.warn("Failed to snapshot the document");Mi({type:On.FullSnapshot,data:{node:Te,initialOffset:aze(window)}}),Pv.forEach(we=>we.unlock()),document.adoptedStyleSheets&&document.adoptedStyleSheets.length>0&&J.adoptStyleSheets(document.adoptedStyleSheets,su.getId(document))};oO=Ne;try{const ce=[],Te=Oe=>sr(Eun)({onMutation:Y,mutationCb:le,mousemoveCb:(Ue,Me)=>Mi({type:On.IncrementalSnapshot,data:{source:Me,positions:Ue}}),mouseInteractionCb:Ue=>Mi({type:On.IncrementalSnapshot,data:{source:un.MouseInteraction,...Ue}}),scrollCb:te,viewportResizeCb:Ue=>Mi({type:On.IncrementalSnapshot,data:{source:un.ViewportResize,...Ue}}),inputCb:Ue=>Mi({type:On.IncrementalSnapshot,data:{source:un.Input,...Ue}}),mediaInteractionCb:Ue=>Mi({type:On.IncrementalSnapshot,data:{source:un.MediaInteraction,...Ue}}),styleSheetRuleCb:Ue=>Mi({type:On.IncrementalSnapshot,data:{source:un.StyleSheetRule,...Ue}}),styleDeclarationCb:Ue=>Mi({type:On.IncrementalSnapshot,data:{source:un.StyleDeclaration,...Ue}}),canvasMutationCb:Z,fontCb:Ue=>Mi({type:On.IncrementalSnapshot,data:{source:un.Font,...Ue}}),selectionCb:Ue=>{Mi({type:On.IncrementalSnapshot,data:{source:un.Selection,...Ue}})},customElementCb:Ue=>{Mi({type:On.IncrementalSnapshot,data:{source:un.CustomElement,...Ue}})},blockClass:i,ignoreClass:o,ignoreSelector:u,maskAllText:c,maskTextClass:d,unmaskTextClass:f,maskTextSelector:p,unmaskTextSelector:m,maskInputOptions:K,inlineStylesheet:y,sampling:A,recordDOM:$,recordCanvas:O,inlineImages:D,userTriggeredOnInput:z,collectFonts:F,doc:Oe,maskAttributeFn:S,maskInputFn:w,maskTextFn:T,keepIframeSrcFn:q,blockSelector:a,unblockSelector:s,slimDOMOptions:Q,dataURLOptions:I,mirror:su,iframeManager:se,stylesheetManager:J,shadowDomManager:ye,processedNodeManager:ie,canvasManager:he,ignoreCSSAttributes:X,plugins:LC([W,"optionalAccess",Ue=>Ue.filter,"call",Ue=>Ue(Me=>Me.observer),"optionalAccess",Ue=>Ue.map,"call",Ue=>Ue(Me=>({observer:Me.observer,options:Me.options,callback:be=>Mi({type:On.Plugin,data:{plugin:Me.name,payload:be}})}))])||[]},{});se.addLoadListener(Oe=>{try{ce.push(Te(Oe.contentDocument))}catch(Ue){console.warn(Ue)}});const we=()=>{Ne(),ce.push(Te(document))};return document.readyState==="interactive"||document.readyState==="complete"?we():(ce.push(Hs("DOMContentLoaded",()=>{Mi({type:On.DomContentLoaded,data:{}}),U==="DOMContentLoaded"&&we()})),ce.push(Hs("load",()=>{Mi({type:On.Load,data:{}}),U==="load"&&we()},window))),()=>{ce.forEach(Oe=>Oe()),ie.destroy(),oO=void 0,pun()}}catch(ce){console.warn(ce)}}function Oun(e){if(!oO)throw new Error("please take full snapshot after start recording");oO(e)}Jd.mirror=su;Jd.takeFullSnapshot=Oun;function Run(e,t){try{return e?e(t):new B0e}catch{return console.warn("Unable to initialize CanvasManager"),new B0e}}const Pun=3,$un=5;function wY(e){return e>9999999999?e:e*1e3}function V8(e){return e>9999999999?e/1e3:e}function Rk(e,t){t.category!=="sentry.transaction"&&(["ui.click","ui.input"].includes(t.category)?e.triggerUserActivity():e.checkAndHandleExpiredSession(),e.addUpdate(()=>(e.throttledAddEvent({type:On.Custom,timestamp:(t.timestamp||0)*1e3,data:{tag:"breadcrumb",payload:cu(t,10,1e3)}}),t.category==="console")))}const Mun="button,a";function yze(e){return e.closest(Mun)||e}function xze(e){const t=bze(e);return!t||!(t instanceof Element)?t:yze(t)}function bze(e){return Dun(e)?e.target:e}function Dun(e){return typeof e=="object"&&!!e&&"target"in e}let mp;function Lun(e){return mp||(mp=[],zun()),mp.push(e),()=>{const t=mp?mp.indexOf(e):-1;t>-1&&mp.splice(t,1)}}function zun(){bo(ni,"open",function(e){return function(...t){if(mp)try{mp.forEach(n=>n())}catch{}return e.apply(ni,t)}})}const Uun=new Set([un.Mutation,un.StyleSheetRule,un.StyleDeclaration,un.AdoptedStyleSheet,un.CanvasMutation,un.Selection,un.MediaInteraction]);function Fun(e,t,n){e.handleClick(t,n)}class Bun{constructor(t,n,r=Rk){this._lastMutation=0,this._lastScroll=0,this._clicks=[],this._timeout=n.timeout/1e3,this._threshold=n.threshold/1e3,this._scrollTimeout=n.scrollTimeout/1e3,this._replay=t,this._ignoreSelector=n.ignoreSelector,this._addBreadcrumbEvent=r}addListeners(){const t=Lun(()=>{this._lastMutation=q0e()});this._teardown=()=>{t(),this._clicks=[],this._lastMutation=0,this._lastScroll=0}}removeListeners(){this._teardown&&this._teardown(),this._checkClickTimeout&&clearTimeout(this._checkClickTimeout)}handleClick(t,n){if(Hun(n,this._ignoreSelector)||!Vun(t))return;const r={timestamp:V8(t.timestamp),clickBreadcrumb:t,clickCount:0,node:n};this._clicks.some(i=>i.node===r.node&&Math.abs(i.timestamp-r.timestamp)<1)||(this._clicks.push(r),this._clicks.length===1&&this._scheduleCheckClicks())}registerMutation(t=Date.now()){this._lastMutation=V8(t)}registerScroll(t=Date.now()){this._lastScroll=V8(t)}registerClick(t){const n=yze(t);this._handleMultiClick(n)}_handleMultiClick(t){this._getClicks(t).forEach(n=>{n.clickCount++})}_getClicks(t){return this._clicks.filter(n=>n.node===t)}_checkClicks(){const t=[],n=q0e();this._clicks.forEach(r=>{!r.mutationAfter&&this._lastMutation&&(r.mutationAfter=r.timestamp<=this._lastMutation?this._lastMutation-r.timestamp:void 0),!r.scrollAfter&&this._lastScroll&&(r.scrollAfter=r.timestamp<=this._lastScroll?this._lastScroll-r.timestamp:void 0),r.timestamp+this._timeout<=n&&t.push(r)});for(const r of t){const i=this._clicks.indexOf(r);i>-1&&(this._generateBreadcrumbs(r),this._clicks.splice(i,1))}this._clicks.length&&this._scheduleCheckClicks()}_generateBreadcrumbs(t){const n=this._replay,r=t.scrollAfter&&t.scrollAfter<=this._scrollTimeout,i=t.mutationAfter&&t.mutationAfter<=this._threshold,a=!r&&!i,{clickCount:s,clickBreadcrumb:o}=t;if(a){const u=Math.min(t.mutationAfter||this._timeout,this._timeout)*1e3,c=u<this._timeout*1e3?"mutation":"timeout",d={type:"default",message:o.message,timestamp:o.timestamp,category:"ui.slowClickDetected",data:{...o.data,url:ni.location.href,route:n.getCurrentRoute(),timeAfterClickMs:u,endReason:c,clickCount:s||1}};this._addBreadcrumbEvent(n,d);return}if(s>1){const u={type:"default",message:o.message,timestamp:o.timestamp,category:"ui.multiClick",data:{...o.data,url:ni.location.href,route:n.getCurrentRoute(),clickCount:s,metric:!0}};this._addBreadcrumbEvent(n,u)}}_scheduleCheckClicks(){this._checkClickTimeout&&clearTimeout(this._checkClickTimeout),this._checkClickTimeout=dx(()=>this._checkClicks(),1e3)}}const qun=["A","BUTTON","INPUT"];function Hun(e,t){return!!(!qun.includes(e.tagName)||e.tagName==="INPUT"&&!["submit","button"].includes(e.getAttribute("type")||"")||e.tagName==="A"&&(e.hasAttribute("download")||e.hasAttribute("target")&&e.getAttribute("target")!=="_self")||t&&e.matches(t))}function Vun(e){return!!(e.data&&typeof e.data.nodeId=="number"&&e.timestamp)}function q0e(){return Date.now()/1e3}function Gun(e,t){try{if(!Wun(t))return;const{source:n}=t.data;if(Uun.has(n)&&e.registerMutation(t.timestamp),n===un.Scroll&&e.registerScroll(t.timestamp),Kun(t)){const{type:r,id:i}=t.data,a=Jd.mirror.getNode(i);a instanceof HTMLElement&&r===Fs.Click&&e.registerClick(a)}}catch{}}function Wun(e){return e.type===Pun}function Kun(e){return e.data.source===un.MouseInteraction}function bc(e){return{timestamp:Date.now()/1e3,type:"default",...e}}var lO;(function(e){e[e.Document=0]="Document",e[e.DocumentType=1]="DocumentType",e[e.Element=2]="Element",e[e.Text=3]="Text",e[e.CDATA=4]="CDATA",e[e.Comment=5]="Comment"})(lO||(lO={}));const Zun=new Set(["id","class","aria-label","role","name","alt","title","data-test-id","data-testid","disabled","aria-disabled","data-sentry-component"]);function Yun(e){const t={};!e["data-sentry-component"]&&e["data-sentry-element"]&&(e["data-sentry-component"]=e["data-sentry-element"]);for(const n in e)if(Zun.has(n)){let r=n;(n==="data-testid"||n==="data-test-id")&&(r="testId"),t[r]=e[n]}return t}const Xun=e=>t=>{if(!e.isEnabled())return;const n=Jun(t);if(!n)return;const r=t.name==="click",i=r?t.event:void 0;r&&e.clickDetector&&i&&i.target&&!i.altKey&&!i.metaKey&&!i.ctrlKey&&!i.shiftKey&&Fun(e.clickDetector,n,xze(t.event)),Rk(e,n)};function _ze(e,t){const n=Jd.mirror.getId(e),r=n&&Jd.mirror.getNode(n),i=r&&Jd.mirror.getMeta(r),a=i&&ecn(i)?i:null;return{message:t,data:a?{nodeId:n,node:{id:n,tagName:a.tagName,textContent:Array.from(a.childNodes).map(s=>s.type===lO.Text&&s.textContent).filter(Boolean).map(s=>s.trim()).join(""),attributes:Yun(a.attributes)}}:{}}}function Jun(e){const{target:t,message:n}=Qun(e);return bc({category:`ui.${e.name}`,..._ze(t,n)})}function Qun(e){const t=e.name==="click";let n,r=null;try{r=t?xze(e.event):bze(e.event),n=cf(r,{maxStringLength:200})||"<unknown>"}catch{n="<unknown>"}return{target:r,message:n}}function ecn(e){return e.type===lO.Element}function tcn(e,t){if(!e.isEnabled())return;e.updateUserActivity();const n=ncn(t);n&&Rk(e,n)}function ncn(e){const{metaKey:t,shiftKey:n,ctrlKey:r,altKey:i,key:a,target:s}=e;if(!s||rcn(s)||!a)return null;const o=t||r||i,u=a.length===1;if(!o&&u)return null;const c=cf(s,{maxStringLength:200})||"<unknown>",d=_ze(s,c);return bc({category:"ui.keyDown",message:c,data:{...d.data,metaKey:t,shiftKey:n,ctrlKey:r,altKey:i,key:a}})}function rcn(e){return e.tagName==="INPUT"||e.tagName==="TEXTAREA"||e.isContentEditable}const icn={resource:ucn,paint:ocn,navigation:lcn};function rC(e,t){return({metric:n})=>void t.replayPerformanceEntries.push(e(n))}function acn(e){return e.map(scn).filter(Boolean)}function scn(e){const t=icn[e.entryType];return t?t(e):null}function hx(e){return((to||ni.performance.timeOrigin)+e)/1e3}function ocn(e){const{duration:t,entryType:n,name:r,startTime:i}=e,a=hx(i);return{type:n,name:r,start:a,end:a+t,data:void 0}}function lcn(e){const{entryType:t,name:n,decodedBodySize:r,duration:i,domComplete:a,encodedBodySize:s,domContentLoadedEventStart:o,domContentLoadedEventEnd:u,domInteractive:c,loadEventStart:d,loadEventEnd:f,redirectCount:p,startTime:m,transferSize:y,type:v}=e;return i===0?null:{type:`${t}.${v}`,start:hx(m),end:hx(a),name:n,data:{size:y,decodedBodySize:r,encodedBodySize:s,duration:i,domInteractive:c,domContentLoadedEventStart:o,domContentLoadedEventEnd:u,loadEventStart:d,loadEventEnd:f,domComplete:a,redirectCount:p}}}function ucn(e){const{entryType:t,initiatorType:n,name:r,responseEnd:i,startTime:a,decodedBodySize:s,encodedBodySize:o,responseStatus:u,transferSize:c}=e;return["fetch","xmlhttprequest"].includes(n)?null:{type:`${t}.${n}`,start:hx(a),end:hx(i),name:r,data:{size:c,statusCode:u,decodedBodySize:s,encodedBodySize:o}}}function ccn(e){const t=e.entries[e.entries.length-1],n=t&&t.element?[t.element]:void 0;return n4(e,"largest-contentful-paint",n)}function dcn(e){return e.sources!==void 0}function fcn(e){const t=[],n=[];for(const r of e.entries)if(dcn(r)){const i=[];for(const a of r.sources)if(a.node){n.push(a.node);const s=Jd.mirror.getId(a.node);s&&i.push(s)}t.push({value:r.value,nodeIds:i.length?i:void 0})}return n4(e,"cumulative-layout-shift",n,t)}function pcn(e){const t=e.entries[e.entries.length-1],n=t&&t.target?[t.target]:void 0;return n4(e,"first-input-delay",n)}function hcn(e){const t=e.entries[e.entries.length-1],n=t&&t.target?[t.target]:void 0;return n4(e,"interaction-to-next-paint",n)}function n4(e,t,n,r){const i=e.value,a=e.rating,s=hx(i);return{type:"web-vital",name:t,start:s,end:s,data:{value:i,size:i,rating:a,nodeIds:n?n.map(o=>Jd.mirror.getId(o)):void 0,attributions:r}}}function mcn(e){function t(i){e.performanceEntries.includes(i)||e.performanceEntries.push(i)}function n({entries:i}){i.forEach(t)}const r=[];return["navigation","paint","resource"].forEach(i=>{r.push(cx(i,n))}),r.push(LLe(rC(ccn,e)),fY(rC(fcn,e)),zLe(rC(pcn,e)),ULe(rC(hcn,e))),()=>{r.forEach(i=>i())}}const tn=typeof __SENTRY_DEBUG__>"u"||__SENTRY_DEBUG__,gcn='var t=Uint8Array,n=Uint16Array,r=Int32Array,e=new t([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0,0,0,0]),i=new t([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13,0,0]),a=new t([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),s=function(t,e){for(var i=new n(31),a=0;a<31;++a)i[a]=e+=1<<t[a-1];var s=new r(i[30]);for(a=1;a<30;++a)for(var o=i[a];o<i[a+1];++o)s[o]=o-i[a]<<5|a;return{b:i,r:s}},o=s(e,2),f=o.b,h=o.r;f[28]=258,h[258]=28;for(var l=s(i,0).r,u=new n(32768),c=0;c<32768;++c){var v=(43690&c)>>1|(21845&c)<<1;v=(61680&(v=(52428&v)>>2|(13107&v)<<2))>>4|(3855&v)<<4,u[c]=((65280&v)>>8|(255&v)<<8)>>1}var d=function(t,r,e){for(var i=t.length,a=0,s=new n(r);a<i;++a)t[a]&&++s[t[a]-1];var o,f=new n(r);for(a=1;a<r;++a)f[a]=f[a-1]+s[a-1]<<1;if(e){o=new n(1<<r);var h=15-r;for(a=0;a<i;++a)if(t[a])for(var l=a<<4|t[a],c=r-t[a],v=f[t[a]-1]++<<c,d=v|(1<<c)-1;v<=d;++v)o[u[v]>>h]=l}else for(o=new n(i),a=0;a<i;++a)t[a]&&(o[a]=u[f[t[a]-1]++]>>15-t[a]);return o},g=new t(288);for(c=0;c<144;++c)g[c]=8;for(c=144;c<256;++c)g[c]=9;for(c=256;c<280;++c)g[c]=7;for(c=280;c<288;++c)g[c]=8;var w=new t(32);for(c=0;c<32;++c)w[c]=5;var p=d(g,9,0),y=d(w,5,0),m=function(t){return(t+7)/8|0},b=function(n,r,e){return(null==e||e>n.length)&&(e=n.length),new t(n.subarray(r,e))},M=["unexpected EOF","invalid block type","invalid length/literal","invalid distance","stream finished","no stream handler",,"no callback","invalid UTF-8 data","extra field too long","date not in range 1980-2099","filename too long","stream finishing","invalid zip data"],E=function(t,n,r){var e=new Error(n||M[t]);if(e.code=t,Error.captureStackTrace&&Error.captureStackTrace(e,E),!r)throw e;return e},z=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8},_=function(t,n,r){r<<=7&n;var e=n/8|0;t[e]|=r,t[e+1]|=r>>8,t[e+2]|=r>>16},x=function(r,e){for(var i=[],a=0;a<r.length;++a)r[a]&&i.push({s:a,f:r[a]});var s=i.length,o=i.slice();if(!s)return{t:F,l:0};if(1==s){var f=new t(i[0].s+1);return f[i[0].s]=1,{t:f,l:1}}i.sort((function(t,n){return t.f-n.f})),i.push({s:-1,f:25001});var h=i[0],l=i[1],u=0,c=1,v=2;for(i[0]={s:-1,f:h.f+l.f,l:h,r:l};c!=s-1;)h=i[i[u].f<i[v].f?u++:v++],l=i[u!=c&&i[u].f<i[v].f?u++:v++],i[c++]={s:-1,f:h.f+l.f,l:h,r:l};var d=o[0].s;for(a=1;a<s;++a)o[a].s>d&&(d=o[a].s);var g=new n(d+1),w=A(i[c-1],g,0);if(w>e){a=0;var p=0,y=w-e,m=1<<y;for(o.sort((function(t,n){return g[n.s]-g[t.s]||t.f-n.f}));a<s;++a){var b=o[a].s;if(!(g[b]>e))break;p+=m-(1<<w-g[b]),g[b]=e}for(p>>=y;p>0;){var M=o[a].s;g[M]<e?p-=1<<e-g[M]++-1:++a}for(;a>=0&&p;--a){var E=o[a].s;g[E]==e&&(--g[E],++p)}w=e}return{t:new t(g),l:w}},A=function(t,n,r){return-1==t.s?Math.max(A(t.l,n,r+1),A(t.r,n,r+1)):n[t.s]=r},D=function(t){for(var r=t.length;r&&!t[--r];);for(var e=new n(++r),i=0,a=t[0],s=1,o=function(t){e[i++]=t},f=1;f<=r;++f)if(t[f]==a&&f!=r)++s;else{if(!a&&s>2){for(;s>138;s-=138)o(32754);s>2&&(o(s>10?s-11<<5|28690:s-3<<5|12305),s=0)}else if(s>3){for(o(a),--s;s>6;s-=6)o(8304);s>2&&(o(s-3<<5|8208),s=0)}for(;s--;)o(a);s=1,a=t[f]}return{c:e.subarray(0,i),n:r}},T=function(t,n){for(var r=0,e=0;e<n.length;++e)r+=t[e]*n[e];return r},k=function(t,n,r){var e=r.length,i=m(n+2);t[i]=255&e,t[i+1]=e>>8,t[i+2]=255^t[i],t[i+3]=255^t[i+1];for(var a=0;a<e;++a)t[i+a+4]=r[a];return 8*(i+4+e)},U=function(t,r,s,o,f,h,l,u,c,v,m){z(r,m++,s),++f[256];for(var b=x(f,15),M=b.t,E=b.l,A=x(h,15),U=A.t,C=A.l,F=D(M),I=F.c,S=F.n,L=D(U),O=L.c,j=L.n,q=new n(19),B=0;B<I.length;++B)++q[31&I[B]];for(B=0;B<O.length;++B)++q[31&O[B]];for(var G=x(q,7),H=G.t,J=G.l,K=19;K>4&&!H[a[K-1]];--K);var N,P,Q,R,V=v+5<<3,W=T(f,g)+T(h,w)+l,X=T(f,M)+T(h,U)+l+14+3*K+T(q,H)+2*q[16]+3*q[17]+7*q[18];if(c>=0&&V<=W&&V<=X)return k(r,m,t.subarray(c,c+v));if(z(r,m,1+(X<W)),m+=2,X<W){N=d(M,E,0),P=M,Q=d(U,C,0),R=U;var Y=d(H,J,0);z(r,m,S-257),z(r,m+5,j-1),z(r,m+10,K-4),m+=14;for(B=0;B<K;++B)z(r,m+3*B,H[a[B]]);m+=3*K;for(var Z=[I,O],$=0;$<2;++$){var tt=Z[$];for(B=0;B<tt.length;++B){var nt=31&tt[B];z(r,m,Y[nt]),m+=H[nt],nt>15&&(z(r,m,tt[B]>>5&127),m+=tt[B]>>12)}}}else N=p,P=g,Q=y,R=w;for(B=0;B<u;++B){var rt=o[B];if(rt>255){_(r,m,N[(nt=rt>>18&31)+257]),m+=P[nt+257],nt>7&&(z(r,m,rt>>23&31),m+=e[nt]);var et=31&rt;_(r,m,Q[et]),m+=R[et],et>3&&(_(r,m,rt>>5&8191),m+=i[et])}else _(r,m,N[rt]),m+=P[rt]}return _(r,m,N[256]),m+P[256]},C=new r([65540,131080,131088,131104,262176,1048704,1048832,2114560,2117632]),F=new t(0),I=function(){for(var t=new Int32Array(256),n=0;n<256;++n){for(var r=n,e=9;--e;)r=(1&r&&-306674912)^r>>>1;t[n]=r}return t}(),S=function(){var t=-1;return{p:function(n){for(var r=t,e=0;e<n.length;++e)r=I[255&r^n[e]]^r>>>8;t=r},d:function(){return~t}}},L=function(){var t=1,n=0;return{p:function(r){for(var e=t,i=n,a=0|r.length,s=0;s!=a;){for(var o=Math.min(s+2655,a);s<o;++s)i+=e+=r[s];e=(65535&e)+15*(e>>16),i=(65535&i)+15*(i>>16)}t=e,n=i},d:function(){return(255&(t%=65521))<<24|(65280&t)<<8|(255&(n%=65521))<<8|n>>8}}},O=function(a,s,o,f,u){if(!u&&(u={l:1},s.dictionary)){var c=s.dictionary.subarray(-32768),v=new t(c.length+a.length);v.set(c),v.set(a,c.length),a=v,u.w=c.length}return function(a,s,o,f,u,c){var v=c.z||a.length,d=new t(f+v+5*(1+Math.ceil(v/7e3))+u),g=d.subarray(f,d.length-u),w=c.l,p=7&(c.r||0);if(s){p&&(g[0]=c.r>>3);for(var y=C[s-1],M=y>>13,E=8191&y,z=(1<<o)-1,_=c.p||new n(32768),x=c.h||new n(z+1),A=Math.ceil(o/3),D=2*A,T=function(t){return(a[t]^a[t+1]<<A^a[t+2]<<D)&z},F=new r(25e3),I=new n(288),S=new n(32),L=0,O=0,j=c.i||0,q=0,B=c.w||0,G=0;j+2<v;++j){var H=T(j),J=32767&j,K=x[H];if(_[J]=K,x[H]=J,B<=j){var N=v-j;if((L>7e3||q>24576)&&(N>423||!w)){p=U(a,g,0,F,I,S,O,q,G,j-G,p),q=L=O=0,G=j;for(var P=0;P<286;++P)I[P]=0;for(P=0;P<30;++P)S[P]=0}var Q=2,R=0,V=E,W=J-K&32767;if(N>2&&H==T(j-W))for(var X=Math.min(M,N)-1,Y=Math.min(32767,j),Z=Math.min(258,N);W<=Y&&--V&&J!=K;){if(a[j+Q]==a[j+Q-W]){for(var $=0;$<Z&&a[j+$]==a[j+$-W];++$);if($>Q){if(Q=$,R=W,$>X)break;var tt=Math.min(W,$-2),nt=0;for(P=0;P<tt;++P){var rt=j-W+P&32767,et=rt-_[rt]&32767;et>nt&&(nt=et,K=rt)}}}W+=(J=K)-(K=_[J])&32767}if(R){F[q++]=268435456|h[Q]<<18|l[R];var it=31&h[Q],at=31&l[R];O+=e[it]+i[at],++I[257+it],++S[at],B=j+Q,++L}else F[q++]=a[j],++I[a[j]]}}for(j=Math.max(j,B);j<v;++j)F[q++]=a[j],++I[a[j]];p=U(a,g,w,F,I,S,O,q,G,j-G,p),w||(c.r=7&p|g[p/8|0]<<3,p-=7,c.h=x,c.p=_,c.i=j,c.w=B)}else{for(j=c.w||0;j<v+w;j+=65535){var st=j+65535;st>=v&&(g[p/8|0]=w,st=v),p=k(g,p+1,a.subarray(j,st))}c.i=v}return b(d,0,f+m(p)+u)}(a,null==s.level?6:s.level,null==s.mem?Math.ceil(1.5*Math.max(8,Math.min(13,Math.log(a.length)))):12+s.mem,o,f,u)},j=function(t,n,r){for(;r;++n)t[n]=r,r>>>=8},q=function(t,n){var r=n.filename;if(t[0]=31,t[1]=139,t[2]=8,t[8]=n.level<2?4:9==n.level?2:0,t[9]=3,0!=n.mtime&&j(t,4,Math.floor(new Date(n.mtime||Date.now())/1e3)),r){t[3]=8;for(var e=0;e<=r.length;++e)t[e+10]=r.charCodeAt(e)}},B=function(t){return 10+(t.filename?t.filename.length+1:0)},G=function(){function n(n,r){if("function"==typeof n&&(r=n,n={}),this.ondata=r,this.o=n||{},this.s={l:0,i:32768,w:32768,z:32768},this.b=new t(98304),this.o.dictionary){var e=this.o.dictionary.subarray(-32768);this.b.set(e,32768-e.length),this.s.i=32768-e.length}}return n.prototype.p=function(t,n){this.ondata(O(t,this.o,0,0,this.s),n)},n.prototype.push=function(n,r){this.ondata||E(5),this.s.l&&E(4);var e=n.length+this.s.z;if(e>this.b.length){if(e>2*this.b.length-32768){var i=new t(-32768&e);i.set(this.b.subarray(0,this.s.z)),this.b=i}var a=this.b.length-this.s.z;a&&(this.b.set(n.subarray(0,a),this.s.z),this.s.z=this.b.length,this.p(this.b,!1)),this.b.set(this.b.subarray(-32768)),this.b.set(n.subarray(a),32768),this.s.z=n.length-a+32768,this.s.i=32766,this.s.w=32768}else this.b.set(n,this.s.z),this.s.z+=n.length;this.s.l=1&r,(this.s.z>this.s.w+8191||r)&&(this.p(this.b,r||!1),this.s.w=this.s.i,this.s.i-=2)},n}();var H=function(){function t(t,n){this.c=L(),this.v=1,G.call(this,t,n)}return t.prototype.push=function(t,n){this.c.p(t),G.prototype.push.call(this,t,n)},t.prototype.p=function(t,n){var r=O(t,this.o,this.v&&(this.o.dictionary?6:2),n&&4,this.s);this.v&&(function(t,n){var r=n.level,e=0==r?0:r<6?1:9==r?3:2;if(t[0]=120,t[1]=e<<6|(n.dictionary&&32),t[1]|=31-(t[0]<<8|t[1])%31,n.dictionary){var i=L();i.p(n.dictionary),j(t,2,i.d())}}(r,this.o),this.v=0),n&&j(r,r.length-4,this.c.d()),this.ondata(r,n)},t}(),J="undefined"!=typeof TextEncoder&&new TextEncoder,K="undefined"!=typeof TextDecoder&&new TextDecoder;try{K.decode(F,{stream:!0})}catch(t){}var N=function(){function t(t){this.ondata=t}return t.prototype.push=function(t,n){this.ondata||E(5),this.d&&E(4),this.ondata(P(t),this.d=n||!1)},t}();function P(n,r){if(J)return J.encode(n);for(var e=n.length,i=new t(n.length+(n.length>>1)),a=0,s=function(t){i[a++]=t},o=0;o<e;++o){if(a+5>i.length){var f=new t(a+8+(e-o<<1));f.set(i),i=f}var h=n.charCodeAt(o);h<128||r?s(h):h<2048?(s(192|h>>6),s(128|63&h)):h>55295&&h<57344?(s(240|(h=65536+(1047552&h)|1023&n.charCodeAt(++o))>>18),s(128|h>>12&63),s(128|h>>6&63),s(128|63&h)):(s(224|h>>12),s(128|h>>6&63),s(128|63&h))}return b(i,0,a)}function Q(t){return function(t,n){n||(n={});var r=S(),e=t.length;r.p(t);var i=O(t,n,B(n),8),a=i.length;return q(i,n),j(i,a-8,r.d()),j(i,a-4,e),i}(P(t))}const R=new class{constructor(){this._init()}clear(){this._init()}addEvent(t){if(!t)throw new Error("Adding invalid event");const n=this._hasEvents?",":"";this.stream.push(n+t),this._hasEvents=!0}finish(){this.stream.push("]",!0);const t=function(t){let n=0;for(const r of t)n+=r.length;const r=new Uint8Array(n);for(let n=0,e=0,i=t.length;n<i;n++){const i=t[n];r.set(i,e),e+=i.length}return r}(this._deflatedData);return this._init(),t}_init(){this._hasEvents=!1,this._deflatedData=[],this.deflate=new H,this.deflate.ondata=(t,n)=>{this._deflatedData.push(t)},this.stream=new N(((t,n)=>{this.deflate.push(t,n)})),this.stream.push("[")}},V={clear:()=>{R.clear()},addEvent:t=>R.addEvent(t),finish:()=>R.finish(),compress:t=>Q(t)};addEventListener("message",(function(t){const n=t.data.method,r=t.data.id,e=t.data.arg;if(n in V&&"function"==typeof V[n])try{const t=V[n](e);postMessage({id:r,method:n,success:!0,response:t})}catch(t){postMessage({id:r,method:n,success:!1,response:t.message}),console.error(t)}})),postMessage({id:void 0,method:"init",success:!0,response:void 0});';function vcn(){const e=new Blob([gcn]);return URL.createObjectURL(e)}const H0e=["info","warn","error","log"],FC="[Replay] ";function G8(e,t="info"){Jp({category:"console",data:{logger:"replay"},level:t,message:`${FC}${e}`},{level:t})}function ycn(){let e=!1,t=!1;const n={exception:()=>{},infoTick:()=>{},setConfig:r=>{e=r.captureExceptions,t=r.traceInternals}};return tn?(H0e.forEach(r=>{n[r]=(...i)=>{bt[r](FC,...i),t&&G8(i.join(""),wLe(r))}}),n.exception=(r,...i)=>{i.length&&n.error&&n.error(...i),bt.error(FC,r),e?cLe(r):t&&G8(r,"error")},n.infoTick=(...r)=>{bt.info(FC,...r),t&&setTimeout(()=>G8(r[0]),0)}):H0e.forEach(r=>{n[r]=()=>{}}),n}const on=ycn();class SY extends Error{constructor(){super(`Event buffer exceeded maximum size of ${gY}.`)}}class wze{constructor(){this.events=[],this._totalSize=0,this.hasCheckout=!1,this.waitForCheckout=!1}get hasEvents(){return this.events.length>0}get type(){return"sync"}destroy(){this.events=[]}async addEvent(t){const n=JSON.stringify(t).length;if(this._totalSize+=n,this._totalSize>gY)throw new SY;this.events.push(t)}finish(){return new Promise(t=>{const n=this.events;this.clear(),t(JSON.stringify(n))})}clear(){this.events=[],this._totalSize=0,this.hasCheckout=!1}getEarliestTimestamp(){const t=this.events.map(n=>n.timestamp).sort()[0];return t?wY(t):null}}class xcn{constructor(t){this._worker=t,this._id=0}ensureReady(){return this._ensureReadyPromise?this._ensureReadyPromise:(this._ensureReadyPromise=new Promise((t,n)=>{this._worker.addEventListener("message",({data:r})=>{r.success?t():n()},{once:!0}),this._worker.addEventListener("error",r=>{n(r)},{once:!0})}),this._ensureReadyPromise)}destroy(){tn&&on.info("Destroying compression worker"),this._worker.terminate()}postMessage(t,n){const r=this._getAndIncrementId();return new Promise((i,a)=>{const s=({data:o})=>{const u=o;if(u.method===t&&u.id===r){if(this._worker.removeEventListener("message",s),!u.success){tn&&on.error("Error in compression worker: ",u.response),a(new Error("Error in compression worker"));return}i(u.response)}};this._worker.addEventListener("message",s),this._worker.postMessage({id:r,method:t,arg:n})})}_getAndIncrementId(){return this._id++}}class bcn{constructor(t){this._worker=new xcn(t),this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1,this.waitForCheckout=!1}get hasEvents(){return!!this._earliestTimestamp}get type(){return"worker"}ensureReady(){return this._worker.ensureReady()}destroy(){this._worker.destroy()}addEvent(t){const n=wY(t.timestamp);(!this._earliestTimestamp||n<this._earliestTimestamp)&&(this._earliestTimestamp=n);const r=JSON.stringify(t);return this._totalSize+=r.length,this._totalSize>gY?Promise.reject(new SY):this._sendEventToWorker(r)}finish(){return this._finishRequest()}clear(){this._earliestTimestamp=null,this._totalSize=0,this.hasCheckout=!1,this._worker.postMessage("clear").then(null,t=>{tn&&on.exception(t,'Sending "clear" message to worker failed',t)})}getEarliestTimestamp(){return this._earliestTimestamp}_sendEventToWorker(t){return this._worker.postMessage("addEvent",t)}async _finishRequest(){const t=await this._worker.postMessage("finish");return this._earliestTimestamp=null,this._totalSize=0,t}}class _cn{constructor(t){this._fallback=new wze,this._compression=new bcn(t),this._used=this._fallback,this._ensureWorkerIsLoadedPromise=this._ensureWorkerIsLoaded()}get waitForCheckout(){return this._used.waitForCheckout}get type(){return this._used.type}get hasEvents(){return this._used.hasEvents}get hasCheckout(){return this._used.hasCheckout}set hasCheckout(t){this._used.hasCheckout=t}set waitForCheckout(t){this._used.waitForCheckout=t}destroy(){this._fallback.destroy(),this._compression.destroy()}clear(){return this._used.clear()}getEarliestTimestamp(){return this._used.getEarliestTimestamp()}addEvent(t){return this._used.addEvent(t)}async finish(){return await this.ensureWorkerIsLoaded(),this._used.finish()}ensureWorkerIsLoaded(){return this._ensureWorkerIsLoadedPromise}async _ensureWorkerIsLoaded(){try{await this._compression.ensureReady()}catch(t){tn&&on.exception(t,"Failed to load the compression worker, falling back to simple buffer");return}await this._switchToCompressionWorker()}async _switchToCompressionWorker(){const{events:t,hasCheckout:n,waitForCheckout:r}=this._fallback,i=[];for(const a of t)i.push(this._compression.addEvent(a));this._compression.hasCheckout=n,this._compression.waitForCheckout=r,this._used=this._compression;try{await Promise.all(i),this._fallback.clear()}catch(a){tn&&on.exception(a,"Failed to add events when switching buffers.")}}}function wcn({useCompression:e,workerUrl:t}){if(e&&window.Worker){const n=Scn(t);if(n)return n}return tn&&on.info("Using simple buffer"),new wze}function Scn(e){try{const t=e||kcn();if(!t)return;tn&&on.info(`Using compression worker${e?` from ${e}`:""}`);const n=new Worker(t);return new _cn(n)}catch(t){tn&&on.exception(t,"Failed to create compression worker")}}function kcn(){return typeof __SENTRY_EXCLUDE_REPLAY_WORKER__>"u"||!__SENTRY_EXCLUDE_REPLAY_WORKER__?vcn():""}function kY(){try{return"sessionStorage"in ni&&!!ni.sessionStorage}catch{return!1}}function Ecn(e){Tcn(),e.session=void 0}function Tcn(){if(kY())try{ni.sessionStorage.removeItem(hY)}catch{}}function Sze(e){return e===void 0?!1:Math.random()<e}function kze(e){const t=Date.now(),n=e.id||el(),r=e.started||t,i=e.lastActivity||t,a=e.segmentId||0,s=e.sampled,o=e.previousSessionId;return{id:n,started:r,lastActivity:i,segmentId:a,sampled:s,previousSessionId:o}}function EY(e){if(kY())try{ni.sessionStorage.setItem(hY,JSON.stringify(e))}catch{}}function Ncn(e,t){return Sze(e)?"session":t?"buffer":!1}function V0e({sessionSampleRate:e,allowBuffering:t,stickySession:n=!1},{previousSessionId:r}={}){const i=Ncn(e,t),a=kze({sampled:i,previousSessionId:r});return n&&EY(a),a}function Ccn(){if(!kY())return null;try{const e=ni.sessionStorage.getItem(hY);if(!e)return null;const t=JSON.parse(e);return tn&&on.infoTick("Loading existing session"),kze(t)}catch{return null}}function I9(e,t,n=+new Date){return e===null||t===void 0||t<0?!0:t===0?!1:e+t<=n}function Eze(e,{maxReplayDuration:t,sessionIdleExpire:n,targetTime:r=Date.now()}){return I9(e.started,t,r)||I9(e.lastActivity,n,r)}function Tze(e,{sessionIdleExpire:t,maxReplayDuration:n}){return!(!Eze(e,{sessionIdleExpire:t,maxReplayDuration:n})||e.sampled==="buffer"&&e.segmentId===0)}function W8({sessionIdleExpire:e,maxReplayDuration:t,previousSessionId:n},r){const i=r.stickySession&&Ccn();return i?Tze(i,{sessionIdleExpire:e,maxReplayDuration:t})?(tn&&on.infoTick("Session in sessionStorage is expired, creating new one..."),V0e(r,{previousSessionId:i.id})):i:(tn&&on.infoTick("Creating new session"),V0e(r,{previousSessionId:n}))}function Acn(e){return e.type===On.Custom}function TY(e,t,n){return Cze(e,t)?(Nze(e,t,n),!0):!1}function Icn(e,t,n){return Cze(e,t)?Nze(e,t,n):Promise.resolve(null)}async function Nze(e,t,n){const{eventBuffer:r}=e;if(!r||r.waitForCheckout&&!n)return null;const i=e.recordingMode==="buffer";try{n&&i&&r.clear(),n&&(r.hasCheckout=!0,r.waitForCheckout=!1);const a=e.getOptions(),s=jcn(t,a.beforeAddRecordingEvent);return s?await r.addEvent(s):void 0}catch(a){const s=a&&a instanceof SY,o=s?"addEventSizeExceeded":"addEvent";if(s&&i)return r.clear(),r.waitForCheckout=!0,null;e.handleException(a),await e.stop({reason:o});const u=Xn();u&&u.recordDroppedEvent("internal_sdk_error","replay")}}function Cze(e,t){if(!e.eventBuffer||e.isPaused()||!e.isEnabled())return!1;const n=wY(t.timestamp);return n+e.timeouts.sessionIdlePause<Date.now()?!1:n>e.getContext().initialTimestamp+e.getOptions().maxReplayDuration?(tn&&on.infoTick(`Skipping event with timestamp ${n} because it is after maxReplayDuration`),!1):!0}function jcn(e,t){try{if(typeof t=="function"&&Acn(e))return t(e)}catch(n){return tn&&on.exception(n,"An error occurred in the `beforeAddRecordingEvent` callback, skipping the event..."),null}return e}function NY(e){return!e.type}function j9(e){return e.type==="transaction"}function Ocn(e){return e.type==="replay_event"}function G0e(e){return e.type==="feedback"}function Rcn(e){return(t,n)=>{if(!e.isEnabled()||!NY(t)&&!j9(t))return;const r=n&&n.statusCode;if(!(!r||r<200||r>=300)){if(j9(t)){Pcn(e,t);return}$cn(e,t)}}}function Pcn(e,t){const n=e.getContext();t.contexts&&t.contexts.trace&&t.contexts.trace.trace_id&&n.traceIds.size<100&&n.traceIds.add(t.contexts.trace.trace_id)}function $cn(e,t){const n=e.getContext();if(t.event_id&&n.errorIds.size<100&&n.errorIds.add(t.event_id),e.recordingMode!=="buffer"||!t.tags||!t.tags.replayId)return;const{beforeErrorSampling:r}=e.getOptions();typeof r=="function"&&!r(t)||dx(async()=>{try{await e.sendBufferedReplayOrFlush()}catch(i){e.handleException(i)}})}function Mcn(e){return t=>{!e.isEnabled()||!NY(t)||Dcn(e,t)}}function Dcn(e,t){const n=t.exception&&t.exception.values&&t.exception.values[0]&&t.exception.values[0].value;if(typeof n=="string"&&(n.match(/(reactjs\.org\/docs\/error-decoder\.html\?invariant=|react\.dev\/errors\/)(418|419|422|423|425)/)||n.match(/(does not match server-rendered HTML|Hydration failed because)/i))){const r=bc({category:"replay.hydrate-error",data:{url:P6e()}});Rk(e,r)}}function Lcn(e){const t=Xn();t&&t.on("beforeAddBreadcrumb",n=>zcn(e,n))}function zcn(e,t){if(!e.isEnabled()||!Aze(t))return;const n=Ucn(t);n&&Rk(e,n)}function Ucn(e){return!Aze(e)||["fetch","xhr","sentry.event","sentry.transaction"].includes(e.category)||e.category.startsWith("ui.")?null:e.category==="console"?Fcn(e):bc(e)}function Fcn(e){const t=e.data&&e.data.arguments;if(!Array.isArray(t)||t.length===0)return bc(e);let n=!1;const r=t.map(i=>{if(!i)return i;if(typeof i=="string")return i.length>eC?(n=!0,`${i.slice(0,eC)}…`):i;if(typeof i=="object")try{const a=cu(i,7);return JSON.stringify(a).length>eC?(n=!0,`${JSON.stringify(a,null,2).slice(0,eC)}…`):a}catch{}return i});return bc({...e,data:{...e.data,arguments:r,...n?{_meta:{warnings:["CONSOLE_ARG_TRUNCATED"]}}:{}}})}function Aze(e){return!!e.category}function Bcn(e,t){return e.type||!e.exception||!e.exception.values||!e.exception.values.length?!1:!!(t.originalException&&t.originalException.__rrweb__)}function Ize(){const e=ui().getPropagationContext().dsc;e&&delete e.replay_id;const t=Va();if(t){const n=zg(t);delete n.replay_id}}function qcn(e,t){e.triggerUserActivity(),e.addUpdate(()=>t.timestamp?(e.throttledAddEvent({type:On.Custom,timestamp:t.timestamp*1e3,data:{tag:"breadcrumb",payload:{timestamp:t.timestamp,type:"default",category:"sentry.feedback",data:{feedbackId:t.event_id}}}}),!1):!0)}function Hcn(e,t){return e.recordingMode!=="buffer"||t.message===mY||!t.exception||t.type?!1:Sze(e.getOptions().errorSampleRate)}function Vcn(e){return Object.assign((t,n)=>!e.isEnabled()||e.isPaused()?t:Ocn(t)?(delete t.breadcrumbs,t):!NY(t)&&!j9(t)&&!G0e(t)?t:e.checkAndHandleExpiredSession()?G0e(t)?(e.flush(),t.contexts.feedback.replay_id=e.getSessionId(),qcn(e,t),t):Bcn(t,n)&&!e.getOptions()._experiments.captureExceptions?(tn&&on.log("Ignoring error from rrweb internals",t),null):((Hcn(e,t)||e.recordingMode==="session")&&(t.tags={...t.tags,replayId:e.getSessionId()}),t):(Ize(),t),{id:"Replay"})}function r4(e,t){return t.map(({type:n,start:r,end:i,name:a,data:s})=>{const o=e.throttledAddEvent({type:On.Custom,timestamp:r,data:{tag:"performanceSpan",payload:{op:n,description:a,startTimestamp:r,endTimestamp:i,data:s}}});return typeof o=="string"?Promise.resolve(null):o})}function Gcn(e){const{from:t,to:n}=e,r=Date.now()/1e3;return{type:"navigation.push",start:r,end:r,name:n,data:{previous:t}}}function Wcn(e){return t=>{if(!e.isEnabled())return;const n=Gcn(t);n!==null&&(e.getContext().urls.push(n.name),e.triggerUserActivity(),e.addUpdate(()=>(r4(e,[n]),!1)))}}function Kcn(e,t){return tn&&e.getOptions()._experiments.traceInternals?!1:Gin(t,Xn())}function jze(e,t){e.isEnabled()&&t!==null&&(Kcn(e,t.name)||e.addUpdate(()=>(r4(e,[t]),!0)))}function i4(e){if(!e)return;const t=new TextEncoder;try{if(typeof e=="string")return t.encode(e).length;if(e instanceof URLSearchParams)return t.encode(e.toString()).length;if(e instanceof FormData){const n=$ze(e);return t.encode(n).length}if(e instanceof Blob)return e.size;if(e instanceof ArrayBuffer)return e.byteLength}catch{}}function Oze(e){if(!e)return;const t=parseInt(e,10);return isNaN(t)?void 0:t}function Rze(e){try{if(typeof e=="string")return[e];if(e instanceof URLSearchParams)return[e.toString()];if(e instanceof FormData)return[$ze(e)];if(!e)return[void 0]}catch(t){return tn&&on.exception(t,"Failed to serialize body",e),[void 0,"BODY_PARSE_ERROR"]}return tn&&on.info("Skipping network body because of body type",e),[void 0,"UNPARSEABLE_BODY_TYPE"]}function uO(e,t){if(!e)return{headers:{},size:void 0,_meta:{warnings:[t]}};const n={...e._meta},r=n.warnings||[];return n.warnings=[...r,t],e._meta=n,e}function Pze(e,t){if(!t)return null;const{startTimestamp:n,endTimestamp:r,url:i,method:a,statusCode:s,request:o,response:u}=t;return{type:e,start:n/1e3,end:r/1e3,name:i,data:Na({method:a,statusCode:s,request:o,response:u})}}function Y2(e){return{headers:{},size:e,_meta:{warnings:["URL_SKIPPED"]}}}function Lp(e,t,n){if(!t&&Object.keys(e).length===0)return;if(!t)return{headers:e};if(!n)return{headers:e,size:t};const r={headers:e,size:t},{body:i,warnings:a}=Zcn(n);return r.body=i,a&&a.length>0&&(r._meta={warnings:a}),r}function O9(e,t){return Object.entries(e).reduce((n,[r,i])=>{const a=r.toLowerCase();return t.includes(a)&&e[r]&&(n[a]=i),n},{})}function $ze(e){return new URLSearchParams(e).toString()}function Zcn(e){if(!e||typeof e!="string")return{body:e};const t=e.length>T0e,n=Ycn(e);if(t){const r=e.slice(0,T0e);return n?{body:r,warnings:["MAYBE_JSON_TRUNCATED"]}:{body:`${r}…`,warnings:["TEXT_TRUNCATED"]}}if(n)try{return{body:JSON.parse(e)}}catch{}return{body:e}}function Ycn(e){const t=e[0],n=e[e.length-1];return t==="["&&n==="]"||t==="{"&&n==="}"}function cO(e,t){const n=Xcn(e);return Dp(n,t)}function Xcn(e,t=ni.document.baseURI){if(e.startsWith("http://")||e.startsWith("https://")||e.startsWith(ni.location.origin))return e;const n=new URL(e,t);if(n.origin!==new URL(t).origin)return e;const r=n.href;return!e.endsWith("/")&&r.endsWith("/")?r.slice(0,-1):r}async function Jcn(e,t,n){try{const r=await edn(e,t,n),i=Pze("resource.fetch",r);jze(n.replay,i)}catch(r){tn&&on.exception(r,"Failed to capture fetch breadcrumb")}}function Qcn(e,t){const{input:n,response:r}=t,i=n?Mze(n):void 0,a=i4(i),s=r?Oze(r.headers.get("content-length")):void 0;a!==void 0&&(e.data.request_body_size=a),s!==void 0&&(e.data.response_body_size=s)}async function edn(e,t,n){const r=Date.now(),{startTimestamp:i=r,endTimestamp:a=r}=t,{url:s,method:o,status_code:u=0,request_body_size:c,response_body_size:d}=e.data,f=cO(s,n.networkDetailAllowUrls)&&!cO(s,n.networkDetailDenyUrls),p=f?tdn(n,t.input,c):Y2(c),m=await ndn(f,n,t.response,d);return{startTimestamp:i,endTimestamp:a,url:s,method:o,statusCode:u,request:p,response:m}}function tdn({networkCaptureBodies:e,networkRequestHeaders:t},n,r){const i=n?adn(n,t):{};if(!e)return Lp(i,r,void 0);const a=Mze(n),[s,o]=Rze(a),u=Lp(i,r,s);return o?uO(u,o):u}async function ndn(e,{networkCaptureBodies:t,networkResponseHeaders:n},r,i){if(!e&&i!==void 0)return Y2(i);const a=r?Dze(r.headers,n):{};if(!r||!t&&i!==void 0)return Lp(a,i,void 0);const[s,o]=await idn(r),u=rdn(s,{networkCaptureBodies:t,responseBodySize:i,captureDetails:e,headers:a});return o?uO(u,o):u}function rdn(e,{networkCaptureBodies:t,responseBodySize:n,captureDetails:r,headers:i}){try{const a=e&&e.length&&n===void 0?i4(e):n;return r?t?Lp(i,a,e):Lp(i,a,void 0):Y2(a)}catch(a){return tn&&on.exception(a,"Failed to serialize response body"),Lp(i,n,void 0)}}async function idn(e){const t=sdn(e);if(!t)return[void 0,"BODY_PARSE_ERROR"];try{return[await odn(t)]}catch(n){return n instanceof Error&&n.message.indexOf("Timeout")>-1?(tn&&on.warn("Parsing text body from response timed out"),[void 0,"BODY_PARSE_TIMEOUT"]):(tn&&on.exception(n,"Failed to get text body from response"),[void 0,"BODY_PARSE_ERROR"])}}function Mze(e=[]){if(!(e.length!==2||typeof e[1]!="object"))return e[1].body}function Dze(e,t){const n={};return t.forEach(r=>{e.get(r)&&(n[r]=e.get(r))}),n}function adn(e,t){return e.length===1&&typeof e[0]!="string"?W0e(e[0],t):e.length===2?W0e(e[1],t):{}}function W0e(e,t){if(!e)return{};const n=e.headers;return n?n instanceof Headers?Dze(n,t):Array.isArray(n)?{}:O9(n,t):{}}function sdn(e){try{return e.clone()}catch(t){tn&&on.exception(t,"Failed to clone response body")}}function odn(e){return new Promise((t,n)=>{const r=dx(()=>n(new Error("Timeout while trying to read response body")),500);ldn(e).then(i=>t(i),i=>n(i)).finally(()=>clearTimeout(r))})}async function ldn(e){return await e.text()}async function udn(e,t,n){try{const r=ddn(e,t,n),i=Pze("resource.xhr",r);jze(n.replay,i)}catch(r){tn&&on.exception(r,"Failed to capture xhr breadcrumb")}}function cdn(e,t){const{xhr:n,input:r}=t;if(!n)return;const i=i4(r),a=n.getResponseHeader("content-length")?Oze(n.getResponseHeader("content-length")):mdn(n.response,n.responseType);i!==void 0&&(e.data.request_body_size=i),a!==void 0&&(e.data.response_body_size=a)}function ddn(e,t,n){const r=Date.now(),{startTimestamp:i=r,endTimestamp:a=r,input:s,xhr:o}=t,{url:u,method:c,status_code:d=0,request_body_size:f,response_body_size:p}=e.data;if(!u)return null;if(!o||!cO(u,n.networkDetailAllowUrls)||cO(u,n.networkDetailDenyUrls)){const E=Y2(f),A=Y2(p);return{startTimestamp:i,endTimestamp:a,url:u,method:c,statusCode:d,request:E,response:A}}const m=o[ym],y=m?O9(m.request_headers,n.networkRequestHeaders):{},v=O9(fdn(o),n.networkResponseHeaders),[x,_]=n.networkCaptureBodies?Rze(s):[void 0],[S,w]=n.networkCaptureBodies?pdn(o):[void 0],T=Lp(y,f,x),N=Lp(v,p,S);return{startTimestamp:i,endTimestamp:a,url:u,method:c,statusCode:d,request:_?uO(T,_):T,response:w?uO(N,w):N}}function fdn(e){const t=e.getAllResponseHeaders();return t?t.split(`\r
|
|
1941
1941
|
`).reduce((n,r)=>{const[i,a]=r.split(": ");return a&&(n[i.toLowerCase()]=a),n},{}):{}}function pdn(e){const t=[];try{return[e.responseText]}catch(n){t.push(n)}try{return hdn(e.response,e.responseType)}catch(n){t.push(n)}return tn&&on.warn("Failed to get xhr response body",...t),[void 0]}function hdn(e,t){try{if(typeof e=="string")return[e];if(e instanceof Document)return[e.body.outerHTML];if(t==="json"&&e&&typeof e=="object")return[JSON.stringify(e)];if(!e)return[void 0]}catch(n){return tn&&on.exception(n,"Failed to serialize body",e),[void 0,"BODY_PARSE_ERROR"]}return tn&&on.info("Skipping network body because of body type",e),[void 0,"UNPARSEABLE_BODY_TYPE"]}function mdn(e,t){try{const n=t==="json"&&e&&typeof e=="object"?JSON.stringify(e):e;return i4(n)}catch{return}}function gdn(e){const t=Xn();try{const{networkDetailAllowUrls:n,networkDetailDenyUrls:r,networkCaptureBodies:i,networkRequestHeaders:a,networkResponseHeaders:s}=e.getOptions(),o={replay:e,networkDetailAllowUrls:n,networkDetailDenyUrls:r,networkCaptureBodies:i,networkRequestHeaders:a,networkResponseHeaders:s};t&&t.on("beforeAddBreadcrumb",(u,c)=>vdn(o,u,c))}catch{}}function vdn(e,t,n){if(t.data)try{ydn(t)&&bdn(n)&&(cdn(t,n),udn(t,n,e)),xdn(t)&&_dn(n)&&(Qcn(t,n),Jcn(t,n,e))}catch(r){tn&&on.exception(r,"Error when enriching network breadcrumb")}}function ydn(e){return e.category==="xhr"}function xdn(e){return e.category==="fetch"}function bdn(e){return e&&e.xhr}function _dn(e){return e&&e.response}function wdn(e){const t=Xn();VLe(Xun(e)),JP(Wcn(e)),Lcn(e),gdn(e);const n=Vcn(e);Ein(n),t&&(t.on("beforeSendEvent",Mcn(e)),t.on("afterSendEvent",Rcn(e)),t.on("createDsc",r=>{const i=e.getSessionId();i&&e.isEnabled()&&e.recordingMode==="session"&&e.checkAndHandleExpiredSession()&&(r.replay_id=i)}),t.on("spanStart",r=>{e.lastActiveSpan=r}),t.on("spanEnd",r=>{e.lastActiveSpan=r}),t.on("beforeSendFeedback",(r,i)=>{const a=e.getSessionId();i&&i.includeReplay&&e.isEnabled()&&a&&r.contexts&&r.contexts.feedback&&(r.contexts.feedback.replay_id=a)}))}async function Sdn(e){try{return Promise.all(r4(e,[kdn(ni.performance.memory)]))}catch{return[]}}function kdn(e){const{jsHeapSizeLimit:t,totalJSHeapSize:n,usedJSHeapSize:r}=e,i=Date.now()/1e3;return{type:"memory",name:"memory",start:i,end:i,data:{memory:{jsHeapSizeLimit:t,totalJSHeapSize:n,usedJSHeapSize:r}}}}function Edn(e,t,n){let r,i,a;const s=n&&n.maxWait?Math.max(n.maxWait,t):0;function o(){return u(),r=e(),r}function u(){i!==void 0&&clearTimeout(i),a!==void 0&&clearTimeout(a),i=a=void 0}function c(){return i!==void 0||a!==void 0?o():r}function d(){return i&&clearTimeout(i),i=dx(o,t),s&&a===void 0&&(a=dx(o,s)),r}return d.cancel=u,d.flush=c,d}const tm=nr.navigator;function Tdn(){return/iPhone|iPad|iPod/i.test(tm&&tm.userAgent||"")||/Macintosh/i.test(tm&&tm.userAgent||"")&&tm&&tm.maxTouchPoints&&tm.maxTouchPoints>1?{sampling:{mousemove:!1}}:{}}function Ndn(e){let t=!1;return(n,r)=>{if(!e.checkAndHandleExpiredSession()){tn&&on.warn("Received replay event after session expired.");return}const i=r||!t;t=!0,e.clickDetector&&Gun(e.clickDetector,n),e.addUpdate(()=>{if(e.recordingMode==="buffer"&&i&&e.setInitialState(),!TY(e,n,i))return!0;if(!i)return!1;const a=e.session;if(Adn(e,i),e.recordingMode==="buffer"&&a&&e.eventBuffer){const s=e.eventBuffer.getEarliestTimestamp();s&&(tn&&on.info(`Updating session start time to earliest event in buffer to ${new Date(s)}`),a.started=s,e.getOptions().stickySession&&EY(a))}return a&&a.previousSessionId||e.recordingMode==="session"&&e.flush(),!0})}}function Cdn(e){const t=e.getOptions();return{type:On.Custom,timestamp:Date.now(),data:{tag:"options",payload:{shouldRecordCanvas:e.isRecordingCanvas(),sessionSampleRate:t.sessionSampleRate,errorSampleRate:t.errorSampleRate,useCompressionOption:t.useCompression,blockAllMedia:t.blockAllMedia,maskAllText:t.maskAllText,maskAllInputs:t.maskAllInputs,useCompression:e.eventBuffer?e.eventBuffer.type==="worker":!1,networkDetailHasUrls:t.networkDetailAllowUrls.length>0,networkCaptureBodies:t.networkCaptureBodies,networkRequestHasHeaders:t.networkRequestHeaders.length>0,networkResponseHasHeaders:t.networkResponseHeaders.length>0}}}}function Adn(e,t){!t||!e.session||e.session.segmentId!==0||TY(e,Cdn(e),!1)}function Idn(e,t,n,r){return Ug(iLe(e,sY(e),r,n),[[{type:"replay_event"},e],[{type:"replay_recording",length:typeof t=="string"?new TextEncoder().encode(t).length:t.length},t]])}function jdn({recordingData:e,headers:t}){let n;const r=`${JSON.stringify(t)}
|
|
1942
|
-
`;if(typeof e=="string")n=`${r}${e}`;else{const a=new TextEncoder().encode(r);n=new Uint8Array(a.length+e.length),n.set(a),n.set(e,a.length)}return n}async function Odn({client:e,scope:t,replayId:n,event:r}){const i=typeof e._integrations=="object"&&e._integrations!==null&&!Array.isArray(e._integrations)?Object.keys(e._integrations):void 0,a={event_id:n,integrations:i};e.emit("preprocessEvent",r,a);const s=await uLe(e.getOptions(),r,a,t,e,Yl());if(!s)return null;s.platform=s.platform||"javascript";const o=e.getSdkMetadata(),{name:u,version:c}=o&&o.sdk||{};return s.sdk={...s.sdk,name:u||"sentry.javascript.unknown",version:c||"0.0.0"},s}async function Rdn({recordingData:e,replayId:t,segmentId:n,eventContext:r,timestamp:i,session:a}){const s=jdn({recordingData:e,headers:{segment_id:n}}),{urls:o,errorIds:u,traceIds:c,initialTimestamp:d}=r,f=Xn(),p=ui(),m=f&&f.getTransport(),y=f&&f.getDsn();if(!f||!m||!y||!a.sampled)return df({});const v={type:dln,replay_start_timestamp:d/1e3,timestamp:i/1e3,error_ids:u,trace_ids:c,urls:o,replay_id:t,segment_id:n,replay_type:a.sampled},x=await Odn({scope:p,client:f,replayId:t,event:v});if(!x)return f.recordDroppedEvent("event_processor","replay",v),tn&&on.info("An event processor returned `null`, will not send event."),df({});delete x.sdkProcessingMetadata;const _=Idn(x,s,y,f.getOptions().tunnel);let S;try{S=await m.send(_)}catch(T){const N=new Error(mY);try{N.cause=T}catch{}throw N}if(typeof S.statusCode=="number"&&(S.statusCode<200||S.statusCode>=300))throw new Lze(S.statusCode);const w=xLe({},S);if(yLe(w,"replay"))throw new CY(w);return S}class Lze extends Error{constructor(t){super(`Transport returned status code ${t}`)}}class CY extends Error{constructor(t){super("Rate limit hit"),this.rateLimits=t}}async function zze(e,t={count:0,interval:vln}){const{recordingData:n,onError:r}=e;if(n.length)try{return await Rdn(e),!0}catch(i){if(i instanceof Lze||i instanceof CY)throw i;if(fLe("Replays",{_retryCount:t.count}),r&&r(i),t.count>=yln){const a=new Error(`${mY} - max retries exceeded`);try{a.cause=i}catch{}throw a}return t.interval*=++t.count,new Promise((a,s)=>{dx(async()=>{try{await zze(e,t),a(!0)}catch(o){s(o)}},t.interval)})}}const Uze="__THROTTLED",Pdn="__SKIPPED";function $dn(e,t,n){const r=new Map,i=o=>{const u=o-n;r.forEach((c,d)=>{d<u&&r.delete(d)})},a=()=>[...r.values()].reduce((o,u)=>o+u,0);let s=!1;return(...o)=>{const u=Math.floor(Date.now()/1e3);if(i(u),a()>=t){const d=s;return s=!0,d?Pdn:Uze}s=!1;const c=r.get(u)||0;return r.set(u,c+1),e(...o)}}class gp{constructor({options:t,recordingOptions:n}){gp.prototype.__init.call(this),gp.prototype.__init2.call(this),gp.prototype.__init3.call(this),gp.prototype.__init4.call(this),gp.prototype.__init5.call(this),gp.prototype.__init6.call(this),this.eventBuffer=null,this.performanceEntries=[],this.replayPerformanceEntries=[],this.recordingMode="session",this.timeouts={sessionIdlePause:fln,sessionIdleExpire:pln},this._lastActivity=Date.now(),this._isEnabled=!1,this._isPaused=!1,this._requiresManualStart=!1,this._hasInitializedCoreListeners=!1,this._context={errorIds:new Set,traceIds:new Set,urls:[],initialTimestamp:Date.now(),initialUrl:""},this._recordingOptions=n,this._options=t,this._debouncedFlush=Edn(()=>this._flush(),this._options.flushMinDelay,{maxWait:this._options.flushMaxDelay}),this._throttledAddEvent=$dn((s,o)=>Icn(this,s,o),300,5);const{slowClickTimeout:r,slowClickIgnoreSelectors:i}=this.getOptions(),a=r?{threshold:Math.min(xln,r),timeout:r,scrollTimeout:bln,ignoreSelector:i?i.join(","):""}:void 0;if(a&&(this.clickDetector=new Bun(this,a)),tn){const s=t._experiments;on.setConfig({captureExceptions:!!s.captureExceptions,traceInternals:!!s.traceInternals})}}getContext(){return this._context}isEnabled(){return this._isEnabled}isPaused(){return this._isPaused}isRecordingCanvas(){return!!this._canvas}getOptions(){return this._options}handleException(t){tn&&on.exception(t),this._options.onError&&this._options.onError(t)}initializeSampling(t){const{errorSampleRate:n,sessionSampleRate:r}=this._options,i=n<=0&&r<=0;if(this._requiresManualStart=i,!i){if(this._initializeSessionForSampling(t),!this.session){tn&&on.exception(new Error("Unable to initialize and create session"));return}this.session.sampled!==!1&&(this.recordingMode=this.session.sampled==="buffer"&&this.session.segmentId===0?"buffer":"session",tn&&on.infoTick(`Starting replay in ${this.recordingMode} mode`),this._initializeRecording())}}start(){if(this._isEnabled&&this.recordingMode==="session"){tn&&on.info("Recording is already in progress");return}if(this._isEnabled&&this.recordingMode==="buffer"){tn&&on.info("Buffering is in progress, call `flush()` to save the replay");return}tn&&on.infoTick("Starting replay in session mode"),this._updateUserActivity();const t=W8({maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire},{stickySession:this._options.stickySession,sessionSampleRate:1,allowBuffering:!1});this.session=t,this._initializeRecording()}startBuffering(){if(this._isEnabled){tn&&on.info("Buffering is in progress, call `flush()` to save the replay");return}tn&&on.infoTick("Starting replay in buffer mode");const t=W8({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration},{stickySession:this._options.stickySession,sessionSampleRate:0,allowBuffering:!0});this.session=t,this.recordingMode="buffer",this._initializeRecording()}startRecording(){try{const t=this._canvas;this._stopRecording=Jd({...this._recordingOptions,...this.recordingMode==="buffer"?{checkoutEveryNms:gln}:this._options._experiments.continuousCheckout&&{checkoutEveryNms:Math.max(36e4,this._options._experiments.continuousCheckout)},emit:Ndn(this),...Tdn(),onMutation:this._onMutationHandler,...t?{recordCanvas:t.recordCanvas,getCanvasManager:t.getCanvasManager,sampling:t.sampling,dataURLOptions:t.dataURLOptions}:{}})}catch(t){this.handleException(t)}}stopRecording(){try{return this._stopRecording&&(this._stopRecording(),this._stopRecording=void 0),!0}catch(t){return this.handleException(t),!1}}async stop({forceFlush:t=!1,reason:n}={}){if(this._isEnabled){this._isEnabled=!1;try{tn&&on.info(`Stopping Replay${n?` triggered by ${n}`:""}`),Ize(),this._removeListeners(),this.stopRecording(),this._debouncedFlush.cancel(),t&&await this._flush({force:!0}),this.eventBuffer&&this.eventBuffer.destroy(),this.eventBuffer=null,Ecn(this)}catch(r){this.handleException(r)}}}pause(){this._isPaused||(this._isPaused=!0,this.stopRecording(),tn&&on.info("Pausing replay"))}resume(){!this._isPaused||!this._checkSession()||(this._isPaused=!1,this.startRecording(),tn&&on.info("Resuming replay"))}async sendBufferedReplayOrFlush({continueRecording:t=!0}={}){if(this.recordingMode==="session")return this.flushImmediate();const n=Date.now();tn&&on.info("Converting buffer to session"),await this.flushImmediate();const r=this.stopRecording();!t||!r||this.recordingMode!=="session"&&(this.recordingMode="session",this.session&&(this._updateUserActivity(n),this._updateSessionActivity(n),this._maybeSaveSession()),this.startRecording())}addUpdate(t){const n=t();this.recordingMode!=="buffer"&&n!==!0&&this._debouncedFlush()}triggerUserActivity(){if(this._updateUserActivity(),!this._stopRecording){if(!this._checkSession())return;this.resume();return}this.checkAndHandleExpiredSession(),this._updateSessionActivity()}updateUserActivity(){this._updateUserActivity(),this._updateSessionActivity()}conditionalFlush(){return this.recordingMode==="buffer"?Promise.resolve():this.flushImmediate()}flush(){return this._debouncedFlush()}flushImmediate(){return this._debouncedFlush(),this._debouncedFlush.flush()}cancelFlush(){this._debouncedFlush.cancel()}getSessionId(){return this.session&&this.session.id}checkAndHandleExpiredSession(){if(this._lastActivity&&I9(this._lastActivity,this.timeouts.sessionIdlePause)&&this.session&&this.session.sampled==="session"){this.pause();return}return!!this._checkSession()}setInitialState(){const t=`${ni.location.pathname}${ni.location.hash}${ni.location.search}`,n=`${ni.location.origin}${t}`;this.performanceEntries=[],this.replayPerformanceEntries=[],this._clearContext(),this._context.initialUrl=n,this._context.initialTimestamp=Date.now(),this._context.urls.push(n)}throttledAddEvent(t,n){const r=this._throttledAddEvent(t,n);if(r===Uze){const i=bc({category:"replay.throttled"});this.addUpdate(()=>!TY(this,{type:$un,timestamp:i.timestamp||0,data:{tag:"breadcrumb",payload:i,metric:!0}}))}return r}getCurrentRoute(){const t=this.lastActiveSpan||Va(),n=t&&cs(t),i=(n&&fr(n).data||{})[xc];if(!(!n||!i||!["route","custom"].includes(i)))return fr(n).description}_initializeRecording(){this.setInitialState(),this._updateSessionActivity(),this.eventBuffer=wcn({useCompression:this._options.useCompression,workerUrl:this._options.workerUrl}),this._removeListeners(),this._addListeners(),this._isEnabled=!0,this._isPaused=!1,this.startRecording()}_initializeSessionForSampling(t){const n=this._options.errorSampleRate>0,r=W8({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration,previousSessionId:t},{stickySession:this._options.stickySession,sessionSampleRate:this._options.sessionSampleRate,allowBuffering:n});this.session=r}_checkSession(){if(!this.session)return!1;const t=this.session;return Tze(t,{sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration})?(this._refreshSession(t),!1):!0}async _refreshSession(t){this._isEnabled&&(await this.stop({reason:"refresh session"}),this.initializeSampling(t.id))}_addListeners(){try{ni.document.addEventListener("visibilitychange",this._handleVisibilityChange),ni.addEventListener("blur",this._handleWindowBlur),ni.addEventListener("focus",this._handleWindowFocus),ni.addEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.addListeners(),this._hasInitializedCoreListeners||(wdn(this),this._hasInitializedCoreListeners=!0)}catch(t){this.handleException(t)}this._performanceCleanupCallback=mcn(this)}_removeListeners(){try{ni.document.removeEventListener("visibilitychange",this._handleVisibilityChange),ni.removeEventListener("blur",this._handleWindowBlur),ni.removeEventListener("focus",this._handleWindowFocus),ni.removeEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.removeListeners(),this._performanceCleanupCallback&&this._performanceCleanupCallback()}catch(t){this.handleException(t)}}__init(){this._handleVisibilityChange=()=>{ni.document.visibilityState==="visible"?this._doChangeToForegroundTasks():this._doChangeToBackgroundTasks()}}__init2(){this._handleWindowBlur=()=>{const t=bc({category:"ui.blur"});this._doChangeToBackgroundTasks(t)}}__init3(){this._handleWindowFocus=()=>{const t=bc({category:"ui.focus"});this._doChangeToForegroundTasks(t)}}__init4(){this._handleKeyboardEvent=t=>{tcn(this,t)}}_doChangeToBackgroundTasks(t){!this.session||Eze(this.session,{maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire})||(t&&this._createCustomBreadcrumb(t),this.conditionalFlush())}_doChangeToForegroundTasks(t){if(!this.session)return;if(!this.checkAndHandleExpiredSession()){tn&&on.info("Document has become active, but session has expired");return}t&&this._createCustomBreadcrumb(t)}_updateUserActivity(t=Date.now()){this._lastActivity=t}_updateSessionActivity(t=Date.now()){this.session&&(this.session.lastActivity=t,this._maybeSaveSession())}_createCustomBreadcrumb(t){this.addUpdate(()=>{this.throttledAddEvent({type:On.Custom,timestamp:t.timestamp||0,data:{tag:"breadcrumb",payload:t}})})}_addPerformanceEntries(){let t=acn(this.performanceEntries).concat(this.replayPerformanceEntries);if(this.performanceEntries=[],this.replayPerformanceEntries=[],this._requiresManualStart){const n=this._context.initialTimestamp/1e3;t=t.filter(r=>r.start>=n)}return Promise.all(r4(this,t))}_clearContext(){this._context.errorIds.clear(),this._context.traceIds.clear(),this._context.urls=[]}_updateInitialTimestampFromEventBuffer(){const{session:t,eventBuffer:n}=this;if(!t||!n||this._requiresManualStart||t.segmentId)return;const r=n.getEarliestTimestamp();r&&r<this._context.initialTimestamp&&(this._context.initialTimestamp=r)}_popEventContext(){const t={initialTimestamp:this._context.initialTimestamp,initialUrl:this._context.initialUrl,errorIds:Array.from(this._context.errorIds),traceIds:Array.from(this._context.traceIds),urls:this._context.urls};return this._clearContext(),t}async _runFlush(){const t=this.getSessionId();if(!this.session||!this.eventBuffer||!t){tn&&on.error("No session or eventBuffer found to flush.");return}if(await this._addPerformanceEntries(),!(!this.eventBuffer||!this.eventBuffer.hasEvents)&&(await Sdn(this),!!this.eventBuffer&&t===this.getSessionId()))try{this._updateInitialTimestampFromEventBuffer();const n=Date.now();if(n-this._context.initialTimestamp>this._options.maxReplayDuration+3e4)throw new Error("Session is too long, not sending replay");const r=this._popEventContext(),i=this.session.segmentId++;this._maybeSaveSession();const a=await this.eventBuffer.finish();await zze({replayId:t,recordingData:a,segmentId:i,eventContext:r,session:this.session,timestamp:n,onError:s=>this.handleException(s)})}catch(n){this.handleException(n),this.stop({reason:"sendReplay"});const r=Xn();if(r){const i=n instanceof CY?"ratelimit_backoff":"send_error";r.recordDroppedEvent(i,"replay")}}}__init5(){this._flush=async({force:t=!1}={})=>{if(!this._isEnabled&&!t)return;if(!this.checkAndHandleExpiredSession()){tn&&on.error("Attempting to finish replay event after session expired.");return}if(!this.session)return;const n=this.session.started,i=Date.now()-n;this._debouncedFlush.cancel();const a=i<this._options.minReplayDuration,s=i>this._options.maxReplayDuration+5e3;if(a||s){tn&&on.info(`Session duration (${Math.floor(i/1e3)}s) is too ${a?"short":"long"}, not sending replay.`),a&&this._debouncedFlush();return}const o=this.eventBuffer;o&&this.session.segmentId===0&&!o.hasCheckout&&tn&&on.info("Flushing initial segment without checkout.");const u=!!this._flushLock;this._flushLock||(this._flushLock=this._runFlush());try{await this._flushLock}catch(c){this.handleException(c)}finally{this._flushLock=void 0,u&&this._debouncedFlush()}}}_maybeSaveSession(){this.session&&this._options.stickySession&&EY(this.session)}__init6(){this._onMutationHandler=t=>{const n=t.length,r=this._options.mutationLimit,i=this._options.mutationBreadcrumbLimit,a=r&&n>r;if(n>i||a){const s=bc({category:"replay.mutations",data:{count:n,limit:a}});this._createCustomBreadcrumb(s)}return a?(this.stop({reason:"mutationLimit",forceFlush:this.recordingMode==="session"}),!1):!0}}}function V_(e,t){return[...e,...t].join(",")}function Mdn({mask:e,unmask:t,block:n,unblock:r,ignore:i}){const a=["base","iframe[srcdoc]:not([src])"],s=V_(e,[".sentry-mask","[data-sentry-mask]"]),o=V_(t,[]);return{maskTextSelector:s,unmaskTextSelector:o,blockSelector:V_(n,[".sentry-block","[data-sentry-block]",...a]),unblockSelector:V_(r,[]),ignoreSelector:V_(i,[".sentry-ignore","[data-sentry-ignore]",'input[type="file"]'])}}function Ddn({el:e,key:t,maskAttributes:n,maskAllText:r,privacyOptions:i,value:a}){return!r||i.unmaskTextSelector&&e.matches(i.unmaskTextSelector)?a:n.includes(t)||t==="value"&&e.tagName==="INPUT"&&["submit","button"].includes(e.getAttribute("type")||"")?a.replace(/[\S]/g,"*"):a}const K0e='img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]',Ldn=["content-length","content-type","accept"];let Z0e=!1;const zdn=(e=>new a4(e));class a4{static __initStatic(){this.id="Replay"}constructor({flushMinDelay:t=hln,flushMaxDelay:n=mln,minReplayDuration:r=_ln,maxReplayDuration:i=N0e,stickySession:a=!0,useCompression:s=!0,workerUrl:o,_experiments:u={},maskAllText:c=!0,maskAllInputs:d=!0,blockAllMedia:f=!0,mutationBreadcrumbLimit:p=750,mutationLimit:m=1e4,slowClickTimeout:y=7e3,slowClickIgnoreSelectors:v=[],networkDetailAllowUrls:x=[],networkDetailDenyUrls:_=[],networkCaptureBodies:S=!0,networkRequestHeaders:w=[],networkResponseHeaders:T=[],mask:N=[],maskAttributes:E=["title","placeholder"],unmask:A=[],block:I=[],unblock:M=[],ignore:$=[],maskFn:O,beforeAddRecordingEvent:R,beforeErrorSampling:U,onError:z}={}){this.name=a4.id;const F=Mdn({mask:N,unmask:A,block:I,unblock:M,ignore:$});if(this._recordingOptions={maskAllInputs:d,maskAllText:c,maskInputOptions:{password:!0},maskTextFn:O,maskInputFn:O,maskAttributeFn:(D,W,q)=>Ddn({maskAttributes:E,maskAllText:c,privacyOptions:F,key:D,value:W,el:q}),...F,slimDOMOptions:"all",inlineStylesheet:!0,inlineImages:!1,collectFonts:!0,errorHandler:D=>{try{D.__rrweb__=!0}catch{}}},this._initialOptions={flushMinDelay:t,flushMaxDelay:n,minReplayDuration:Math.min(r,wln),maxReplayDuration:Math.min(i,N0e),stickySession:a,useCompression:s,workerUrl:o,blockAllMedia:f,maskAllInputs:d,maskAllText:c,mutationBreadcrumbLimit:p,mutationLimit:m,slowClickTimeout:y,slowClickIgnoreSelectors:v,networkDetailAllowUrls:x,networkDetailDenyUrls:_,networkCaptureBodies:S,networkRequestHeaders:Y0e(w),networkResponseHeaders:Y0e(T),beforeAddRecordingEvent:R,beforeErrorSampling:U,onError:z,_experiments:u},this._initialOptions.blockAllMedia&&(this._recordingOptions.blockSelector=this._recordingOptions.blockSelector?`${this._recordingOptions.blockSelector},${K0e}`:K0e),this._isInitialized&&v0e())throw new Error("Multiple Sentry Session Replay instances are not supported");this._isInitialized=!0}get _isInitialized(){return Z0e}set _isInitialized(t){Z0e=t}afterAllSetup(t){!v0e()||this._replay||(this._setup(t),this._initialize(t))}start(){this._replay&&this._replay.start()}startBuffering(){this._replay&&this._replay.startBuffering()}stop(){return this._replay?this._replay.stop({forceFlush:this._replay.recordingMode==="session"}):Promise.resolve()}flush(t){return this._replay?this._replay.isEnabled()?this._replay.sendBufferedReplayOrFlush(t):(this._replay.start(),Promise.resolve()):Promise.resolve()}getReplayId(){if(!(!this._replay||!this._replay.isEnabled()))return this._replay.getSessionId()}getRecordingMode(){if(!(!this._replay||!this._replay.isEnabled()))return this._replay.recordingMode}_initialize(t){this._replay&&(this._maybeLoadFromReplayCanvasIntegration(t),this._replay.initializeSampling())}_setup(t){const n=Udn(this._initialOptions,t);this._replay=new gp({options:n,recordingOptions:this._recordingOptions})}_maybeLoadFromReplayCanvasIntegration(t){try{const n=t.getIntegrationByName("ReplayCanvas");if(!n)return;this._replay._canvas=n.getOptions()}catch{}}}a4.__initStatic();function Udn(e,t){const n=t.getOptions(),r={sessionSampleRate:0,errorSampleRate:0,...Na(e)},i=Jj(n.replaysSessionSampleRate),a=Jj(n.replaysOnErrorSampleRate);return i==null&&a==null&&yh(()=>{console.warn("Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.")}),i!=null&&(r.sessionSampleRate=i),a!=null&&(r.errorSampleRate=a),r}function Y0e(e){return[...Ldn,...e.map(t=>t.toLowerCase())]}const X0e=new WeakMap,K8=new Map,BC={traceFetch:!0,traceXHR:!0,enableHTTPTimings:!0,trackFetchStreamPerformance:!1};function Fdn(e,t){const{traceFetch:n,traceXHR:r,trackFetchStreamPerformance:i,shouldCreateSpanForRequest:a,enableHTTPTimings:s,tracePropagationTargets:o}={traceFetch:BC.traceFetch,traceXHR:BC.traceXHR,trackFetchStreamPerformance:BC.trackFetchStreamPerformance,...t},u=typeof a=="function"?a:f=>!0,c=f=>Hdn(f,o),d={};n&&(e.addEventProcessor(f=>(f.type==="transaction"&&f.spans&&f.spans.forEach(p=>{if(p.op==="http.client"){const m=K8.get(p.span_id);m&&(p.timestamp=m/1e3,K8.delete(p.span_id))}}),f)),i&&jan(f=>{if(f.response){const p=X0e.get(f.response);p&&f.endTimestamp&&K8.set(p,f.endTimestamp)}}),NLe(f=>{const p=kan(f,u,c,d);if(f.response&&f.fetchData.__span&&X0e.set(f.response,f.fetchData.__span),p){const m=Fze(f.fetchData.url),y=m?Om(m).host:void 0;p.setAttributes({"http.url":m,"server.address":y})}s&&p&&J0e(p)})),r&&WLe(f=>{const p=Vdn(f,u,c,d);s&&p&&J0e(p)})}function Bdn(e){return e.entryType==="resource"&&"initiatorType"in e&&typeof e.nextHopProtocol=="string"&&(e.initiatorType==="fetch"||e.initiatorType==="xmlhttprequest")}function J0e(e){const{url:t}=fr(e).data||{};if(!t||typeof t!="string")return;const n=cx("resource",({entries:r})=>{r.forEach(i=>{Bdn(i)&&i.name.endsWith(t)&&(qdn(i).forEach(s=>e.setAttribute(...s)),setTimeout(n))})})}function Qu(e=0){return((to||performance.timeOrigin)+e)/1e3}function qdn(e){const{name:t,version:n}=HLe(e.nextHopProtocol),r=[];return r.push(["network.protocol.version",n],["network.protocol.name",t]),to?[...r,["http.request.redirect_start",Qu(e.redirectStart)],["http.request.fetch_start",Qu(e.fetchStart)],["http.request.domain_lookup_start",Qu(e.domainLookupStart)],["http.request.domain_lookup_end",Qu(e.domainLookupEnd)],["http.request.connect_start",Qu(e.connectStart)],["http.request.secure_connection_start",Qu(e.secureConnectionStart)],["http.request.connection_end",Qu(e.connectEnd)],["http.request.request_start",Qu(e.requestStart)],["http.request.response_start",Qu(e.responseStart)],["http.request.response_end",Qu(e.responseEnd)]]:r}function Hdn(e,t){const n=hn.location&&hn.location.href;if(n){let r,i;try{r=new URL(e,n),i=new URL(n).origin}catch{return!1}const a=r.origin===i;return t?Dp(r.toString(),t)||a&&Dp(r.pathname,t):a}else{const r=!!e.match(/^\/(?!\/)/);return t?Dp(e,t):r}}function Vdn(e,t,n,r){const i=e.xhr,a=i&&i[ym];if(!i||i.__sentry_own_request__||!a)return;const s=Xp()&&t(a.url);if(e.endTimestamp&&s){const f=i.__sentry_xhr_span_id__;if(!f)return;const p=r[f];p&&a.status_code!==void 0&&(B6e(p,a.status_code),p.end(),delete r[f]);return}const o=Fze(a.url),u=o?Om(o).host:void 0,c=!!Va(),d=s&&c?Nk({name:`${a.method} ${a.url}`,attributes:{type:"xhr","http.method":a.method,"http.url":o,url:a.url,"server.address":u,[Fa]:"auto.http.browser",[vg]:"http.client"}}):new Yx;return i.__sentry_xhr_span_id__=d.spanContext().spanId,r[i.__sentry_xhr_span_id__]=d,n(a.url)&&Gdn(i,Xp()&&c?d:void 0),d}function Gdn(e,t){const{"sentry-trace":n,baggage:r}=_Le({span:t});n&&Wdn(e,n,r)}function Wdn(e,t,n){try{e.setRequestHeader("sentry-trace",t),n&&e.setRequestHeader("baggage",n)}catch{}}function Fze(e){try{return new URL(e,hn.location.origin).href}catch{return}}function Kdn(){hn&&hn.document?hn.document.addEventListener("visibilitychange",()=>{const e=Va();if(!e)return;const t=cs(e);if(hn.document.hidden&&t){const n="cancelled",{op:r,status:i}=fr(t);Lc&&bt.log(`[Tracing] Transaction: ${n} -> since tab moved to the background, op: ${r}`),i||t.setStatus({code:Ma,message:n}),t.setAttribute("sentry.cancellation_reason","document.hidden"),t.end()}}):Lc&&bt.warn("[Tracing] Could not set up background tab detection due to lack of global document")}const Zdn="BrowserTracing",Ydn={...DC,instrumentNavigation:!0,instrumentPageLoad:!0,markBackgroundSpan:!0,enableLongTask:!0,enableLongAnimationFrame:!0,enableInp:!0,_experiments:{},...BC},Xdn=((e={})=>{Crn();const{enableInp:t,enableLongTask:n,enableLongAnimationFrame:r,_experiments:{enableInteractions:i,enableStandaloneClsSpans:a},beforeStartSpan:s,idleTimeout:o,finalTimeout:u,childSpanTimeout:c,markBackgroundSpan:d,traceFetch:f,traceXHR:p,trackFetchStreamPerformance:m,shouldCreateSpanForRequest:y,enableHTTPTimings:v,instrumentPageLoad:x,instrumentNavigation:_}={...Ydn,...e},S=Usn({recordClsStandaloneSpans:a||!1});t&&don(),r&&nr.PerformanceObserver&&PerformanceObserver.supportedEntryTypes&&PerformanceObserver.supportedEntryTypes.includes("long-animation-frame")?Bsn():n&&Fsn(),i&&qsn();const w={name:void 0,source:void 0};function T(N,E){const A=E.op==="pageload",I=s?s(E):E,M=I.attributes||{};E.name!==I.name&&(M[xc]="custom",I.attributes=M),w.name=I.name,w.source=M[xc];const $=lLe(I,{idleTimeout:o,finalTimeout:u,childSpanTimeout:c,disableAutoFinish:A,beforeSpanEnd:R=>{S(),Ksn(R,{recordClsOnPageloadSpan:!a})}});function O(){["interactive","complete"].includes(hn.document.readyState)&&N.emit("idleSpanEnableAutoFinish",$)}return A&&hn.document&&(hn.document.addEventListener("readystatechange",()=>{O()}),O()),$}return{name:Zdn,afterAllSetup(N){let E,A=hn.location&&hn.location.href;function I(){E&&!fr(E).timestamp&&(Lc&&bt.log(`[Tracing] Finishing current active span with op: ${fr(E).op}`),E.end())}N.on("startNavigationSpan",M=>{Xn()===N&&(I(),E=T(N,{op:"navigation",...M}))}),N.on("startPageLoadSpan",(M,$={})=>{if(Xn()!==N)return;I();const O=$.sentryTrace||Q0e("sentry-trace"),R=$.baggage||Q0e("baggage"),U=_rn(O,R);ui().setPropagationContext(U),E=T(N,{op:"pageload",...M})}),N.on("spanEnd",M=>{const $=fr(M).op;if(M!==cs(M)||$!=="navigation"&&$!=="pageload")return;const O=ui(),R=O.getPropagationContext();O.setPropagationContext({...R,sampled:R.sampled!==void 0?R.sampled:Lg(M),dsc:R.dsc||zg(M)})}),hn.location&&(x&&Jdn(N,{name:hn.location.pathname,startTime:to?to/1e3:void 0,attributes:{[xc]:"url",[Fa]:"auto.pageload.browser"}}),_&&JP(({to:M,from:$})=>{if($===void 0&&A&&A.indexOf(M)!==-1){A=void 0;return}$!==M&&(A=void 0,Qdn(N,{name:hn.location.pathname,attributes:{[xc]:"url",[Fa]:"auto.navigation.browser"}}))})),d&&Kdn(),i&&efn(o,u,c,w),t&&pon(),Fdn(N,{traceFetch:f,traceXHR:p,trackFetchStreamPerformance:m,tracePropagationTargets:N.getOptions().tracePropagationTargets,shouldCreateSpanForRequest:y,enableHTTPTimings:v})}}});function Jdn(e,t,n){e.emit("startPageLoadSpan",t,n),ui().setTransactionName(t.name);const r=Va();return(r&&fr(r).op)==="pageload"?r:void 0}function Qdn(e,t){Yl().setPropagationContext({traceId:Zp()}),ui().setPropagationContext({traceId:Zp()}),e.emit("startNavigationSpan",t),ui().setTransactionName(t.name);const n=Va();return(n&&fr(n).op)==="navigation"?n:void 0}function Q0e(e){const t=Wnn(`meta[name=${e}]`);return t?t.getAttribute("content"):void 0}function efn(e,t,n,r){let i;const a=()=>{const s="ui.action.click",o=Va(),u=o&&cs(o);if(u){const c=fr(u).op;if(["navigation","pageload"].includes(c)){Lc&&bt.warn(`[Tracing] Did not create ${s} span because a pageload or navigation span is in progress.`);return}}if(i&&(i.setAttribute(s9,"interactionInterrupted"),i.end(),i=void 0),!r.name){Lc&&bt.warn(`[Tracing] Did not create ${s} transaction because _latestRouteName is missing.`);return}i=lLe({name:r.name,op:s,attributes:{[xc]:r.source||"url"}},{idleTimeout:e,finalTimeout:t,childSpanTimeout:n})};hn.document&&addEventListener("click",a,{once:!1,capture:!0})}function tfn(e){const t={...e};return bLe(t,"react"),fLe("react",{version:b.version}),cln(t)}function nfn(){const{user:e}=Aa(),{isAuthenticated:t,isLoading:n}=Ba(),r=_n("users:ensureUser"),i=b.useRef(null);b.useEffect(()=>{t||(i.current=null,r0e(null))},[t]),b.useEffect(()=>{if(!n){if(!t&&e)throw console.log("useEnsureDbUser: not authenticated"),new Error("Not authenticated");t&&e&&i.current!==e.id&&r().then(a=>{i.current=e.id,r0e({id:e.id})}).catch(a=>{console.error("[auth] ensureUser failed",a),i.current=null})}},[t,n,e,r])}function rfn(){const e=ci(),{user:t}=Aa(),{isAuthenticated:n}=Ba();b.useEffect(()=>{e&&(n&&t?(e.identify(t.id,{email:t.email,name:t.firstName&&t.lastName?`${t.firstName} ${t.lastName}`:t.email,first_name:t.firstName,last_name:t.lastName}),e.register({user_id:t.id})):e.reset())},[e,n,t])}function ifn(){return l.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-primary mx-auto"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Completing sign in..."})]})})}function afn(){return l.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:l.jsx("div",{className:"text-center",children:l.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-primary mx-auto"})})})}const Bze=de.forwardRef(({className:e,...t},n)=>l.jsx("svg",{ref:n,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 50 50",fill:"currentColor",className:e,...t,children:l.jsx("path",{d:"M 41.625 10.769531 C 37.644531 7.566406 31.347656 7.023438 31.078125 7.003906 C 30.660156 6.96875 30.261719 7.203125 30.089844 7.589844 C 30.074219 7.613281 29.9375 7.929688 29.785156 8.421875 C 32.417969 8.867188 35.652344 9.761719 38.578125 11.578125 C 39.046875 11.867188 39.191406 12.484375 38.902344 12.953125 C 38.710938 13.261719 38.386719 13.429688 38.050781 13.429688 C 37.871094 13.429688 37.6875 13.378906 37.523438 13.277344 C 32.492188 10.15625 26.210938 10 25 10 C 23.789063 10 17.503906 10.15625 12.476563 13.277344 C 12.007813 13.570313 11.390625 13.425781 11.101563 12.957031 C 10.808594 12.484375 10.953125 11.871094 11.421875 11.578125 C 14.347656 9.765625 17.582031 8.867188 20.214844 8.425781 C 20.0625 7.929688 19.925781 7.617188 19.914063 7.589844 C 19.738281 7.203125 19.34375 6.960938 18.921875 7.003906 C 18.652344 7.023438 12.355469 7.566406 8.320313 10.8125 C 6.214844 12.761719 2 24.152344 2 34 C 2 34.175781 2.046875 34.34375 2.132813 34.496094 C 5.039063 39.605469 12.972656 40.941406 14.78125 41 C 14.789063 41 14.800781 41 14.8125 41 C 15.132813 41 15.433594 40.847656 15.621094 40.589844 L 17.449219 38.074219 C 12.515625 36.800781 9.996094 34.636719 9.851563 34.507813 C 9.4375 34.144531 9.398438 33.511719 9.765625 33.097656 C 10.128906 32.683594 10.761719 32.644531 11.175781 33.007813 C 11.234375 33.0625 15.875 37 25 37 C 34.140625 37 38.78125 33.046875 38.828125 33.007813 C 39.242188 32.648438 39.871094 32.683594 40.238281 33.101563 C 40.601563 33.515625 40.5625 34.144531 40.148438 34.507813 C 40.003906 34.636719 37.484375 36.800781 32.550781 38.074219 L 34.378906 40.589844 C 34.566406 40.847656 34.867188 41 35.1875 41 C 35.199219 41 35.210938 41 35.21875 41 C 37.027344 40.941406 44.960938 39.605469 47.867188 34.496094 C 47.953125 34.34375 48 34.175781 48 34 C 48 24.152344 43.785156 12.761719 41.625 10.769531 Z M 18.5 30 C 16.566406 30 15 28.210938 15 26 C 15 23.789063 16.566406 22 18.5 22 C 20.433594 22 22 23.789063 22 26 C 22 28.210938 20.433594 30 18.5 30 Z M 31.5 30 C 29.566406 30 28 28.210938 28 26 C 28 23.789063 29.566406 22 31.5 22 C 33.433594 22 35 23.789063 35 26 C 35 28.210938 33.433594 30 31.5 30 Z"})}));Bze.displayName="DiscordIcon";const qze=de.forwardRef(({className:e,...t},n)=>l.jsx("svg",{ref:n,viewBox:"0 0 24 24",fill:"currentColor",className:e,...t,children:l.jsx("path",{d:"M12 .5C5.73.5.5 5.73.5 12.02c0 5.1 3.29 9.42 7.86 10.95.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.69-3.88-1.54-3.88-1.54-.53-1.35-1.29-1.71-1.29-1.71-1.05-.72.08-.7.08-.7 1.17.08 1.78 1.2 1.78 1.2 1.04 1.78 2.72 1.26 3.38.97.1-.76.41-1.26.75-1.55-2.55-.29-5.24-1.28-5.24-5.69 0-1.26.45-2.29 1.19-3.09-.12-.29-.52-1.45.11-3.02 0 0 .97-.31 3.18 1.18a11.1 11.1 0 0 1 5.79 0c2.2-1.49 3.17-1.18 3.17-1.18.63 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.09 0 4.42-2.69 5.39-5.25 5.67.42.36.8 1.1.8 2.22 0 1.6-.01 2.88-.01 3.27 0 .31.21.68.8.56 4.56-1.54 7.85-5.86 7.85-10.95C23.5 5.73 18.27.5 12 .5Z"})}));qze.displayName="GitHubIcon";function sfn(e){switch(e){case"connected":return"bg-green-500 dark:bg-green-400";case"connecting":return"bg-yellow-500 dark:bg-yellow-400 animate-pulse";case"failed":return"bg-red-500 dark:bg-red-400";case"disconnected":return"bg-muted-foreground";default:return"bg-muted-foreground"}}function ofn(e){switch(e){case"connected":return"Connected";case"connecting":return"Connecting...";case"failed":return"Failed";case"disconnected":return"Disconnected";default:return"Unknown"}}function lfn({serverConfigs:e,selectedServer:t,selectedMultipleServers:n,isMultiSelectEnabled:r,onServerChange:i,onMultiServerToggle:a,onConnect:s,onReconnect:o,showOnlyOAuthServers:u=!1,showOnlyOpenAIAppsServers:c=!1,openAiAppOrMcpAppsServers:d,showOnlyServersWithViews:f=!1,serversWithViews:p,hasMessages:m=!1,className:y}){const[v,x]=b.useState(!1),[_,S]=b.useState(!1),[w,T]=b.useState(null),[N,E]=b.useState(!1),[A,I]=b.useState(!1),M=b.useRef(null),$=ci(),O=W=>"url"in W.config?!!(W.oauthTokens||qH(W.name)||W.connectionStatus==="oauth-flow"):!1,R=Object.entries(e).filter(([W,q])=>!(u&&!O(q)||c&&d&&!d.has(W)||f&&p&&!p.has(W)));b.useEffect(()=>{if(r)return;const W=R.map(([X])=>X);!W.includes(t)&&W.length>0&&i(W[0])},[R.length,t,r,i]);const U=W=>{if(r){if(m){T(W),S(!0);return}a(W)}else{if(t!==W&&m){T(W),S(!0);return}i(W)}},z=()=>{w&&(r?a(w):i(w),T(null)),S(!1)},F=()=>{T(null),S(!1)};b.useEffect(()=>{const W=M.current;if(!W)return;const q=()=>{E(W.scrollLeft>0),I(W.scrollLeft+W.clientWidth<W.scrollWidth-1)};return q(),W.addEventListener("scroll",q,{passive:!0}),window.addEventListener("resize",q),()=>{W.removeEventListener("scroll",q),window.removeEventListener("resize",q)}},[R.length]);const D=W=>{const q=M.current;if(!q)return;const X=200,L=W==="left"?Math.max(0,q.scrollLeft-X):Math.min(q.scrollWidth-q.clientWidth,q.scrollLeft+X);q.scrollTo({left:L,behavior:"smooth"})};return l.jsx("div",{className:Ie("relative h-full w-full min-w-0",y),children:l.jsxs("div",{ref:M,className:Ie("w-full h-full min-w-0 overflow-x-auto scrollbar-hidden","flex justify-start"),children:[l.jsxs("div",{className:"flex flex-nowrap min-w-fit h-full",children:[R.map(([W,q])=>{const X=r?n.includes(W):t===W;return l.jsxs("button",{onClick:L=>{L.target.closest("[data-reconnect-button]")||U(W)},className:Ie("group relative flex h-full items-center gap-3 px-4 border-r border-border transition-all duration-200 cursor-pointer outline-none focus-visible:bg-accent focus-visible:text-accent-foreground","hover:bg-accent hover:text-accent-foreground",X?"bg-muted text-foreground":"bg-background text-foreground"),children:[r&&l.jsx("div",{className:Ie("w-4 h-4 rounded border-2 flex items-center justify-center transition-colors",X?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30 hover:border-primary/50"),children:X&&l.jsx(xi,{className:"w-3 h-3"})}),l.jsx("div",{className:Ie("w-2 h-2 rounded-full",sfn(q.connectionStatus)),title:ofn(q.connectionStatus)}),l.jsx("span",{className:"text-sm font-medium truncate max-w-36",children:W}),l.jsx("div",{className:"text-xs opacity-70",children:q.config.command?"STDIO":"HTTP"}),o&&l.jsx("div",{role:"button",tabIndex:0,"data-reconnect-button":!0,onClick:L=>{L.stopPropagation(),L.nativeEvent.stopImmediatePropagation(),L.preventDefault(),o(W)},className:"ml-auto p-1 rounded-md hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground transition-colors",title:"Reconnect",children:l.jsx(wn,{className:"w-3 h-3"})})]},W)}),l.jsxs("button",{onClick:()=>{x(!0)},className:Ie("group relative flex h-full items-center gap-3 px-4 border-r border-border transition-all duration-200 cursor-pointer","hover:bg-accent hover:text-accent-foreground","bg-background text-muted-foreground border-dashed"),children:[r&&l.jsx("div",{className:"w-4 h-4"}),l.jsx("span",{className:"text-sm font-medium",children:"Add Server"}),l.jsx("div",{className:"text-xs opacity-70",children:"+"})]})]}),l.jsx(uIe,{isOpen:v,onClose:()=>x(!1),onSubmit:W=>{$.capture("connecting_server",{location:"active_server_selector",platform:Et(),environment:void 0}),s(W)}}),l.jsx(hK,{open:_,onConfirm:z,onCancel:F,message:"Changing server selection will cause the chat to reset. This action cannot be undone."}),N&&l.jsx("button",{className:"absolute left-0 top-0 h-full px-3 flex items-center bg-gradient-to-r from-background via-background/95 to-background/40 cursor-pointer",onClick:()=>D("left"),"aria-label":"Scroll left",children:l.jsx(Dq,{className:"h-5 w-5"})}),A&&l.jsx("button",{className:"absolute right-0 top-0 h-full px-3 flex items-center bg-gradient-to-l from-background via-background/95 to-background/40 cursor-pointer",onClick:()=>D("right"),"aria-label":"Scroll right",children:l.jsx(wr,{className:"h-5 w-5"})})]})})}function ufn({isAuthenticated:e}){const t=Ua("notifications:getMyNotifications",e?{}:"skip"),n=Ua("notifications:getUnreadCount",e?{}:"skip");return{notifications:t??[],unreadCount:n??0,isLoading:e&&t===void 0}}function cfn(){const e=_n("notifications:markAsRead"),t=_n("notifications:markAllAsRead"),n=_n("notifications:clearAllNotifications");return{markAsRead:e,markAllAsRead:t,clearAllNotifications:n}}function dfn(e){const n=Date.now()-e,r=Math.floor(n/1e3),i=Math.floor(r/60),a=Math.floor(i/60),s=Math.floor(a/24);return s>0?`${s}d ago`:a>0?`${a}h ago`:i>0?`${i}m ago`:"just now"}function ffn(e){return e.startsWith("workspace")?l.jsx(mJe,{className:"h-4 w-4"}):l.jsx($q,{className:"h-4 w-4"})}function pfn(e){const{type:t,entityName:n,actorName:r}=e,i=r||"Someone";switch(t){case"workspace_added":return`${i} added you to workspace "${n}"`;case"workspace_removed":return`${i} removed you from workspace "${n}"`;case"organization_added":return`${i} added you to organization "${n}"`;case"organization_removed":return`${i} removed you from organization "${n}"`;default:return"You have a new notification"}}function hfn({notification:e,onMarkAsRead:t}){const n=()=>{e.isRead||t(e._id)};return l.jsxs("div",{className:Ie("flex items-start gap-3 p-3 border-b last:border-b-0 cursor-pointer transition-colors hover:bg-muted/50",!e.isRead&&"bg-muted/30"),onClick:n,children:[l.jsx("div",{className:Ie("flex items-center justify-center h-8 w-8 rounded-full shrink-0",e.type.includes("added")?"bg-success/10 text-success":"bg-destructive/10 text-destructive"),children:ffn(e.type)}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm leading-tight",children:pfn(e)}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:dfn(e.createdAt)})]}),!e.isRead&&l.jsx("div",{className:"h-2 w-2 rounded-full bg-info shrink-0 mt-1.5"})]})}function mfn(){const{isAuthenticated:e}=Ba(),{notifications:t,unreadCount:n,isLoading:r}=ufn({isAuthenticated:e}),{markAsRead:i,markAllAsRead:a,clearAllNotifications:s}=cfn(),o=async f=>{try{await i({notificationId:f})}catch(p){console.error("Failed to mark notification as read:",p)}},u=async()=>{try{await a({})}catch(f){console.error("Failed to mark all notifications as read:",f)}},c=async()=>{try{await s({})}catch(f){console.error("Failed to clear notifications:",f)}};if(!e)return null;const d=n>9?"9+":n;return l.jsxs(qo,{children:[l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"icon",className:"relative","aria-label":`Notifications${n>0?` (${n} unread)`:""}`,children:[l.jsx(EXe,{className:"h-5 w-5"}),n>0&&l.jsx("span",{className:"absolute -top-0.5 -right-0.5 flex items-center justify-center h-4 min-w-4 px-1 text-[10px] font-medium bg-destructive text-destructive-foreground rounded-full",children:d})]})}),l.jsxs(Ho,{className:"w-80 p-0",align:"end",side:"bottom",sideOffset:8,children:[l.jsxs("div",{className:"flex items-center justify-between p-3 border-b",children:[l.jsx("h4",{className:"font-semibold text-sm",children:"Notifications"}),l.jsxs("div",{className:"flex items-center gap-1",children:[n>0&&l.jsx(Ee,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-xs",onClick:u,children:"Mark all read"}),t.length>0&&l.jsx(Ee,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-xs text-destructive hover:text-destructive",onClick:c,children:"Clear all"})]})]}),l.jsx(Es,{className:"h-[300px]",children:r?l.jsx("div",{className:"flex items-center justify-center h-20",children:l.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):t.length===0?l.jsxs("div",{className:"flex flex-col items-center justify-center h-40 text-muted-foreground",children:[l.jsx(IJe,{className:"h-8 w-8 mb-2"}),l.jsx("p",{className:"text-sm",children:"No notifications yet"})]}):l.jsx("div",{children:t.map(f=>l.jsx(hfn,{notification:f,onMarkAsRead:o},f._id))})})]})]})}function gfn({activeServerSelectorProps:e}){const{user:t,signIn:n,signUp:r}=Aa(),{isLoading:i}=Ba(),a=ci(),s=eo(d=>d.themeMode),o=eo(d=>d.setThemeMode),u=()=>{const d=s==="dark"?"light":"dark";RZ(d),o(d)},c=l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Ee,{asChild:!0,size:"icon",variant:"ghost",children:l.jsxs("a",{href:"https://discord.gg/JEnDtz8X6z",target:"_blank",rel:"noreferrer","aria-label":"Join the Discord community",title:"Join the Discord community",children:[l.jsx(Bze,{className:"h-10 w-10"}),l.jsx("span",{className:"sr-only",children:"Discord"})]})}),l.jsx(Ee,{asChild:!0,size:"icon",variant:"ghost",children:l.jsxs("a",{href:"https://github.com/MCPJam/inspector",target:"_blank",rel:"noreferrer","aria-label":"Visit the GitHub repository",title:"Visit the GitHub repository",children:[l.jsx(qze,{className:"h-10 w-10"}),l.jsx("span",{className:"sr-only",children:"GitHub"})]})})]});return l.jsxs("div",{className:"ml-auto flex h-full flex-1 items-center gap-2 no-drag min-w-0",children:[e&&l.jsx("div",{className:"flex-1 min-w-0 h-full pr-2",children:l.jsx(lfn,{...e,className:"h-full"})}),l.jsxs("div",{className:"ml-auto flex items-center gap-2 shrink-0",children:[l.jsx(Ee,{size:"icon",variant:"ghost",onClick:u,"aria-label":s==="dark"?"Switch to light mode":"Switch to dark mode",title:s==="dark"?"Switch to light mode":"Switch to dark mode",children:s==="dark"?l.jsx(z1e,{className:"h-5 w-5"}):l.jsx($1e,{className:"h-5 w-5"})}),l.jsx(mfn,{}),c,!t&&!i&&l.jsxs(l.Fragment,{children:[l.jsx(Ee,{variant:"outline",size:"sm",onClick:()=>{a.capture("login_button_clicked",{location:"header",platform:Et(),environment:void 0}),n()},children:"Sign in"}),l.jsx(Ee,{size:"sm",onClick:()=>{a.capture("sign_up_button_clicked",{location:"header",platform:Et(),environment:void 0}),r()},children:"Create account"})]})]})]})}const vfn=[{id:"ipc-2025-app-builder-1-1-1",render:({dismiss:e})=>l.jsx("div",{className:"no-drag bg-orange-200 px-4 py-2 text-gray-900 lg:px-6",children:l.jsxs("div",{className:"flex items-center justify-between gap-4",children:[l.jsxs("div",{className:"flex items-center gap-4 flex-1",children:[l.jsx("p",{className:"text-sm font-normal leading-snug",children:"Try the new App Builder for ChatGPT Apps and MCP Apps"}),l.jsx("a",{href:"#app-builder",onClick:e,className:"text-sm font-normal text-orange-700 hover:text-orange-800 underline underline-offset-2",children:"Try it now"})]}),l.jsx(Ee,{size:"sm",variant:"ghost",onClick:e,className:"hover:bg-orange-200 p-1 h-8 w-8",children:l.jsx(Yn,{className:"h-5 w-5"})})]})})}],Hze="inspector.header-ipc.dismissed",yfn=e=>{if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(t){return console.warn("Failed to parse stored IPC state",t),[]}},eve=()=>{if(typeof window>"u")return new Set;const e=window.localStorage.getItem(Hze);return new Set(yfn(e))},xfn=e=>{typeof window>"u"||window.localStorage.setItem(Hze,JSON.stringify([...e]))},bfn=()=>{const[e,t]=b.useState(null);b.useEffect(()=>{const r=eve(),i=vfn.find(a=>!r.has(a.id))??null;t(i)},[]);const n=b.useCallback(()=>{if(!e)return;const r=eve();r.add(e.id),xfn(r),t(null)},[e]);return{activeIpc:e,dismissActiveIpc:n}};function _fn({activeWorkspaceId:e,workspaces:t,onSwitchWorkspace:n,onCreateWorkspace:r,onUpdateWorkspace:i,onDeleteWorkspace:a,isLoading:s}){if(s)return l.jsx("div",{className:"flex items-center gap-1",children:l.jsx(nI,{className:"h-8 w-32"})});const o=t[e],u=Object.values(t).sort((f,p)=>f.isDefault?-1:p.isDefault?1:f.name.localeCompare(p.name)),c=()=>{let f="New workspace",p=f,m=1;const y=Object.values(t).map(v=>v.name.toLowerCase());for(;y.includes(p.toLowerCase());)m++,p=`${f} ${m}`;r(p,!0)},d=f=>{i(e,{name:f})};return l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Wj,{value:o?.name||"No Workspace",onSave:d,className:"px-3 py-2 text-m font-semibold",placeholder:"Workspace name"}),l.jsxs(Ic,{children:[l.jsx(jc,{asChild:!0,children:l.jsx(Ee,{variant:"ghost",size:"sm",className:"h-auto p-1",children:l.jsx(Wr,{className:"h-4 w-4 opacity-50"})})}),l.jsxs(Oc,{align:"start",className:"w-[240px]",children:[u.map(f=>l.jsxs(Oi,{className:Ie("cursor-pointer group flex items-center justify-between",f.id===e&&"bg-accent"),onClick:()=>n(f.id),children:[l.jsx("span",{className:"truncate flex-1",children:f.name}),l.jsx("button",{onClick:p=>{p.stopPropagation(),p.preventDefault(),a(f.id)},className:"opacity-0 group-hover:opacity-100 hover:text-destructive transition-opacity p-1",children:l.jsx(Ll,{className:"h-4 w-4"})})]},f.id)),l.jsx(uC,{}),l.jsxs(Oi,{onClick:c,className:"cursor-pointer",children:[l.jsx(_o,{className:"mr-2 h-4 w-4"}),"Add Workspace"]})]})]})]})}function tve({isOpen:e,onClose:t,workspaceName:n,workspaceServers:r,sharedWorkspaceId:i,currentUser:a,onWorkspaceShared:s,onLeaveWorkspace:o}){const[u,c]=b.useState(""),[d,f]=b.useState(!1),[p,m]=b.useState(!1),{isAuthenticated:y}=Ba(),{profilePictureUrl:v}=BP(),{createWorkspace:x,addMember:_,removeMember:S}=T6e(),{activeMembers:w,pendingMembers:T}=E6e({isAuthenticated:y,workspaceId:i||null}),N=!i||w.some(O=>O.email.toLowerCase()===a.email?.toLowerCase()&&O.isOwner);b.useEffect(()=>{e&&Tr.capture("share_dialog_opened",{workspace_name:n,is_already_shared:!!i,member_count:w.length+T.length,platform:Et(),environment:void 0})},[e]);const E=async()=>{if(u.trim()){f(!0);try{let O=i;if(!O){const U=PC(r);O=await x({name:n,servers:U}),O&&s?.(O)}const R=await _({workspaceId:O,email:u.trim()});R.isPending?Pe.success(`Invitation sent to ${u}. They'll get access once they sign up.`):Pe.success(`${u} has been added to the workspace.`),c(""),Tr.capture("workspace_invite_sent",{workspace_name:n,is_new_share:!i,is_pending:R.isPending,platform:Et(),environment:void 0})}catch(O){Pe.error(O.message||"Failed to add member")}finally{f(!1)}}},A=async O=>{if(i)try{await S({workspaceId:i,email:O}),Pe.success("Member removed"),Tr.capture("workspace_member_removed",{workspace_name:n,platform:Et(),environment:void 0})}catch(R){Pe.error(R.message||"Failed to remove member")}},I=async()=>{if(!(!i||!a.email)){m(!0);try{await S({workspaceId:i,email:a.email}),Pe.success("You have left the workspace"),Tr.capture("workspace_left",{workspace_name:n,platform:Et(),environment:void 0}),t(),o?.()}catch(O){Pe.error(O.message||"Failed to leave workspace")}finally{m(!1)}}},M=[a.firstName,a.lastName].filter(Boolean).join(" ")||"You",$=Pm(M);return l.jsx(si,{open:e,onOpenChange:O=>!O&&t(),children:l.jsxs(oi,{className:"sm:max-w-[480px]",children:[l.jsx(vi,{children:l.jsxs(yi,{children:['Share "',n,'"']})}),l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-sm font-medium",children:"Invite with email"}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Ct,{placeholder:"Enter email address",value:u,onChange:O=>c(O.target.value),onKeyDown:O=>O.key==="Enter"&&E(),className:"flex-1"}),l.jsx(Ee,{onClick:E,disabled:!u.trim()||d,children:d?"...":"Invite"})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-sm font-medium",children:i?"People with access":"Only you have access"}),l.jsxs("div",{className:"space-y-1 max-h-[300px] overflow-y-auto",children:[!i&&l.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-md",children:[l.jsxs(kc,{className:"size-9",children:[l.jsx(Ec,{src:v,alt:M}),l.jsx(Tc,{className:"text-sm",children:$})]}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("p",{className:"text-sm font-medium truncate",children:M}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"(you)"})]}),l.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.email})]})]}),w.map(O=>{const R=O.user?.name||O.email,U=O.email,z=Pm(R),F=U.toLowerCase()===a.email?.toLowerCase(),D=N&&!F;return l.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50",children:[l.jsxs(kc,{className:"size-9",children:[l.jsx(Ec,{src:O.user?.imageUrl||void 0,alt:R}),l.jsx(Tc,{className:"text-sm",children:z})]}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("p",{className:"text-sm font-medium truncate",children:R}),F&&l.jsx("span",{className:"text-xs text-muted-foreground",children:"(you)"})]}),l.jsx("p",{className:"text-xs text-muted-foreground truncate",children:U})]}),D&&l.jsx(Ee,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-muted-foreground hover:text-destructive",onClick:()=>A(U),children:l.jsx(Yn,{className:"size-4"})})]},O._id)}),T.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"pt-2 pb-1",children:l.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Pending (awaiting signup)"})}),T.map(O=>l.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50",children:[l.jsx("div",{className:"size-9 rounded-full bg-muted flex items-center justify-center",children:l.jsx(Sw,{className:"size-4 text-muted-foreground"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm font-medium truncate",children:O.email}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Invited - waiting for signup"})]}),N&&l.jsx(Ee,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>A(O.email),children:l.jsx(Yn,{className:"size-4"})})]},O._id))]})]})]}),i&&!N&&l.jsxs(Ee,{variant:"outline",className:"w-full text-destructive hover:text-destructive hover:bg-destructive/10",onClick:I,disabled:p,children:[l.jsx(Uq,{className:"size-4 mr-2"}),p?"Leaving...":"Leave workspace"]})]})]})})}function wfn({workspaceName:e,workspaceServers:t,sharedWorkspaceId:n,onWorkspaceShared:r,onLeaveWorkspace:i}){const{isAuthenticated:a}=Ba(),{user:s}=Aa(),{profilePictureUrl:o}=BP(),[u,c]=b.useState(!1),{activeMembers:d,isLoading:f}=E6e({isAuthenticated:a,workspaceId:n??null});if(!a||!s)return null;if(!n){const y=[s.firstName,s.lastName].filter(Boolean).join(" "),v=Pm(y);return l.jsxs("div",{className:"flex items-center",children:[l.jsxs("button",{onClick:()=>c(!0),className:"flex -space-x-2 hover:opacity-80 transition-opacity",children:[l.jsxs(kc,{className:"size-8 border-2 border-background",children:[l.jsx(Ec,{src:o,alt:y}),l.jsx(Tc,{className:"text-xs",children:v})]}),l.jsx("div",{className:"size-8 rounded-full border-2 border-background bg-muted flex items-center justify-center hover:bg-accent transition-colors",children:l.jsx(DM,{className:"size-3.5 text-muted-foreground"})})]}),l.jsx(tve,{isOpen:u,onClose:()=>c(!1),workspaceName:e,workspaceServers:t,sharedWorkspaceId:n,currentUser:s,onWorkspaceShared:r,onLeaveWorkspace:i})]})}if(f)return l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("div",{className:"flex -space-x-2",children:l.jsx("div",{className:"size-8 rounded-full bg-muted animate-pulse"})})});const p=d.slice(0,4),m=d.length-4;return l.jsxs("div",{className:"flex items-center",children:[l.jsxs("button",{onClick:()=>c(!0),className:"flex -space-x-2 hover:opacity-80 transition-opacity",children:[p.map(y=>{const v=y.user?.name||y.email,x=Pm(v);return l.jsxs(kc,{className:Ie("size-8 border-2 border-background ring-0","hover:z-10 transition-transform hover:scale-105"),children:[l.jsx(Ec,{src:y.user?.imageUrl||void 0,alt:v}),l.jsx(Tc,{className:"text-xs",children:x})]},y._id)}),l.jsx("div",{className:"size-8 rounded-full border-2 border-background bg-muted flex items-center justify-center hover:bg-accent transition-colors relative",children:m>0?l.jsxs(l.Fragment,{children:[l.jsx(DM,{className:"size-3.5 text-muted-foreground"}),l.jsx("span",{className:"absolute -top-1 -right-1 size-4 rounded-full bg-primary text-[10px] font-medium text-primary-foreground flex items-center justify-center",children:m>9?"9+":`+${m}`})]}):l.jsx(DM,{className:"size-3.5 text-muted-foreground"})})]}),l.jsx(tve,{isOpen:u,onClose:()=>c(!1),workspaceName:e,workspaceServers:t,sharedWorkspaceId:n,currentUser:s,onWorkspaceShared:r,onLeaveWorkspace:i})]})}const Sfn=({workspaces:e,activeWorkspaceId:t,onSwitchWorkspace:n,onCreateWorkspace:r,onUpdateWorkspace:i,onDeleteWorkspace:a,onLeaveWorkspace:s,onWorkspaceShared:o,activeServerSelectorProps:u,isLoadingWorkspaces:c})=>{const{activeIpc:d,dismissActiveIpc:f}=bfn(),p=e[t],m=()=>{s(t)};return l.jsxs("header",{className:"flex shrink-0 flex-col border-b transition-[width,height] ease-linear",children:[l.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-2 px-4 lg:px-6 drag",children:[l.jsxs("div",{className:"flex items-center gap-1 lg:gap-2 no-drag",children:[l.jsx(lnn,{className:"-ml-1"}),l.jsx(_fn,{activeWorkspaceId:t,workspaces:e,onSwitchWorkspace:n,onCreateWorkspace:r,onUpdateWorkspace:i,onDeleteWorkspace:a,isLoading:c}),l.jsx(wfn,{workspaceName:p?.name||"Workspace",workspaceServers:p?.servers||{},sharedWorkspaceId:p?.sharedWorkspaceId,onWorkspaceShared:o,onLeaveWorkspace:m})]}),l.jsx(gfn,{activeServerSelectorProps:u})]}),d&&d.render({dismiss:f})]})};function kfn(){const[e,t]=b.useState("servers"),[n,r]=b.useState(void 0),[i,a]=b.useState(!1),[s,o]=b.useState(new Set),u=ci(),{isAuthenticated:c,isLoading:d}=Ba();rfn(),b.useEffect(()=>{d||u.capture("app_launched",{platform:Et(),environment:void 0,user_agent:navigator.userAgent,version:"1.5.13",is_authenticated:c})},[d,c]);const f=FWt(),p=BWt();b.useEffect(()=>{RZ(f),qWt(p)},[]),Pnn(),nfn();const m=b.useMemo(()=>window.location.pathname.startsWith("/oauth/callback/debug"),[]),y=b.useMemo(()=>window.location.pathname==="/callback",[]),{appState:v,isLoading:x,isLoadingRemoteWorkspaces:_,workspaceServers:S,connectedOrConnectingServerConfigs:w,selectedMCPConfig:T,handleConnect:N,handleDisconnect:E,handleReconnect:A,handleUpdate:I,handleRemoveServer:M,setSelectedServer:$,toggleServerSelection:O,setSelectedMultipleServersToAllServers:R,workspaces:U,activeWorkspaceId:z,handleSwitchWorkspace:F,handleCreateWorkspace:D,handleUpdateWorkspace:W,handleDeleteWorkspace:q,handleLeaveWorkspace:X,handleWorkspaceShared:L,saveServerConfigWithoutConnecting:Y,handleConnectWithTokensFromOAuthFlow:G,handleRefreshTokensFromOAuthFlow:P}=Cnn(),V=b.useMemo(()=>({...v,workspaces:U,activeWorkspaceId:z}),[v,U,z]),Q=U[z]?.sharedWorkspaceId??null,{viewsByServer:oe}=xK({isAuthenticated:c,workspaceId:Q}),{serversById:re}=bK({isAuthenticated:c,workspaceId:Q}),ee=b.useMemo(()=>{const se=new Set;for(const ie of oe.keys()){const he=re.get(ie);he&&se.add(he)}return se},[oe,re]),le=b.useMemo(()=>Object.entries(w).filter(([,se])=>se.connectionStatus==="connected").map(([se])=>se).sort().join(","),[w]);b.useEffect(()=>{(async()=>{const ie=Object.entries(w).filter(([,ye])=>ye.connectionStatus==="connected").map(([ye])=>ye),he=new Set;await Promise.all(ie.map(async ye=>{try{const Ne=await _g({serverId:ye});(aR(Ne)||iR(Ne)||sR(Ne))&&he.add(ye)}catch(Ne){console.debug(`Failed to check OpenAI apps for server ${ye}:`,Ne)}})),o(he)})()},[le]),b.useEffect(()=>{const se=()=>{const ie=(window.location.hash||"#servers").replace("#",""),ye=(ie.startsWith("/")?ie.slice(1):ie).split("/"),Ne=ye[0];ye[0]==="organizations"&&ye[1]?r(ye[1]):r(void 0);const ce=Ne==="registry"?"servers":Ne;t(ce),(ce==="chat"||ce==="chat-v2")&&R(),ce!=="chat-v2"&&a(!1)};return se(),window.addEventListener("hashchange",se),()=>window.removeEventListener("hashchange",se)},[R]);const te=se=>{(se==="chat"||se==="chat-v2")&&R(),se!=="chat-v2"&&a(!1),window.location.hash=se,t(se)};if(m)return l.jsx(Vtn,{});if(y)return b.useEffect(()=>{const se=setTimeout(()=>{window.location.href="/"},5e3);return()=>clearTimeout(se)},[]),l.jsx(ifn,{});if(x)return l.jsx(afn,{});const ne=e==="tools"||e==="resources"||e==="prompts"||e==="tasks"||e==="oauth-flow"||e==="chat"||e==="chat-v2"||e==="app-builder"||e==="evals"||e==="views"?{serverConfigs:e==="oauth-flow"?v.servers:e==="views"?S:w,selectedServer:v.selectedServer,onServerChange:$,onConnect:N,onReconnect:A,isMultiSelectEnabled:e==="chat"||e==="chat-v2",onMultiServerToggle:O,selectedMultipleServers:v.selectedMultipleServers,showOnlyOAuthServers:e==="oauth-flow",showOnlyOpenAIAppsServers:e==="app-builder",openAiAppOrMcpAppsServers:s,showOnlyServersWithViews:e==="views",serversWithViews:ee,hasMessages:e==="chat-v2"?i:!1}:void 0,J=l.jsxs(snn,{defaultOpen:!0,children:[l.jsx(bnn,{onNavigate:te,activeTab:e,servers:S}),l.jsxs(unn,{className:"flex flex-col min-h-0",children:[l.jsx(Sfn,{workspaces:U,activeWorkspaceId:z,onSwitchWorkspace:F,onCreateWorkspace:D,onUpdateWorkspace:W,onDeleteWorkspace:q,onLeaveWorkspace:X,onWorkspaceShared:L,activeServerSelectorProps:ne,isLoadingWorkspaces:_}),l.jsxs("div",{className:"flex flex-1 min-h-0 flex-col overflow-hidden h-full",children:[e==="servers"&&l.jsx(O0t,{connectedOrConnectingServerConfigs:S,onConnect:N,onDisconnect:E,onReconnect:A,onUpdate:I,onRemove:M,isLoadingWorkspaces:_}),e==="tools"&&l.jsx("div",{className:"h-full overflow-hidden",children:l.jsx(gyt,{serverConfig:T,serverName:v.selectedServer})}),e==="evals"&&l.jsx(DWt,{selectedServer:v.selectedServer}),e==="views"&&l.jsx(KWt,{selectedServer:v.selectedServer}),e==="resources"&&l.jsx("div",{className:"h-full overflow-hidden",children:l.jsx(Syt,{serverConfig:T,serverName:v.selectedServer})}),e==="prompts"&&l.jsx("div",{className:"h-full overflow-hidden",children:l.jsx(Tyt,{serverConfig:T,serverName:v.selectedServer})}),e==="skills"&&l.jsx(uIt,{}),l.jsx("div",{className:e==="tasks"?"h-full overflow-hidden":"hidden",children:l.jsx(vIt,{serverConfig:T,serverName:v.selectedServer,isActive:e==="tasks"})}),e==="auth"&&l.jsx(uKt,{serverConfig:T,serverEntry:v.servers[v.selectedServer],serverName:v.selectedServer}),e==="oauth-flow"&&l.jsx(ytn,{serverConfigs:v.servers,selectedServerName:v.selectedServer,onSelectServer:$,onSaveServerConfig:Y,onConnectWithTokens:G,onRefreshTokens:P}),e==="chat-v2"&&l.jsx(jPt,{connectedOrConnectingServerConfigs:w,selectedServerNames:v.selectedMultipleServers,onHasMessagesChange:a}),e==="tracing"&&l.jsx(iKt,{}),e==="app-builder"&&l.jsx(Ltn,{serverConfig:T,serverName:v.selectedServer}),e==="settings"&&l.jsx(rKt,{}),e==="profile"&&l.jsx(ztn,{}),e==="organizations"&&l.jsx(Ftn,{organizationId:n})]})]})]});return l.jsx(BOt,{themeMode:f,themePreset:p,children:l.jsxs(C0t,{appState:V,children:[l.jsx(Rnn,{}),J]})})}function Efn({children:e,client:t,useAuth:n}){const r=Tfn(n);return l.jsx(jFe,{client:t,useAuth:r,children:e})}function Tfn(e){return b.useMemo(()=>function(){const{isLoading:n,user:r,getAccessToken:i}=e(),a=b.useCallback(async()=>{try{return await i()}catch{return null}},[i]);return b.useMemo(()=>({isLoading:n,isAuthenticated:!!r,fetchAccessToken:a}),[n,r,a])},[e])}const Nfn={environment:"prod",sendDefaultPii:!1,tracesSampleRate:.1,tracePropagationTargets:["localhost",/^\//,/^https?:\/\/[^/]*\.convex\.(cloud|site)/]},Cfn={...Nfn,dsn:"https://c9df3785c734acfe9dad2d0c1e963e28@o4510109778378752.ingest.us.sentry.io/4510111435063296",replaysSessionSampleRate:.1,replaysOnErrorSampleRate:1};function Afn(){tfn({...Cfn,integrations:[zdn(),Xdn()]})}function Ifn(){return l.jsx("div",{className:"flex items-center justify-center h-screen p-5 font-sans bg-neutral-50 text-neutral-800 dark:bg-neutral-900 dark:text-neutral-200",children:l.jsxs("div",{className:"max-w-[400px] leading-relaxed text-center",children:[l.jsxs("p",{className:"mb-3",children:[l.jsx("strong",{children:"Router issue:"})," Your app uses"," ",l.jsx("code",{className:"bg-neutral-200 dark:bg-neutral-700 px-1.5 py-0.5 rounded text-[0.9em]",children:"BrowserRouter"}),", which isn't supported in iframes."]}),l.jsxs("p",{className:"text-sm opacity-70",children:["Switch to"," ",l.jsx("code",{className:"bg-neutral-200 dark:bg-neutral-700 px-1.5 py-0.5 rounded text-[0.9em]",children:"MemoryRouter"})," ","or"," ",l.jsx("code",{className:"bg-neutral-200 dark:bg-neutral-700 px-1.5 py-0.5 rounded text-[0.9em]",children:"HashRouter"})," ","instead, then re-run your tool."]})]})})}Afn();const jfn=(()=>{try{return window.self!==window.top}catch{return!0}})();if(jfn)fee.createRoot(document.getElementById("root")).render(l.jsx(b.StrictMode,{children:l.jsx(Ifn,{})}));else{const e="https://outstanding-fennec-304.convex.cloud",t="client_01K4C1TVPBE7JTBFQJF9SDW9P9",n=(()=>{const o="mcpjam://oauth/callback";return typeof window>"u"?o:window.location.protocol==="http:"||window.location.protocol==="https:"?`${window.location.origin}/callback`:o})(),r={apiHostname:"api.mcpjam.com"},i=new SFe(e),a=l.jsx(_0t,{clientId:t,redirectUri:n,...r,children:l.jsx(Efn,{client:i,useAuth:Aa,children:l.jsx(kfn,{})})});async function s(){const o=fee.createRoot(document.getElementById("root"));try{await Ket(),console.log("[Auth] Session token initialized")}catch(u){console.error("[Auth] Failed to initialize session token:",u),o.render(l.jsx(b.StrictMode,{children:l.jsxs("div",{style:{padding:"2rem",textAlign:"center",fontFamily:"system-ui",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"100vh"},children:[l.jsx("img",{src:"/mcp_jam.svg",alt:"MCPJam Logo",style:{width:"120px",height:"auto",marginBottom:"1.5rem"}}),l.jsx("h1",{style:{color:"#dc2626",marginBottom:"0.5rem"},children:"Authentication Error"}),l.jsx("p",{style:{marginBottom:"0.25rem"},children:"Failed to establish secure session."}),l.jsx("p",{style:{color:"#666",fontSize:"0.875rem"},children:"If accessing via network, use localhost instead."}),l.jsx("button",{onClick:()=>location.reload(),style:{marginTop:"1.5rem",padding:"0.75rem 1.5rem",cursor:"pointer",backgroundColor:"#18181b",color:"#fff",border:"none",borderRadius:"0.5rem",fontSize:"1rem",fontWeight:500},children:"Restart App"})]})}));return}o.render(l.jsx(b.StrictMode,{children:l.jsx(brt,{apiKey:Nrt(),options:Crt(),children:a})}))}s()}const Ofn=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:NRe},Symbol.toStringTag,{value:"Module"}));export{pAt as I,Ul as L,Hpn as Z,cn as g,l as j,b as r};
|
|
1943
|
-
//# sourceMappingURL=index-
|
|
1942
|
+
`;if(typeof e=="string")n=`${r}${e}`;else{const a=new TextEncoder().encode(r);n=new Uint8Array(a.length+e.length),n.set(a),n.set(e,a.length)}return n}async function Odn({client:e,scope:t,replayId:n,event:r}){const i=typeof e._integrations=="object"&&e._integrations!==null&&!Array.isArray(e._integrations)?Object.keys(e._integrations):void 0,a={event_id:n,integrations:i};e.emit("preprocessEvent",r,a);const s=await uLe(e.getOptions(),r,a,t,e,Yl());if(!s)return null;s.platform=s.platform||"javascript";const o=e.getSdkMetadata(),{name:u,version:c}=o&&o.sdk||{};return s.sdk={...s.sdk,name:u||"sentry.javascript.unknown",version:c||"0.0.0"},s}async function Rdn({recordingData:e,replayId:t,segmentId:n,eventContext:r,timestamp:i,session:a}){const s=jdn({recordingData:e,headers:{segment_id:n}}),{urls:o,errorIds:u,traceIds:c,initialTimestamp:d}=r,f=Xn(),p=ui(),m=f&&f.getTransport(),y=f&&f.getDsn();if(!f||!m||!y||!a.sampled)return df({});const v={type:dln,replay_start_timestamp:d/1e3,timestamp:i/1e3,error_ids:u,trace_ids:c,urls:o,replay_id:t,segment_id:n,replay_type:a.sampled},x=await Odn({scope:p,client:f,replayId:t,event:v});if(!x)return f.recordDroppedEvent("event_processor","replay",v),tn&&on.info("An event processor returned `null`, will not send event."),df({});delete x.sdkProcessingMetadata;const _=Idn(x,s,y,f.getOptions().tunnel);let S;try{S=await m.send(_)}catch(T){const N=new Error(mY);try{N.cause=T}catch{}throw N}if(typeof S.statusCode=="number"&&(S.statusCode<200||S.statusCode>=300))throw new Lze(S.statusCode);const w=xLe({},S);if(yLe(w,"replay"))throw new CY(w);return S}class Lze extends Error{constructor(t){super(`Transport returned status code ${t}`)}}class CY extends Error{constructor(t){super("Rate limit hit"),this.rateLimits=t}}async function zze(e,t={count:0,interval:vln}){const{recordingData:n,onError:r}=e;if(n.length)try{return await Rdn(e),!0}catch(i){if(i instanceof Lze||i instanceof CY)throw i;if(fLe("Replays",{_retryCount:t.count}),r&&r(i),t.count>=yln){const a=new Error(`${mY} - max retries exceeded`);try{a.cause=i}catch{}throw a}return t.interval*=++t.count,new Promise((a,s)=>{dx(async()=>{try{await zze(e,t),a(!0)}catch(o){s(o)}},t.interval)})}}const Uze="__THROTTLED",Pdn="__SKIPPED";function $dn(e,t,n){const r=new Map,i=o=>{const u=o-n;r.forEach((c,d)=>{d<u&&r.delete(d)})},a=()=>[...r.values()].reduce((o,u)=>o+u,0);let s=!1;return(...o)=>{const u=Math.floor(Date.now()/1e3);if(i(u),a()>=t){const d=s;return s=!0,d?Pdn:Uze}s=!1;const c=r.get(u)||0;return r.set(u,c+1),e(...o)}}class gp{constructor({options:t,recordingOptions:n}){gp.prototype.__init.call(this),gp.prototype.__init2.call(this),gp.prototype.__init3.call(this),gp.prototype.__init4.call(this),gp.prototype.__init5.call(this),gp.prototype.__init6.call(this),this.eventBuffer=null,this.performanceEntries=[],this.replayPerformanceEntries=[],this.recordingMode="session",this.timeouts={sessionIdlePause:fln,sessionIdleExpire:pln},this._lastActivity=Date.now(),this._isEnabled=!1,this._isPaused=!1,this._requiresManualStart=!1,this._hasInitializedCoreListeners=!1,this._context={errorIds:new Set,traceIds:new Set,urls:[],initialTimestamp:Date.now(),initialUrl:""},this._recordingOptions=n,this._options=t,this._debouncedFlush=Edn(()=>this._flush(),this._options.flushMinDelay,{maxWait:this._options.flushMaxDelay}),this._throttledAddEvent=$dn((s,o)=>Icn(this,s,o),300,5);const{slowClickTimeout:r,slowClickIgnoreSelectors:i}=this.getOptions(),a=r?{threshold:Math.min(xln,r),timeout:r,scrollTimeout:bln,ignoreSelector:i?i.join(","):""}:void 0;if(a&&(this.clickDetector=new Bun(this,a)),tn){const s=t._experiments;on.setConfig({captureExceptions:!!s.captureExceptions,traceInternals:!!s.traceInternals})}}getContext(){return this._context}isEnabled(){return this._isEnabled}isPaused(){return this._isPaused}isRecordingCanvas(){return!!this._canvas}getOptions(){return this._options}handleException(t){tn&&on.exception(t),this._options.onError&&this._options.onError(t)}initializeSampling(t){const{errorSampleRate:n,sessionSampleRate:r}=this._options,i=n<=0&&r<=0;if(this._requiresManualStart=i,!i){if(this._initializeSessionForSampling(t),!this.session){tn&&on.exception(new Error("Unable to initialize and create session"));return}this.session.sampled!==!1&&(this.recordingMode=this.session.sampled==="buffer"&&this.session.segmentId===0?"buffer":"session",tn&&on.infoTick(`Starting replay in ${this.recordingMode} mode`),this._initializeRecording())}}start(){if(this._isEnabled&&this.recordingMode==="session"){tn&&on.info("Recording is already in progress");return}if(this._isEnabled&&this.recordingMode==="buffer"){tn&&on.info("Buffering is in progress, call `flush()` to save the replay");return}tn&&on.infoTick("Starting replay in session mode"),this._updateUserActivity();const t=W8({maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire},{stickySession:this._options.stickySession,sessionSampleRate:1,allowBuffering:!1});this.session=t,this._initializeRecording()}startBuffering(){if(this._isEnabled){tn&&on.info("Buffering is in progress, call `flush()` to save the replay");return}tn&&on.infoTick("Starting replay in buffer mode");const t=W8({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration},{stickySession:this._options.stickySession,sessionSampleRate:0,allowBuffering:!0});this.session=t,this.recordingMode="buffer",this._initializeRecording()}startRecording(){try{const t=this._canvas;this._stopRecording=Jd({...this._recordingOptions,...this.recordingMode==="buffer"?{checkoutEveryNms:gln}:this._options._experiments.continuousCheckout&&{checkoutEveryNms:Math.max(36e4,this._options._experiments.continuousCheckout)},emit:Ndn(this),...Tdn(),onMutation:this._onMutationHandler,...t?{recordCanvas:t.recordCanvas,getCanvasManager:t.getCanvasManager,sampling:t.sampling,dataURLOptions:t.dataURLOptions}:{}})}catch(t){this.handleException(t)}}stopRecording(){try{return this._stopRecording&&(this._stopRecording(),this._stopRecording=void 0),!0}catch(t){return this.handleException(t),!1}}async stop({forceFlush:t=!1,reason:n}={}){if(this._isEnabled){this._isEnabled=!1;try{tn&&on.info(`Stopping Replay${n?` triggered by ${n}`:""}`),Ize(),this._removeListeners(),this.stopRecording(),this._debouncedFlush.cancel(),t&&await this._flush({force:!0}),this.eventBuffer&&this.eventBuffer.destroy(),this.eventBuffer=null,Ecn(this)}catch(r){this.handleException(r)}}}pause(){this._isPaused||(this._isPaused=!0,this.stopRecording(),tn&&on.info("Pausing replay"))}resume(){!this._isPaused||!this._checkSession()||(this._isPaused=!1,this.startRecording(),tn&&on.info("Resuming replay"))}async sendBufferedReplayOrFlush({continueRecording:t=!0}={}){if(this.recordingMode==="session")return this.flushImmediate();const n=Date.now();tn&&on.info("Converting buffer to session"),await this.flushImmediate();const r=this.stopRecording();!t||!r||this.recordingMode!=="session"&&(this.recordingMode="session",this.session&&(this._updateUserActivity(n),this._updateSessionActivity(n),this._maybeSaveSession()),this.startRecording())}addUpdate(t){const n=t();this.recordingMode!=="buffer"&&n!==!0&&this._debouncedFlush()}triggerUserActivity(){if(this._updateUserActivity(),!this._stopRecording){if(!this._checkSession())return;this.resume();return}this.checkAndHandleExpiredSession(),this._updateSessionActivity()}updateUserActivity(){this._updateUserActivity(),this._updateSessionActivity()}conditionalFlush(){return this.recordingMode==="buffer"?Promise.resolve():this.flushImmediate()}flush(){return this._debouncedFlush()}flushImmediate(){return this._debouncedFlush(),this._debouncedFlush.flush()}cancelFlush(){this._debouncedFlush.cancel()}getSessionId(){return this.session&&this.session.id}checkAndHandleExpiredSession(){if(this._lastActivity&&I9(this._lastActivity,this.timeouts.sessionIdlePause)&&this.session&&this.session.sampled==="session"){this.pause();return}return!!this._checkSession()}setInitialState(){const t=`${ni.location.pathname}${ni.location.hash}${ni.location.search}`,n=`${ni.location.origin}${t}`;this.performanceEntries=[],this.replayPerformanceEntries=[],this._clearContext(),this._context.initialUrl=n,this._context.initialTimestamp=Date.now(),this._context.urls.push(n)}throttledAddEvent(t,n){const r=this._throttledAddEvent(t,n);if(r===Uze){const i=bc({category:"replay.throttled"});this.addUpdate(()=>!TY(this,{type:$un,timestamp:i.timestamp||0,data:{tag:"breadcrumb",payload:i,metric:!0}}))}return r}getCurrentRoute(){const t=this.lastActiveSpan||Va(),n=t&&cs(t),i=(n&&fr(n).data||{})[xc];if(!(!n||!i||!["route","custom"].includes(i)))return fr(n).description}_initializeRecording(){this.setInitialState(),this._updateSessionActivity(),this.eventBuffer=wcn({useCompression:this._options.useCompression,workerUrl:this._options.workerUrl}),this._removeListeners(),this._addListeners(),this._isEnabled=!0,this._isPaused=!1,this.startRecording()}_initializeSessionForSampling(t){const n=this._options.errorSampleRate>0,r=W8({sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration,previousSessionId:t},{stickySession:this._options.stickySession,sessionSampleRate:this._options.sessionSampleRate,allowBuffering:n});this.session=r}_checkSession(){if(!this.session)return!1;const t=this.session;return Tze(t,{sessionIdleExpire:this.timeouts.sessionIdleExpire,maxReplayDuration:this._options.maxReplayDuration})?(this._refreshSession(t),!1):!0}async _refreshSession(t){this._isEnabled&&(await this.stop({reason:"refresh session"}),this.initializeSampling(t.id))}_addListeners(){try{ni.document.addEventListener("visibilitychange",this._handleVisibilityChange),ni.addEventListener("blur",this._handleWindowBlur),ni.addEventListener("focus",this._handleWindowFocus),ni.addEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.addListeners(),this._hasInitializedCoreListeners||(wdn(this),this._hasInitializedCoreListeners=!0)}catch(t){this.handleException(t)}this._performanceCleanupCallback=mcn(this)}_removeListeners(){try{ni.document.removeEventListener("visibilitychange",this._handleVisibilityChange),ni.removeEventListener("blur",this._handleWindowBlur),ni.removeEventListener("focus",this._handleWindowFocus),ni.removeEventListener("keydown",this._handleKeyboardEvent),this.clickDetector&&this.clickDetector.removeListeners(),this._performanceCleanupCallback&&this._performanceCleanupCallback()}catch(t){this.handleException(t)}}__init(){this._handleVisibilityChange=()=>{ni.document.visibilityState==="visible"?this._doChangeToForegroundTasks():this._doChangeToBackgroundTasks()}}__init2(){this._handleWindowBlur=()=>{const t=bc({category:"ui.blur"});this._doChangeToBackgroundTasks(t)}}__init3(){this._handleWindowFocus=()=>{const t=bc({category:"ui.focus"});this._doChangeToForegroundTasks(t)}}__init4(){this._handleKeyboardEvent=t=>{tcn(this,t)}}_doChangeToBackgroundTasks(t){!this.session||Eze(this.session,{maxReplayDuration:this._options.maxReplayDuration,sessionIdleExpire:this.timeouts.sessionIdleExpire})||(t&&this._createCustomBreadcrumb(t),this.conditionalFlush())}_doChangeToForegroundTasks(t){if(!this.session)return;if(!this.checkAndHandleExpiredSession()){tn&&on.info("Document has become active, but session has expired");return}t&&this._createCustomBreadcrumb(t)}_updateUserActivity(t=Date.now()){this._lastActivity=t}_updateSessionActivity(t=Date.now()){this.session&&(this.session.lastActivity=t,this._maybeSaveSession())}_createCustomBreadcrumb(t){this.addUpdate(()=>{this.throttledAddEvent({type:On.Custom,timestamp:t.timestamp||0,data:{tag:"breadcrumb",payload:t}})})}_addPerformanceEntries(){let t=acn(this.performanceEntries).concat(this.replayPerformanceEntries);if(this.performanceEntries=[],this.replayPerformanceEntries=[],this._requiresManualStart){const n=this._context.initialTimestamp/1e3;t=t.filter(r=>r.start>=n)}return Promise.all(r4(this,t))}_clearContext(){this._context.errorIds.clear(),this._context.traceIds.clear(),this._context.urls=[]}_updateInitialTimestampFromEventBuffer(){const{session:t,eventBuffer:n}=this;if(!t||!n||this._requiresManualStart||t.segmentId)return;const r=n.getEarliestTimestamp();r&&r<this._context.initialTimestamp&&(this._context.initialTimestamp=r)}_popEventContext(){const t={initialTimestamp:this._context.initialTimestamp,initialUrl:this._context.initialUrl,errorIds:Array.from(this._context.errorIds),traceIds:Array.from(this._context.traceIds),urls:this._context.urls};return this._clearContext(),t}async _runFlush(){const t=this.getSessionId();if(!this.session||!this.eventBuffer||!t){tn&&on.error("No session or eventBuffer found to flush.");return}if(await this._addPerformanceEntries(),!(!this.eventBuffer||!this.eventBuffer.hasEvents)&&(await Sdn(this),!!this.eventBuffer&&t===this.getSessionId()))try{this._updateInitialTimestampFromEventBuffer();const n=Date.now();if(n-this._context.initialTimestamp>this._options.maxReplayDuration+3e4)throw new Error("Session is too long, not sending replay");const r=this._popEventContext(),i=this.session.segmentId++;this._maybeSaveSession();const a=await this.eventBuffer.finish();await zze({replayId:t,recordingData:a,segmentId:i,eventContext:r,session:this.session,timestamp:n,onError:s=>this.handleException(s)})}catch(n){this.handleException(n),this.stop({reason:"sendReplay"});const r=Xn();if(r){const i=n instanceof CY?"ratelimit_backoff":"send_error";r.recordDroppedEvent(i,"replay")}}}__init5(){this._flush=async({force:t=!1}={})=>{if(!this._isEnabled&&!t)return;if(!this.checkAndHandleExpiredSession()){tn&&on.error("Attempting to finish replay event after session expired.");return}if(!this.session)return;const n=this.session.started,i=Date.now()-n;this._debouncedFlush.cancel();const a=i<this._options.minReplayDuration,s=i>this._options.maxReplayDuration+5e3;if(a||s){tn&&on.info(`Session duration (${Math.floor(i/1e3)}s) is too ${a?"short":"long"}, not sending replay.`),a&&this._debouncedFlush();return}const o=this.eventBuffer;o&&this.session.segmentId===0&&!o.hasCheckout&&tn&&on.info("Flushing initial segment without checkout.");const u=!!this._flushLock;this._flushLock||(this._flushLock=this._runFlush());try{await this._flushLock}catch(c){this.handleException(c)}finally{this._flushLock=void 0,u&&this._debouncedFlush()}}}_maybeSaveSession(){this.session&&this._options.stickySession&&EY(this.session)}__init6(){this._onMutationHandler=t=>{const n=t.length,r=this._options.mutationLimit,i=this._options.mutationBreadcrumbLimit,a=r&&n>r;if(n>i||a){const s=bc({category:"replay.mutations",data:{count:n,limit:a}});this._createCustomBreadcrumb(s)}return a?(this.stop({reason:"mutationLimit",forceFlush:this.recordingMode==="session"}),!1):!0}}}function V_(e,t){return[...e,...t].join(",")}function Mdn({mask:e,unmask:t,block:n,unblock:r,ignore:i}){const a=["base","iframe[srcdoc]:not([src])"],s=V_(e,[".sentry-mask","[data-sentry-mask]"]),o=V_(t,[]);return{maskTextSelector:s,unmaskTextSelector:o,blockSelector:V_(n,[".sentry-block","[data-sentry-block]",...a]),unblockSelector:V_(r,[]),ignoreSelector:V_(i,[".sentry-ignore","[data-sentry-ignore]",'input[type="file"]'])}}function Ddn({el:e,key:t,maskAttributes:n,maskAllText:r,privacyOptions:i,value:a}){return!r||i.unmaskTextSelector&&e.matches(i.unmaskTextSelector)?a:n.includes(t)||t==="value"&&e.tagName==="INPUT"&&["submit","button"].includes(e.getAttribute("type")||"")?a.replace(/[\S]/g,"*"):a}const K0e='img,image,svg,video,object,picture,embed,map,audio,link[rel="icon"],link[rel="apple-touch-icon"]',Ldn=["content-length","content-type","accept"];let Z0e=!1;const zdn=(e=>new a4(e));class a4{static __initStatic(){this.id="Replay"}constructor({flushMinDelay:t=hln,flushMaxDelay:n=mln,minReplayDuration:r=_ln,maxReplayDuration:i=N0e,stickySession:a=!0,useCompression:s=!0,workerUrl:o,_experiments:u={},maskAllText:c=!0,maskAllInputs:d=!0,blockAllMedia:f=!0,mutationBreadcrumbLimit:p=750,mutationLimit:m=1e4,slowClickTimeout:y=7e3,slowClickIgnoreSelectors:v=[],networkDetailAllowUrls:x=[],networkDetailDenyUrls:_=[],networkCaptureBodies:S=!0,networkRequestHeaders:w=[],networkResponseHeaders:T=[],mask:N=[],maskAttributes:E=["title","placeholder"],unmask:A=[],block:I=[],unblock:M=[],ignore:$=[],maskFn:O,beforeAddRecordingEvent:R,beforeErrorSampling:U,onError:z}={}){this.name=a4.id;const F=Mdn({mask:N,unmask:A,block:I,unblock:M,ignore:$});if(this._recordingOptions={maskAllInputs:d,maskAllText:c,maskInputOptions:{password:!0},maskTextFn:O,maskInputFn:O,maskAttributeFn:(D,W,q)=>Ddn({maskAttributes:E,maskAllText:c,privacyOptions:F,key:D,value:W,el:q}),...F,slimDOMOptions:"all",inlineStylesheet:!0,inlineImages:!1,collectFonts:!0,errorHandler:D=>{try{D.__rrweb__=!0}catch{}}},this._initialOptions={flushMinDelay:t,flushMaxDelay:n,minReplayDuration:Math.min(r,wln),maxReplayDuration:Math.min(i,N0e),stickySession:a,useCompression:s,workerUrl:o,blockAllMedia:f,maskAllInputs:d,maskAllText:c,mutationBreadcrumbLimit:p,mutationLimit:m,slowClickTimeout:y,slowClickIgnoreSelectors:v,networkDetailAllowUrls:x,networkDetailDenyUrls:_,networkCaptureBodies:S,networkRequestHeaders:Y0e(w),networkResponseHeaders:Y0e(T),beforeAddRecordingEvent:R,beforeErrorSampling:U,onError:z,_experiments:u},this._initialOptions.blockAllMedia&&(this._recordingOptions.blockSelector=this._recordingOptions.blockSelector?`${this._recordingOptions.blockSelector},${K0e}`:K0e),this._isInitialized&&v0e())throw new Error("Multiple Sentry Session Replay instances are not supported");this._isInitialized=!0}get _isInitialized(){return Z0e}set _isInitialized(t){Z0e=t}afterAllSetup(t){!v0e()||this._replay||(this._setup(t),this._initialize(t))}start(){this._replay&&this._replay.start()}startBuffering(){this._replay&&this._replay.startBuffering()}stop(){return this._replay?this._replay.stop({forceFlush:this._replay.recordingMode==="session"}):Promise.resolve()}flush(t){return this._replay?this._replay.isEnabled()?this._replay.sendBufferedReplayOrFlush(t):(this._replay.start(),Promise.resolve()):Promise.resolve()}getReplayId(){if(!(!this._replay||!this._replay.isEnabled()))return this._replay.getSessionId()}getRecordingMode(){if(!(!this._replay||!this._replay.isEnabled()))return this._replay.recordingMode}_initialize(t){this._replay&&(this._maybeLoadFromReplayCanvasIntegration(t),this._replay.initializeSampling())}_setup(t){const n=Udn(this._initialOptions,t);this._replay=new gp({options:n,recordingOptions:this._recordingOptions})}_maybeLoadFromReplayCanvasIntegration(t){try{const n=t.getIntegrationByName("ReplayCanvas");if(!n)return;this._replay._canvas=n.getOptions()}catch{}}}a4.__initStatic();function Udn(e,t){const n=t.getOptions(),r={sessionSampleRate:0,errorSampleRate:0,...Na(e)},i=Jj(n.replaysSessionSampleRate),a=Jj(n.replaysOnErrorSampleRate);return i==null&&a==null&&yh(()=>{console.warn("Replay is disabled because neither `replaysSessionSampleRate` nor `replaysOnErrorSampleRate` are set.")}),i!=null&&(r.sessionSampleRate=i),a!=null&&(r.errorSampleRate=a),r}function Y0e(e){return[...Ldn,...e.map(t=>t.toLowerCase())]}const X0e=new WeakMap,K8=new Map,BC={traceFetch:!0,traceXHR:!0,enableHTTPTimings:!0,trackFetchStreamPerformance:!1};function Fdn(e,t){const{traceFetch:n,traceXHR:r,trackFetchStreamPerformance:i,shouldCreateSpanForRequest:a,enableHTTPTimings:s,tracePropagationTargets:o}={traceFetch:BC.traceFetch,traceXHR:BC.traceXHR,trackFetchStreamPerformance:BC.trackFetchStreamPerformance,...t},u=typeof a=="function"?a:f=>!0,c=f=>Hdn(f,o),d={};n&&(e.addEventProcessor(f=>(f.type==="transaction"&&f.spans&&f.spans.forEach(p=>{if(p.op==="http.client"){const m=K8.get(p.span_id);m&&(p.timestamp=m/1e3,K8.delete(p.span_id))}}),f)),i&&jan(f=>{if(f.response){const p=X0e.get(f.response);p&&f.endTimestamp&&K8.set(p,f.endTimestamp)}}),NLe(f=>{const p=kan(f,u,c,d);if(f.response&&f.fetchData.__span&&X0e.set(f.response,f.fetchData.__span),p){const m=Fze(f.fetchData.url),y=m?Om(m).host:void 0;p.setAttributes({"http.url":m,"server.address":y})}s&&p&&J0e(p)})),r&&WLe(f=>{const p=Vdn(f,u,c,d);s&&p&&J0e(p)})}function Bdn(e){return e.entryType==="resource"&&"initiatorType"in e&&typeof e.nextHopProtocol=="string"&&(e.initiatorType==="fetch"||e.initiatorType==="xmlhttprequest")}function J0e(e){const{url:t}=fr(e).data||{};if(!t||typeof t!="string")return;const n=cx("resource",({entries:r})=>{r.forEach(i=>{Bdn(i)&&i.name.endsWith(t)&&(qdn(i).forEach(s=>e.setAttribute(...s)),setTimeout(n))})})}function Qu(e=0){return((to||performance.timeOrigin)+e)/1e3}function qdn(e){const{name:t,version:n}=HLe(e.nextHopProtocol),r=[];return r.push(["network.protocol.version",n],["network.protocol.name",t]),to?[...r,["http.request.redirect_start",Qu(e.redirectStart)],["http.request.fetch_start",Qu(e.fetchStart)],["http.request.domain_lookup_start",Qu(e.domainLookupStart)],["http.request.domain_lookup_end",Qu(e.domainLookupEnd)],["http.request.connect_start",Qu(e.connectStart)],["http.request.secure_connection_start",Qu(e.secureConnectionStart)],["http.request.connection_end",Qu(e.connectEnd)],["http.request.request_start",Qu(e.requestStart)],["http.request.response_start",Qu(e.responseStart)],["http.request.response_end",Qu(e.responseEnd)]]:r}function Hdn(e,t){const n=hn.location&&hn.location.href;if(n){let r,i;try{r=new URL(e,n),i=new URL(n).origin}catch{return!1}const a=r.origin===i;return t?Dp(r.toString(),t)||a&&Dp(r.pathname,t):a}else{const r=!!e.match(/^\/(?!\/)/);return t?Dp(e,t):r}}function Vdn(e,t,n,r){const i=e.xhr,a=i&&i[ym];if(!i||i.__sentry_own_request__||!a)return;const s=Xp()&&t(a.url);if(e.endTimestamp&&s){const f=i.__sentry_xhr_span_id__;if(!f)return;const p=r[f];p&&a.status_code!==void 0&&(B6e(p,a.status_code),p.end(),delete r[f]);return}const o=Fze(a.url),u=o?Om(o).host:void 0,c=!!Va(),d=s&&c?Nk({name:`${a.method} ${a.url}`,attributes:{type:"xhr","http.method":a.method,"http.url":o,url:a.url,"server.address":u,[Fa]:"auto.http.browser",[vg]:"http.client"}}):new Yx;return i.__sentry_xhr_span_id__=d.spanContext().spanId,r[i.__sentry_xhr_span_id__]=d,n(a.url)&&Gdn(i,Xp()&&c?d:void 0),d}function Gdn(e,t){const{"sentry-trace":n,baggage:r}=_Le({span:t});n&&Wdn(e,n,r)}function Wdn(e,t,n){try{e.setRequestHeader("sentry-trace",t),n&&e.setRequestHeader("baggage",n)}catch{}}function Fze(e){try{return new URL(e,hn.location.origin).href}catch{return}}function Kdn(){hn&&hn.document?hn.document.addEventListener("visibilitychange",()=>{const e=Va();if(!e)return;const t=cs(e);if(hn.document.hidden&&t){const n="cancelled",{op:r,status:i}=fr(t);Lc&&bt.log(`[Tracing] Transaction: ${n} -> since tab moved to the background, op: ${r}`),i||t.setStatus({code:Ma,message:n}),t.setAttribute("sentry.cancellation_reason","document.hidden"),t.end()}}):Lc&&bt.warn("[Tracing] Could not set up background tab detection due to lack of global document")}const Zdn="BrowserTracing",Ydn={...DC,instrumentNavigation:!0,instrumentPageLoad:!0,markBackgroundSpan:!0,enableLongTask:!0,enableLongAnimationFrame:!0,enableInp:!0,_experiments:{},...BC},Xdn=((e={})=>{Crn();const{enableInp:t,enableLongTask:n,enableLongAnimationFrame:r,_experiments:{enableInteractions:i,enableStandaloneClsSpans:a},beforeStartSpan:s,idleTimeout:o,finalTimeout:u,childSpanTimeout:c,markBackgroundSpan:d,traceFetch:f,traceXHR:p,trackFetchStreamPerformance:m,shouldCreateSpanForRequest:y,enableHTTPTimings:v,instrumentPageLoad:x,instrumentNavigation:_}={...Ydn,...e},S=Usn({recordClsStandaloneSpans:a||!1});t&&don(),r&&nr.PerformanceObserver&&PerformanceObserver.supportedEntryTypes&&PerformanceObserver.supportedEntryTypes.includes("long-animation-frame")?Bsn():n&&Fsn(),i&&qsn();const w={name:void 0,source:void 0};function T(N,E){const A=E.op==="pageload",I=s?s(E):E,M=I.attributes||{};E.name!==I.name&&(M[xc]="custom",I.attributes=M),w.name=I.name,w.source=M[xc];const $=lLe(I,{idleTimeout:o,finalTimeout:u,childSpanTimeout:c,disableAutoFinish:A,beforeSpanEnd:R=>{S(),Ksn(R,{recordClsOnPageloadSpan:!a})}});function O(){["interactive","complete"].includes(hn.document.readyState)&&N.emit("idleSpanEnableAutoFinish",$)}return A&&hn.document&&(hn.document.addEventListener("readystatechange",()=>{O()}),O()),$}return{name:Zdn,afterAllSetup(N){let E,A=hn.location&&hn.location.href;function I(){E&&!fr(E).timestamp&&(Lc&&bt.log(`[Tracing] Finishing current active span with op: ${fr(E).op}`),E.end())}N.on("startNavigationSpan",M=>{Xn()===N&&(I(),E=T(N,{op:"navigation",...M}))}),N.on("startPageLoadSpan",(M,$={})=>{if(Xn()!==N)return;I();const O=$.sentryTrace||Q0e("sentry-trace"),R=$.baggage||Q0e("baggage"),U=_rn(O,R);ui().setPropagationContext(U),E=T(N,{op:"pageload",...M})}),N.on("spanEnd",M=>{const $=fr(M).op;if(M!==cs(M)||$!=="navigation"&&$!=="pageload")return;const O=ui(),R=O.getPropagationContext();O.setPropagationContext({...R,sampled:R.sampled!==void 0?R.sampled:Lg(M),dsc:R.dsc||zg(M)})}),hn.location&&(x&&Jdn(N,{name:hn.location.pathname,startTime:to?to/1e3:void 0,attributes:{[xc]:"url",[Fa]:"auto.pageload.browser"}}),_&&JP(({to:M,from:$})=>{if($===void 0&&A&&A.indexOf(M)!==-1){A=void 0;return}$!==M&&(A=void 0,Qdn(N,{name:hn.location.pathname,attributes:{[xc]:"url",[Fa]:"auto.navigation.browser"}}))})),d&&Kdn(),i&&efn(o,u,c,w),t&&pon(),Fdn(N,{traceFetch:f,traceXHR:p,trackFetchStreamPerformance:m,tracePropagationTargets:N.getOptions().tracePropagationTargets,shouldCreateSpanForRequest:y,enableHTTPTimings:v})}}});function Jdn(e,t,n){e.emit("startPageLoadSpan",t,n),ui().setTransactionName(t.name);const r=Va();return(r&&fr(r).op)==="pageload"?r:void 0}function Qdn(e,t){Yl().setPropagationContext({traceId:Zp()}),ui().setPropagationContext({traceId:Zp()}),e.emit("startNavigationSpan",t),ui().setTransactionName(t.name);const n=Va();return(n&&fr(n).op)==="navigation"?n:void 0}function Q0e(e){const t=Wnn(`meta[name=${e}]`);return t?t.getAttribute("content"):void 0}function efn(e,t,n,r){let i;const a=()=>{const s="ui.action.click",o=Va(),u=o&&cs(o);if(u){const c=fr(u).op;if(["navigation","pageload"].includes(c)){Lc&&bt.warn(`[Tracing] Did not create ${s} span because a pageload or navigation span is in progress.`);return}}if(i&&(i.setAttribute(s9,"interactionInterrupted"),i.end(),i=void 0),!r.name){Lc&&bt.warn(`[Tracing] Did not create ${s} transaction because _latestRouteName is missing.`);return}i=lLe({name:r.name,op:s,attributes:{[xc]:r.source||"url"}},{idleTimeout:e,finalTimeout:t,childSpanTimeout:n})};hn.document&&addEventListener("click",a,{once:!1,capture:!0})}function tfn(e){const t={...e};return bLe(t,"react"),fLe("react",{version:b.version}),cln(t)}function nfn(){const{user:e}=Aa(),{isAuthenticated:t,isLoading:n}=Ba(),r=_n("users:ensureUser"),i=b.useRef(null);b.useEffect(()=>{t||(i.current=null,r0e(null))},[t]),b.useEffect(()=>{if(!n){if(!t&&e)throw console.log("useEnsureDbUser: not authenticated"),new Error("Not authenticated");t&&e&&i.current!==e.id&&r().then(a=>{i.current=e.id,r0e({id:e.id})}).catch(a=>{console.error("[auth] ensureUser failed",a),i.current=null})}},[t,n,e,r])}function rfn(){const e=ci(),{user:t}=Aa(),{isAuthenticated:n}=Ba();b.useEffect(()=>{e&&(n&&t?(e.identify(t.id,{email:t.email,name:t.firstName&&t.lastName?`${t.firstName} ${t.lastName}`:t.email,first_name:t.firstName,last_name:t.lastName}),e.register({user_id:t.id})):e.reset())},[e,n,t])}function ifn(){return l.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:l.jsxs("div",{className:"text-center",children:[l.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-primary mx-auto"}),l.jsx("p",{className:"mt-4 text-muted-foreground",children:"Completing sign in..."})]})})}function afn(){return l.jsx("div",{className:"min-h-screen bg-background flex items-center justify-center",children:l.jsx("div",{className:"text-center",children:l.jsx("div",{className:"animate-spin rounded-full h-12 w-12 border-4 border-gray-200 border-t-primary mx-auto"})})})}const Bze=de.forwardRef(({className:e,...t},n)=>l.jsx("svg",{ref:n,xmlns:"http://www.w3.org/2000/svg",viewBox:"0 0 50 50",fill:"currentColor",className:e,...t,children:l.jsx("path",{d:"M 41.625 10.769531 C 37.644531 7.566406 31.347656 7.023438 31.078125 7.003906 C 30.660156 6.96875 30.261719 7.203125 30.089844 7.589844 C 30.074219 7.613281 29.9375 7.929688 29.785156 8.421875 C 32.417969 8.867188 35.652344 9.761719 38.578125 11.578125 C 39.046875 11.867188 39.191406 12.484375 38.902344 12.953125 C 38.710938 13.261719 38.386719 13.429688 38.050781 13.429688 C 37.871094 13.429688 37.6875 13.378906 37.523438 13.277344 C 32.492188 10.15625 26.210938 10 25 10 C 23.789063 10 17.503906 10.15625 12.476563 13.277344 C 12.007813 13.570313 11.390625 13.425781 11.101563 12.957031 C 10.808594 12.484375 10.953125 11.871094 11.421875 11.578125 C 14.347656 9.765625 17.582031 8.867188 20.214844 8.425781 C 20.0625 7.929688 19.925781 7.617188 19.914063 7.589844 C 19.738281 7.203125 19.34375 6.960938 18.921875 7.003906 C 18.652344 7.023438 12.355469 7.566406 8.320313 10.8125 C 6.214844 12.761719 2 24.152344 2 34 C 2 34.175781 2.046875 34.34375 2.132813 34.496094 C 5.039063 39.605469 12.972656 40.941406 14.78125 41 C 14.789063 41 14.800781 41 14.8125 41 C 15.132813 41 15.433594 40.847656 15.621094 40.589844 L 17.449219 38.074219 C 12.515625 36.800781 9.996094 34.636719 9.851563 34.507813 C 9.4375 34.144531 9.398438 33.511719 9.765625 33.097656 C 10.128906 32.683594 10.761719 32.644531 11.175781 33.007813 C 11.234375 33.0625 15.875 37 25 37 C 34.140625 37 38.78125 33.046875 38.828125 33.007813 C 39.242188 32.648438 39.871094 32.683594 40.238281 33.101563 C 40.601563 33.515625 40.5625 34.144531 40.148438 34.507813 C 40.003906 34.636719 37.484375 36.800781 32.550781 38.074219 L 34.378906 40.589844 C 34.566406 40.847656 34.867188 41 35.1875 41 C 35.199219 41 35.210938 41 35.21875 41 C 37.027344 40.941406 44.960938 39.605469 47.867188 34.496094 C 47.953125 34.34375 48 34.175781 48 34 C 48 24.152344 43.785156 12.761719 41.625 10.769531 Z M 18.5 30 C 16.566406 30 15 28.210938 15 26 C 15 23.789063 16.566406 22 18.5 22 C 20.433594 22 22 23.789063 22 26 C 22 28.210938 20.433594 30 18.5 30 Z M 31.5 30 C 29.566406 30 28 28.210938 28 26 C 28 23.789063 29.566406 22 31.5 22 C 33.433594 22 35 23.789063 35 26 C 35 28.210938 33.433594 30 31.5 30 Z"})}));Bze.displayName="DiscordIcon";const qze=de.forwardRef(({className:e,...t},n)=>l.jsx("svg",{ref:n,viewBox:"0 0 24 24",fill:"currentColor",className:e,...t,children:l.jsx("path",{d:"M12 .5C5.73.5.5 5.73.5 12.02c0 5.1 3.29 9.42 7.86 10.95.58.11.79-.25.79-.56 0-.28-.01-1.02-.02-2-3.2.69-3.88-1.54-3.88-1.54-.53-1.35-1.29-1.71-1.29-1.71-1.05-.72.08-.7.08-.7 1.17.08 1.78 1.2 1.78 1.2 1.04 1.78 2.72 1.26 3.38.97.1-.76.41-1.26.75-1.55-2.55-.29-5.24-1.28-5.24-5.69 0-1.26.45-2.29 1.19-3.09-.12-.29-.52-1.45.11-3.02 0 0 .97-.31 3.18 1.18a11.1 11.1 0 0 1 5.79 0c2.2-1.49 3.17-1.18 3.17-1.18.63 1.57.23 2.73.11 3.02.74.8 1.18 1.83 1.18 3.09 0 4.42-2.69 5.39-5.25 5.67.42.36.8 1.1.8 2.22 0 1.6-.01 2.88-.01 3.27 0 .31.21.68.8.56 4.56-1.54 7.85-5.86 7.85-10.95C23.5 5.73 18.27.5 12 .5Z"})}));qze.displayName="GitHubIcon";function sfn(e){switch(e){case"connected":return"bg-green-500 dark:bg-green-400";case"connecting":return"bg-yellow-500 dark:bg-yellow-400 animate-pulse";case"failed":return"bg-red-500 dark:bg-red-400";case"disconnected":return"bg-muted-foreground";default:return"bg-muted-foreground"}}function ofn(e){switch(e){case"connected":return"Connected";case"connecting":return"Connecting...";case"failed":return"Failed";case"disconnected":return"Disconnected";default:return"Unknown"}}function lfn({serverConfigs:e,selectedServer:t,selectedMultipleServers:n,isMultiSelectEnabled:r,onServerChange:i,onMultiServerToggle:a,onConnect:s,onReconnect:o,showOnlyOAuthServers:u=!1,showOnlyOpenAIAppsServers:c=!1,openAiAppOrMcpAppsServers:d,showOnlyServersWithViews:f=!1,serversWithViews:p,hasMessages:m=!1,className:y}){const[v,x]=b.useState(!1),[_,S]=b.useState(!1),[w,T]=b.useState(null),[N,E]=b.useState(!1),[A,I]=b.useState(!1),M=b.useRef(null),$=ci(),O=W=>"url"in W.config?!!(W.oauthTokens||qH(W.name)||W.connectionStatus==="oauth-flow"):!1,R=Object.entries(e).filter(([W,q])=>!(u&&!O(q)||c&&d&&!d.has(W)||f&&p&&!p.has(W)));b.useEffect(()=>{if(r)return;const W=R.map(([X])=>X);!W.includes(t)&&W.length>0&&i(W[0])},[R.length,t,r,i]);const U=W=>{if(r){if(m){T(W),S(!0);return}a(W)}else{if(t!==W&&m){T(W),S(!0);return}i(W)}},z=()=>{w&&(r?a(w):i(w),T(null)),S(!1)},F=()=>{T(null),S(!1)};b.useEffect(()=>{const W=M.current;if(!W)return;const q=()=>{E(W.scrollLeft>0),I(W.scrollLeft+W.clientWidth<W.scrollWidth-1)};return q(),W.addEventListener("scroll",q,{passive:!0}),window.addEventListener("resize",q),()=>{W.removeEventListener("scroll",q),window.removeEventListener("resize",q)}},[R.length]);const D=W=>{const q=M.current;if(!q)return;const X=200,L=W==="left"?Math.max(0,q.scrollLeft-X):Math.min(q.scrollWidth-q.clientWidth,q.scrollLeft+X);q.scrollTo({left:L,behavior:"smooth"})};return l.jsx("div",{className:Ie("relative h-full w-full min-w-0",y),children:l.jsxs("div",{ref:M,className:Ie("w-full h-full min-w-0 overflow-x-auto scrollbar-hidden","flex justify-start"),children:[l.jsxs("div",{className:"flex flex-nowrap min-w-fit h-full",children:[R.map(([W,q])=>{const X=r?n.includes(W):t===W;return l.jsxs("button",{onClick:L=>{L.target.closest("[data-reconnect-button]")||U(W)},className:Ie("group relative flex h-full items-center gap-3 px-4 border-r border-border transition-all duration-200 cursor-pointer outline-none focus-visible:bg-accent focus-visible:text-accent-foreground","hover:bg-accent hover:text-accent-foreground",X?"bg-muted text-foreground":"bg-background text-foreground"),children:[r&&l.jsx("div",{className:Ie("w-4 h-4 rounded border-2 flex items-center justify-center transition-colors",X?"bg-primary border-primary text-primary-foreground":"border-muted-foreground/30 hover:border-primary/50"),children:X&&l.jsx(xi,{className:"w-3 h-3"})}),l.jsx("div",{className:Ie("w-2 h-2 rounded-full",sfn(q.connectionStatus)),title:ofn(q.connectionStatus)}),l.jsx("span",{className:"text-sm font-medium truncate max-w-36",children:W}),l.jsx("div",{className:"text-xs opacity-70",children:q.config.command?"STDIO":"HTTP"}),o&&l.jsx("div",{role:"button",tabIndex:0,"data-reconnect-button":!0,onClick:L=>{L.stopPropagation(),L.nativeEvent.stopImmediatePropagation(),L.preventDefault(),o(W)},className:"ml-auto p-1 rounded-md hover:bg-muted-foreground/20 text-muted-foreground hover:text-foreground transition-colors",title:"Reconnect",children:l.jsx(wn,{className:"w-3 h-3"})})]},W)}),l.jsxs("button",{onClick:()=>{x(!0)},className:Ie("group relative flex h-full items-center gap-3 px-4 border-r border-border transition-all duration-200 cursor-pointer","hover:bg-accent hover:text-accent-foreground","bg-background text-muted-foreground border-dashed"),children:[r&&l.jsx("div",{className:"w-4 h-4"}),l.jsx("span",{className:"text-sm font-medium",children:"Add Server"}),l.jsx("div",{className:"text-xs opacity-70",children:"+"})]})]}),l.jsx(uIe,{isOpen:v,onClose:()=>x(!1),onSubmit:W=>{$.capture("connecting_server",{location:"active_server_selector",platform:Et(),environment:void 0}),s(W)}}),l.jsx(hK,{open:_,onConfirm:z,onCancel:F,message:"Changing server selection will cause the chat to reset. This action cannot be undone."}),N&&l.jsx("button",{className:"absolute left-0 top-0 h-full px-3 flex items-center bg-gradient-to-r from-background via-background/95 to-background/40 cursor-pointer",onClick:()=>D("left"),"aria-label":"Scroll left",children:l.jsx(Dq,{className:"h-5 w-5"})}),A&&l.jsx("button",{className:"absolute right-0 top-0 h-full px-3 flex items-center bg-gradient-to-l from-background via-background/95 to-background/40 cursor-pointer",onClick:()=>D("right"),"aria-label":"Scroll right",children:l.jsx(wr,{className:"h-5 w-5"})})]})})}function ufn({isAuthenticated:e}){const t=Ua("notifications:getMyNotifications",e?{}:"skip"),n=Ua("notifications:getUnreadCount",e?{}:"skip");return{notifications:t??[],unreadCount:n??0,isLoading:e&&t===void 0}}function cfn(){const e=_n("notifications:markAsRead"),t=_n("notifications:markAllAsRead"),n=_n("notifications:clearAllNotifications");return{markAsRead:e,markAllAsRead:t,clearAllNotifications:n}}function dfn(e){const n=Date.now()-e,r=Math.floor(n/1e3),i=Math.floor(r/60),a=Math.floor(i/60),s=Math.floor(a/24);return s>0?`${s}d ago`:a>0?`${a}h ago`:i>0?`${i}m ago`:"just now"}function ffn(e){return e.startsWith("workspace")?l.jsx(mJe,{className:"h-4 w-4"}):l.jsx($q,{className:"h-4 w-4"})}function pfn(e){const{type:t,entityName:n,actorName:r}=e,i=r||"Someone";switch(t){case"workspace_added":return`${i} added you to workspace "${n}"`;case"workspace_removed":return`${i} removed you from workspace "${n}"`;case"organization_added":return`${i} added you to organization "${n}"`;case"organization_removed":return`${i} removed you from organization "${n}"`;default:return"You have a new notification"}}function hfn({notification:e,onMarkAsRead:t}){const n=()=>{e.isRead||t(e._id)};return l.jsxs("div",{className:Ie("flex items-start gap-3 p-3 border-b last:border-b-0 cursor-pointer transition-colors hover:bg-muted/50",!e.isRead&&"bg-muted/30"),onClick:n,children:[l.jsx("div",{className:Ie("flex items-center justify-center h-8 w-8 rounded-full shrink-0",e.type.includes("added")?"bg-success/10 text-success":"bg-destructive/10 text-destructive"),children:ffn(e.type)}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm leading-tight",children:pfn(e)}),l.jsx("p",{className:"text-xs text-muted-foreground mt-1",children:dfn(e.createdAt)})]}),!e.isRead&&l.jsx("div",{className:"h-2 w-2 rounded-full bg-info shrink-0 mt-1.5"})]})}function mfn(){const{isAuthenticated:e}=Ba(),{notifications:t,unreadCount:n,isLoading:r}=ufn({isAuthenticated:e}),{markAsRead:i,markAllAsRead:a,clearAllNotifications:s}=cfn(),o=async f=>{try{await i({notificationId:f})}catch(p){console.error("Failed to mark notification as read:",p)}},u=async()=>{try{await a({})}catch(f){console.error("Failed to mark all notifications as read:",f)}},c=async()=>{try{await s({})}catch(f){console.error("Failed to clear notifications:",f)}};if(!e)return null;const d=n>9?"9+":n;return l.jsxs(qo,{children:[l.jsx(Sl,{asChild:!0,children:l.jsxs(Ee,{variant:"ghost",size:"icon",className:"relative","aria-label":`Notifications${n>0?` (${n} unread)`:""}`,children:[l.jsx(EXe,{className:"h-5 w-5"}),n>0&&l.jsx("span",{className:"absolute -top-0.5 -right-0.5 flex items-center justify-center h-4 min-w-4 px-1 text-[10px] font-medium bg-destructive text-destructive-foreground rounded-full",children:d})]})}),l.jsxs(Ho,{className:"w-80 p-0",align:"end",side:"bottom",sideOffset:8,children:[l.jsxs("div",{className:"flex items-center justify-between p-3 border-b",children:[l.jsx("h4",{className:"font-semibold text-sm",children:"Notifications"}),l.jsxs("div",{className:"flex items-center gap-1",children:[n>0&&l.jsx(Ee,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-xs",onClick:u,children:"Mark all read"}),t.length>0&&l.jsx(Ee,{variant:"ghost",size:"sm",className:"h-auto py-1 px-2 text-xs text-destructive hover:text-destructive",onClick:c,children:"Clear all"})]})]}),l.jsx(Es,{className:"h-[300px]",children:r?l.jsx("div",{className:"flex items-center justify-center h-20",children:l.jsx("p",{className:"text-sm text-muted-foreground",children:"Loading..."})}):t.length===0?l.jsxs("div",{className:"flex flex-col items-center justify-center h-40 text-muted-foreground",children:[l.jsx(IJe,{className:"h-8 w-8 mb-2"}),l.jsx("p",{className:"text-sm",children:"No notifications yet"})]}):l.jsx("div",{children:t.map(f=>l.jsx(hfn,{notification:f,onMarkAsRead:o},f._id))})})]})]})}function gfn({activeServerSelectorProps:e}){const{user:t,signIn:n,signUp:r}=Aa(),{isLoading:i}=Ba(),a=ci(),s=eo(d=>d.themeMode),o=eo(d=>d.setThemeMode),u=()=>{const d=s==="dark"?"light":"dark";RZ(d),o(d)},c=l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Ee,{asChild:!0,size:"icon",variant:"ghost",children:l.jsxs("a",{href:"https://discord.gg/JEnDtz8X6z",target:"_blank",rel:"noreferrer","aria-label":"Join the Discord community",title:"Join the Discord community",children:[l.jsx(Bze,{className:"h-10 w-10"}),l.jsx("span",{className:"sr-only",children:"Discord"})]})}),l.jsx(Ee,{asChild:!0,size:"icon",variant:"ghost",children:l.jsxs("a",{href:"https://github.com/MCPJam/inspector",target:"_blank",rel:"noreferrer","aria-label":"Visit the GitHub repository",title:"Visit the GitHub repository",children:[l.jsx(qze,{className:"h-10 w-10"}),l.jsx("span",{className:"sr-only",children:"GitHub"})]})})]});return l.jsxs("div",{className:"ml-auto flex h-full flex-1 items-center gap-2 no-drag min-w-0",children:[e&&l.jsx("div",{className:"flex-1 min-w-0 h-full pr-2",children:l.jsx(lfn,{...e,className:"h-full"})}),l.jsxs("div",{className:"ml-auto flex items-center gap-2 shrink-0",children:[l.jsx(Ee,{size:"icon",variant:"ghost",onClick:u,"aria-label":s==="dark"?"Switch to light mode":"Switch to dark mode",title:s==="dark"?"Switch to light mode":"Switch to dark mode",children:s==="dark"?l.jsx(z1e,{className:"h-5 w-5"}):l.jsx($1e,{className:"h-5 w-5"})}),l.jsx(mfn,{}),c,!t&&!i&&l.jsxs(l.Fragment,{children:[l.jsx(Ee,{variant:"outline",size:"sm",onClick:()=>{a.capture("login_button_clicked",{location:"header",platform:Et(),environment:void 0}),n()},children:"Sign in"}),l.jsx(Ee,{size:"sm",onClick:()=>{a.capture("sign_up_button_clicked",{location:"header",platform:Et(),environment:void 0}),r()},children:"Create account"})]})]})]})}const vfn=[{id:"ipc-2025-app-builder-1-1-1",render:({dismiss:e})=>l.jsx("div",{className:"no-drag bg-orange-200 px-4 py-2 text-gray-900 lg:px-6",children:l.jsxs("div",{className:"flex items-center justify-between gap-4",children:[l.jsxs("div",{className:"flex items-center gap-4 flex-1",children:[l.jsx("p",{className:"text-sm font-normal leading-snug",children:"Try the new App Builder for ChatGPT Apps and MCP Apps"}),l.jsx("a",{href:"#app-builder",onClick:e,className:"text-sm font-normal text-orange-700 hover:text-orange-800 underline underline-offset-2",children:"Try it now"})]}),l.jsx(Ee,{size:"sm",variant:"ghost",onClick:e,className:"hover:bg-orange-200 p-1 h-8 w-8",children:l.jsx(Yn,{className:"h-5 w-5"})})]})})}],Hze="inspector.header-ipc.dismissed",yfn=e=>{if(!e)return[];try{const t=JSON.parse(e);return Array.isArray(t)?t:[]}catch(t){return console.warn("Failed to parse stored IPC state",t),[]}},eve=()=>{if(typeof window>"u")return new Set;const e=window.localStorage.getItem(Hze);return new Set(yfn(e))},xfn=e=>{typeof window>"u"||window.localStorage.setItem(Hze,JSON.stringify([...e]))},bfn=()=>{const[e,t]=b.useState(null);b.useEffect(()=>{const r=eve(),i=vfn.find(a=>!r.has(a.id))??null;t(i)},[]);const n=b.useCallback(()=>{if(!e)return;const r=eve();r.add(e.id),xfn(r),t(null)},[e]);return{activeIpc:e,dismissActiveIpc:n}};function _fn({activeWorkspaceId:e,workspaces:t,onSwitchWorkspace:n,onCreateWorkspace:r,onUpdateWorkspace:i,onDeleteWorkspace:a,isLoading:s}){if(s)return l.jsx("div",{className:"flex items-center gap-1",children:l.jsx(nI,{className:"h-8 w-32"})});const o=t[e],u=Object.values(t).sort((f,p)=>f.isDefault?-1:p.isDefault?1:f.name.localeCompare(p.name)),c=()=>{let f="New workspace",p=f,m=1;const y=Object.values(t).map(v=>v.name.toLowerCase());for(;y.includes(p.toLowerCase());)m++,p=`${f} ${m}`;r(p,!0)},d=f=>{i(e,{name:f})};return l.jsxs("div",{className:"flex items-center gap-1",children:[l.jsx(Wj,{value:o?.name||"No Workspace",onSave:d,className:"px-3 py-2 text-m font-semibold",placeholder:"Workspace name"}),l.jsxs(Ic,{children:[l.jsx(jc,{asChild:!0,children:l.jsx(Ee,{variant:"ghost",size:"sm",className:"h-auto p-1",children:l.jsx(Wr,{className:"h-4 w-4 opacity-50"})})}),l.jsxs(Oc,{align:"start",className:"w-[240px]",children:[u.map(f=>l.jsxs(Oi,{className:Ie("cursor-pointer group flex items-center justify-between",f.id===e&&"bg-accent"),onClick:()=>n(f.id),children:[l.jsx("span",{className:"truncate flex-1",children:f.name}),l.jsx("button",{onClick:p=>{p.stopPropagation(),p.preventDefault(),a(f.id)},className:"opacity-0 group-hover:opacity-100 hover:text-destructive transition-opacity p-1",children:l.jsx(Ll,{className:"h-4 w-4"})})]},f.id)),l.jsx(uC,{}),l.jsxs(Oi,{onClick:c,className:"cursor-pointer",children:[l.jsx(_o,{className:"mr-2 h-4 w-4"}),"Add Workspace"]})]})]})]})}function tve({isOpen:e,onClose:t,workspaceName:n,workspaceServers:r,sharedWorkspaceId:i,currentUser:a,onWorkspaceShared:s,onLeaveWorkspace:o}){const[u,c]=b.useState(""),[d,f]=b.useState(!1),[p,m]=b.useState(!1),{isAuthenticated:y}=Ba(),{profilePictureUrl:v}=BP(),{createWorkspace:x,addMember:_,removeMember:S}=T6e(),{activeMembers:w,pendingMembers:T}=E6e({isAuthenticated:y,workspaceId:i||null}),N=!i||w.some(O=>O.email.toLowerCase()===a.email?.toLowerCase()&&O.isOwner);b.useEffect(()=>{e&&Tr.capture("share_dialog_opened",{workspace_name:n,is_already_shared:!!i,member_count:w.length+T.length,platform:Et(),environment:void 0})},[e]);const E=async()=>{if(u.trim()){f(!0);try{let O=i;if(!O){const U=PC(r);O=await x({name:n,servers:U}),O&&s?.(O)}const R=await _({workspaceId:O,email:u.trim()});R.isPending?Pe.success(`Invitation sent to ${u}. They'll get access once they sign up.`):Pe.success(`${u} has been added to the workspace.`),c(""),Tr.capture("workspace_invite_sent",{workspace_name:n,is_new_share:!i,is_pending:R.isPending,platform:Et(),environment:void 0})}catch(O){Pe.error(O.message||"Failed to add member")}finally{f(!1)}}},A=async O=>{if(i)try{await S({workspaceId:i,email:O}),Pe.success("Member removed"),Tr.capture("workspace_member_removed",{workspace_name:n,platform:Et(),environment:void 0})}catch(R){Pe.error(R.message||"Failed to remove member")}},I=async()=>{if(!(!i||!a.email)){m(!0);try{await S({workspaceId:i,email:a.email}),Pe.success("You have left the workspace"),Tr.capture("workspace_left",{workspace_name:n,platform:Et(),environment:void 0}),t(),o?.()}catch(O){Pe.error(O.message||"Failed to leave workspace")}finally{m(!1)}}},M=[a.firstName,a.lastName].filter(Boolean).join(" ")||"You",$=Pm(M);return l.jsx(si,{open:e,onOpenChange:O=>!O&&t(),children:l.jsxs(oi,{className:"sm:max-w-[480px]",children:[l.jsx(vi,{children:l.jsxs(yi,{children:['Share "',n,'"']})}),l.jsxs("div",{className:"space-y-6",children:[l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-sm font-medium",children:"Invite with email"}),l.jsxs("div",{className:"flex gap-2",children:[l.jsx(Ct,{placeholder:"Enter email address",value:u,onChange:O=>c(O.target.value),onKeyDown:O=>O.key==="Enter"&&E(),className:"flex-1"}),l.jsx(Ee,{onClick:E,disabled:!u.trim()||d,children:d?"...":"Invite"})]})]}),l.jsxs("div",{className:"space-y-2",children:[l.jsx("label",{className:"text-sm font-medium",children:i?"People with access":"Only you have access"}),l.jsxs("div",{className:"space-y-1 max-h-[300px] overflow-y-auto",children:[!i&&l.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-md",children:[l.jsxs(kc,{className:"size-9",children:[l.jsx(Ec,{src:v,alt:M}),l.jsx(Tc,{className:"text-sm",children:$})]}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("p",{className:"text-sm font-medium truncate",children:M}),l.jsx("span",{className:"text-xs text-muted-foreground",children:"(you)"})]}),l.jsx("p",{className:"text-xs text-muted-foreground truncate",children:a.email})]})]}),w.map(O=>{const R=O.user?.name||O.email,U=O.email,z=Pm(R),F=U.toLowerCase()===a.email?.toLowerCase(),D=N&&!F;return l.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50",children:[l.jsxs(kc,{className:"size-9",children:[l.jsx(Ec,{src:O.user?.imageUrl||void 0,alt:R}),l.jsx(Tc,{className:"text-sm",children:z})]}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsxs("div",{className:"flex items-center gap-1.5",children:[l.jsx("p",{className:"text-sm font-medium truncate",children:R}),F&&l.jsx("span",{className:"text-xs text-muted-foreground",children:"(you)"})]}),l.jsx("p",{className:"text-xs text-muted-foreground truncate",children:U})]}),D&&l.jsx(Ee,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0 text-muted-foreground hover:text-destructive",onClick:()=>A(U),children:l.jsx(Yn,{className:"size-4"})})]},O._id)}),T.length>0&&l.jsxs(l.Fragment,{children:[l.jsx("div",{className:"pt-2 pb-1",children:l.jsx("p",{className:"text-xs font-medium text-muted-foreground uppercase tracking-wide",children:"Pending (awaiting signup)"})}),T.map(O=>l.jsxs("div",{className:"flex items-center gap-3 p-2 rounded-md hover:bg-muted/50",children:[l.jsx("div",{className:"size-9 rounded-full bg-muted flex items-center justify-center",children:l.jsx(Sw,{className:"size-4 text-muted-foreground"})}),l.jsxs("div",{className:"flex-1 min-w-0",children:[l.jsx("p",{className:"text-sm font-medium truncate",children:O.email}),l.jsx("p",{className:"text-xs text-muted-foreground",children:"Invited - waiting for signup"})]}),N&&l.jsx(Ee,{variant:"ghost",size:"sm",className:"h-8 w-8 p-0",onClick:()=>A(O.email),children:l.jsx(Yn,{className:"size-4"})})]},O._id))]})]})]}),i&&!N&&l.jsxs(Ee,{variant:"outline",className:"w-full text-destructive hover:text-destructive hover:bg-destructive/10",onClick:I,disabled:p,children:[l.jsx(Uq,{className:"size-4 mr-2"}),p?"Leaving...":"Leave workspace"]})]})]})})}function wfn({workspaceName:e,workspaceServers:t,sharedWorkspaceId:n,onWorkspaceShared:r,onLeaveWorkspace:i}){const{isAuthenticated:a}=Ba(),{user:s}=Aa(),{profilePictureUrl:o}=BP(),[u,c]=b.useState(!1),{activeMembers:d,isLoading:f}=E6e({isAuthenticated:a,workspaceId:n??null});if(!a||!s)return null;if(!n){const y=[s.firstName,s.lastName].filter(Boolean).join(" "),v=Pm(y);return l.jsxs("div",{className:"flex items-center",children:[l.jsxs("button",{onClick:()=>c(!0),className:"flex -space-x-2 hover:opacity-80 transition-opacity",children:[l.jsxs(kc,{className:"size-8 border-2 border-background",children:[l.jsx(Ec,{src:o,alt:y}),l.jsx(Tc,{className:"text-xs",children:v})]}),l.jsx("div",{className:"size-8 rounded-full border-2 border-background bg-muted flex items-center justify-center hover:bg-accent transition-colors",children:l.jsx(DM,{className:"size-3.5 text-muted-foreground"})})]}),l.jsx(tve,{isOpen:u,onClose:()=>c(!1),workspaceName:e,workspaceServers:t,sharedWorkspaceId:n,currentUser:s,onWorkspaceShared:r,onLeaveWorkspace:i})]})}if(f)return l.jsx("div",{className:"flex items-center gap-2",children:l.jsx("div",{className:"flex -space-x-2",children:l.jsx("div",{className:"size-8 rounded-full bg-muted animate-pulse"})})});const p=d.slice(0,4),m=d.length-4;return l.jsxs("div",{className:"flex items-center",children:[l.jsxs("button",{onClick:()=>c(!0),className:"flex -space-x-2 hover:opacity-80 transition-opacity",children:[p.map(y=>{const v=y.user?.name||y.email,x=Pm(v);return l.jsxs(kc,{className:Ie("size-8 border-2 border-background ring-0","hover:z-10 transition-transform hover:scale-105"),children:[l.jsx(Ec,{src:y.user?.imageUrl||void 0,alt:v}),l.jsx(Tc,{className:"text-xs",children:x})]},y._id)}),l.jsx("div",{className:"size-8 rounded-full border-2 border-background bg-muted flex items-center justify-center hover:bg-accent transition-colors relative",children:m>0?l.jsxs(l.Fragment,{children:[l.jsx(DM,{className:"size-3.5 text-muted-foreground"}),l.jsx("span",{className:"absolute -top-1 -right-1 size-4 rounded-full bg-primary text-[10px] font-medium text-primary-foreground flex items-center justify-center",children:m>9?"9+":`+${m}`})]}):l.jsx(DM,{className:"size-3.5 text-muted-foreground"})})]}),l.jsx(tve,{isOpen:u,onClose:()=>c(!1),workspaceName:e,workspaceServers:t,sharedWorkspaceId:n,currentUser:s,onWorkspaceShared:r,onLeaveWorkspace:i})]})}const Sfn=({workspaces:e,activeWorkspaceId:t,onSwitchWorkspace:n,onCreateWorkspace:r,onUpdateWorkspace:i,onDeleteWorkspace:a,onLeaveWorkspace:s,onWorkspaceShared:o,activeServerSelectorProps:u,isLoadingWorkspaces:c})=>{const{activeIpc:d,dismissActiveIpc:f}=bfn(),p=e[t],m=()=>{s(t)};return l.jsxs("header",{className:"flex shrink-0 flex-col border-b transition-[width,height] ease-linear",children:[l.jsxs("div",{className:"flex h-12 shrink-0 items-center gap-2 px-4 lg:px-6 drag",children:[l.jsxs("div",{className:"flex items-center gap-1 lg:gap-2 no-drag",children:[l.jsx(lnn,{className:"-ml-1"}),l.jsx(_fn,{activeWorkspaceId:t,workspaces:e,onSwitchWorkspace:n,onCreateWorkspace:r,onUpdateWorkspace:i,onDeleteWorkspace:a,isLoading:c}),l.jsx(wfn,{workspaceName:p?.name||"Workspace",workspaceServers:p?.servers||{},sharedWorkspaceId:p?.sharedWorkspaceId,onWorkspaceShared:o,onLeaveWorkspace:m})]}),l.jsx(gfn,{activeServerSelectorProps:u})]}),d&&d.render({dismiss:f})]})};function kfn(){const[e,t]=b.useState("servers"),[n,r]=b.useState(void 0),[i,a]=b.useState(!1),[s,o]=b.useState(new Set),u=ci(),{isAuthenticated:c,isLoading:d}=Ba();rfn(),b.useEffect(()=>{d||u.capture("app_launched",{platform:Et(),environment:void 0,user_agent:navigator.userAgent,version:"1.5.14",is_authenticated:c})},[d,c]);const f=FWt(),p=BWt();b.useEffect(()=>{RZ(f),qWt(p)},[]),Pnn(),nfn();const m=b.useMemo(()=>window.location.pathname.startsWith("/oauth/callback/debug"),[]),y=b.useMemo(()=>window.location.pathname==="/callback",[]),{appState:v,isLoading:x,isLoadingRemoteWorkspaces:_,workspaceServers:S,connectedOrConnectingServerConfigs:w,selectedMCPConfig:T,handleConnect:N,handleDisconnect:E,handleReconnect:A,handleUpdate:I,handleRemoveServer:M,setSelectedServer:$,toggleServerSelection:O,setSelectedMultipleServersToAllServers:R,workspaces:U,activeWorkspaceId:z,handleSwitchWorkspace:F,handleCreateWorkspace:D,handleUpdateWorkspace:W,handleDeleteWorkspace:q,handleLeaveWorkspace:X,handleWorkspaceShared:L,saveServerConfigWithoutConnecting:Y,handleConnectWithTokensFromOAuthFlow:G,handleRefreshTokensFromOAuthFlow:P}=Cnn(),V=b.useMemo(()=>({...v,workspaces:U,activeWorkspaceId:z}),[v,U,z]),Q=U[z]?.sharedWorkspaceId??null,{viewsByServer:oe}=xK({isAuthenticated:c,workspaceId:Q}),{serversById:re}=bK({isAuthenticated:c,workspaceId:Q}),ee=b.useMemo(()=>{const se=new Set;for(const ie of oe.keys()){const he=re.get(ie);he&&se.add(he)}return se},[oe,re]),le=b.useMemo(()=>Object.entries(w).filter(([,se])=>se.connectionStatus==="connected").map(([se])=>se).sort().join(","),[w]);b.useEffect(()=>{(async()=>{const ie=Object.entries(w).filter(([,ye])=>ye.connectionStatus==="connected").map(([ye])=>ye),he=new Set;await Promise.all(ie.map(async ye=>{try{const Ne=await _g({serverId:ye});(aR(Ne)||iR(Ne)||sR(Ne))&&he.add(ye)}catch(Ne){console.debug(`Failed to check OpenAI apps for server ${ye}:`,Ne)}})),o(he)})()},[le]),b.useEffect(()=>{const se=()=>{const ie=(window.location.hash||"#servers").replace("#",""),ye=(ie.startsWith("/")?ie.slice(1):ie).split("/"),Ne=ye[0];ye[0]==="organizations"&&ye[1]?r(ye[1]):r(void 0);const ce=Ne==="registry"?"servers":Ne;t(ce),(ce==="chat"||ce==="chat-v2")&&R(),ce!=="chat-v2"&&a(!1)};return se(),window.addEventListener("hashchange",se),()=>window.removeEventListener("hashchange",se)},[R]);const te=se=>{(se==="chat"||se==="chat-v2")&&R(),se!=="chat-v2"&&a(!1),window.location.hash=se,t(se)};if(m)return l.jsx(Vtn,{});if(y)return b.useEffect(()=>{const se=setTimeout(()=>{window.location.href="/"},5e3);return()=>clearTimeout(se)},[]),l.jsx(ifn,{});if(x)return l.jsx(afn,{});const ne=e==="tools"||e==="resources"||e==="prompts"||e==="tasks"||e==="oauth-flow"||e==="chat"||e==="chat-v2"||e==="app-builder"||e==="evals"||e==="views"?{serverConfigs:e==="oauth-flow"?v.servers:e==="views"?S:w,selectedServer:v.selectedServer,onServerChange:$,onConnect:N,onReconnect:A,isMultiSelectEnabled:e==="chat"||e==="chat-v2",onMultiServerToggle:O,selectedMultipleServers:v.selectedMultipleServers,showOnlyOAuthServers:e==="oauth-flow",showOnlyOpenAIAppsServers:e==="app-builder",openAiAppOrMcpAppsServers:s,showOnlyServersWithViews:e==="views",serversWithViews:ee,hasMessages:e==="chat-v2"?i:!1}:void 0,J=l.jsxs(snn,{defaultOpen:!0,children:[l.jsx(bnn,{onNavigate:te,activeTab:e,servers:S}),l.jsxs(unn,{className:"flex flex-col min-h-0",children:[l.jsx(Sfn,{workspaces:U,activeWorkspaceId:z,onSwitchWorkspace:F,onCreateWorkspace:D,onUpdateWorkspace:W,onDeleteWorkspace:q,onLeaveWorkspace:X,onWorkspaceShared:L,activeServerSelectorProps:ne,isLoadingWorkspaces:_}),l.jsxs("div",{className:"flex flex-1 min-h-0 flex-col overflow-hidden h-full",children:[e==="servers"&&l.jsx(O0t,{connectedOrConnectingServerConfigs:S,onConnect:N,onDisconnect:E,onReconnect:A,onUpdate:I,onRemove:M,isLoadingWorkspaces:_}),e==="tools"&&l.jsx("div",{className:"h-full overflow-hidden",children:l.jsx(gyt,{serverConfig:T,serverName:v.selectedServer})}),e==="evals"&&l.jsx(DWt,{selectedServer:v.selectedServer}),e==="views"&&l.jsx(KWt,{selectedServer:v.selectedServer}),e==="resources"&&l.jsx("div",{className:"h-full overflow-hidden",children:l.jsx(Syt,{serverConfig:T,serverName:v.selectedServer})}),e==="prompts"&&l.jsx("div",{className:"h-full overflow-hidden",children:l.jsx(Tyt,{serverConfig:T,serverName:v.selectedServer})}),e==="skills"&&l.jsx(uIt,{}),l.jsx("div",{className:e==="tasks"?"h-full overflow-hidden":"hidden",children:l.jsx(vIt,{serverConfig:T,serverName:v.selectedServer,isActive:e==="tasks"})}),e==="auth"&&l.jsx(uKt,{serverConfig:T,serverEntry:v.servers[v.selectedServer],serverName:v.selectedServer}),e==="oauth-flow"&&l.jsx(ytn,{serverConfigs:v.servers,selectedServerName:v.selectedServer,onSelectServer:$,onSaveServerConfig:Y,onConnectWithTokens:G,onRefreshTokens:P}),e==="chat-v2"&&l.jsx(jPt,{connectedOrConnectingServerConfigs:w,selectedServerNames:v.selectedMultipleServers,onHasMessagesChange:a}),e==="tracing"&&l.jsx(iKt,{}),e==="app-builder"&&l.jsx(Ltn,{serverConfig:T,serverName:v.selectedServer}),e==="settings"&&l.jsx(rKt,{}),e==="profile"&&l.jsx(ztn,{}),e==="organizations"&&l.jsx(Ftn,{organizationId:n})]})]})]});return l.jsx(BOt,{themeMode:f,themePreset:p,children:l.jsxs(C0t,{appState:V,children:[l.jsx(Rnn,{}),J]})})}function Efn({children:e,client:t,useAuth:n}){const r=Tfn(n);return l.jsx(jFe,{client:t,useAuth:r,children:e})}function Tfn(e){return b.useMemo(()=>function(){const{isLoading:n,user:r,getAccessToken:i}=e(),a=b.useCallback(async()=>{try{return await i()}catch{return null}},[i]);return b.useMemo(()=>({isLoading:n,isAuthenticated:!!r,fetchAccessToken:a}),[n,r,a])},[e])}const Nfn={environment:"prod",sendDefaultPii:!1,tracesSampleRate:.1,tracePropagationTargets:["localhost",/^\//,/^https?:\/\/[^/]*\.convex\.(cloud|site)/]},Cfn={...Nfn,dsn:"https://c9df3785c734acfe9dad2d0c1e963e28@o4510109778378752.ingest.us.sentry.io/4510111435063296",replaysSessionSampleRate:.1,replaysOnErrorSampleRate:1};function Afn(){tfn({...Cfn,integrations:[zdn(),Xdn()]})}function Ifn(){return l.jsx("div",{className:"flex items-center justify-center h-screen p-5 font-sans bg-neutral-50 text-neutral-800 dark:bg-neutral-900 dark:text-neutral-200",children:l.jsxs("div",{className:"max-w-[400px] leading-relaxed text-center",children:[l.jsxs("p",{className:"mb-3",children:[l.jsx("strong",{children:"Router issue:"})," Your app uses"," ",l.jsx("code",{className:"bg-neutral-200 dark:bg-neutral-700 px-1.5 py-0.5 rounded text-[0.9em]",children:"BrowserRouter"}),", which isn't supported in iframes."]}),l.jsxs("p",{className:"text-sm opacity-70",children:["Switch to"," ",l.jsx("code",{className:"bg-neutral-200 dark:bg-neutral-700 px-1.5 py-0.5 rounded text-[0.9em]",children:"MemoryRouter"})," ","or"," ",l.jsx("code",{className:"bg-neutral-200 dark:bg-neutral-700 px-1.5 py-0.5 rounded text-[0.9em]",children:"HashRouter"})," ","instead, then re-run your tool."]})]})})}Afn();const jfn=(()=>{try{return window.self!==window.top}catch{return!0}})();if(jfn)fee.createRoot(document.getElementById("root")).render(l.jsx(b.StrictMode,{children:l.jsx(Ifn,{})}));else{const e="https://outstanding-fennec-304.convex.cloud",t="client_01K4C1TVPBE7JTBFQJF9SDW9P9",n=(()=>{const o="mcpjam://oauth/callback";return typeof window>"u"?o:window.location.protocol==="http:"||window.location.protocol==="https:"?`${window.location.origin}/callback`:o})(),r={apiHostname:"api.mcpjam.com"},i=new SFe(e),a=l.jsx(_0t,{clientId:t,redirectUri:n,...r,children:l.jsx(Efn,{client:i,useAuth:Aa,children:l.jsx(kfn,{})})});async function s(){const o=fee.createRoot(document.getElementById("root"));try{await Ket(),console.log("[Auth] Session token initialized")}catch(u){console.error("[Auth] Failed to initialize session token:",u),o.render(l.jsx(b.StrictMode,{children:l.jsxs("div",{style:{padding:"2rem",textAlign:"center",fontFamily:"system-ui",display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",minHeight:"100vh"},children:[l.jsx("img",{src:"/mcp_jam.svg",alt:"MCPJam Logo",style:{width:"120px",height:"auto",marginBottom:"1.5rem"}}),l.jsx("h1",{style:{color:"#dc2626",marginBottom:"0.5rem"},children:"Authentication Error"}),l.jsx("p",{style:{marginBottom:"0.25rem"},children:"Failed to establish secure session."}),l.jsx("p",{style:{color:"#666",fontSize:"0.875rem"},children:"If accessing via network, use localhost instead."}),l.jsx("button",{onClick:()=>location.reload(),style:{marginTop:"1.5rem",padding:"0.75rem 1.5rem",cursor:"pointer",backgroundColor:"#18181b",color:"#fff",border:"none",borderRadius:"0.5rem",fontSize:"1rem",fontWeight:500},children:"Restart App"})]})}));return}o.render(l.jsx(b.StrictMode,{children:l.jsx(brt,{apiKey:Nrt(),options:Crt(),children:a})}))}s()}const Ofn=Object.freeze(Object.defineProperty({__proto__:null,Mermaid:NRe},Symbol.toStringTag,{value:"Module"}));export{pAt as I,Ul as L,Hpn as Z,cn as g,l as j,b as r};
|
|
1943
|
+
//# sourceMappingURL=index-BUVtQr4n.js.map
|