@mastra/deployer-cloud 1.67.0-alpha.6 → 1.67.0
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/studio/assets/{core-C6NBy4h2.js → core-BMRp5Zv-.js} +1 -1
- package/dist/studio/assets/{index-CsQQD4Xx.js → index-DcEuRGVF.js} +2 -2
- package/dist/studio/assets/{main-C_EZXcDh.js → main-CeV6Cs7h.js} +3 -3
- package/dist/studio/index.html +1 -1
- package/package.json +7 -7
- package/versions.json +1 -1
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["./core-BMRp5Zv-.js","./engine-compile-BkERmzkH.js","./preload-helper-PPVm8Dsz.js","./engine-javascript-CSIo_1eZ.js","./html-C2L_23MC.js","./javascript-ySlJ1b_l.js","./css-BPhBrDlE.js"])))=>i.map(i=>d[i]);
|
|
2
2
|
import{_ as Va}from"./preload-helper-PPVm8Dsz.js";function fXt(e,t){for(var n=0;n<t.length;n++){const r=t[n];if(typeof r!="string"&&!Array.isArray(r)){for(const s in r)if(s!=="default"&&!(s in e)){const a=Object.getOwnPropertyDescriptor(r,s);a&&Object.defineProperty(e,s,a.get?a:{enumerable:!0,get:()=>r[s]})}}}return Object.freeze(Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}))}var Gj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function Hl(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var gJ={exports:{}},LR={};var HDe;function hXt(){if(HDe)return LR;HDe=1;var e=Symbol.for("react.transitional.element"),t=Symbol.for("react.fragment");function n(r,s,a){var i=null;if(a!==void 0&&(i=""+a),s.key!==void 0&&(i=""+s.key),"key"in s){a={};for(var l in s)l!=="key"&&(a[l]=s[l])}else a=s;return s=a.ref,{$$typeof:e,type:r,key:i,ref:s!==void 0?s:null,props:a}}return LR.Fragment=t,LR.jsx=n,LR.jsxs=n,LR}var WDe;function pXt(){return WDe||(WDe=1,gJ.exports=hXt()),gJ.exports}var o=pXt(),vJ={exports:{}},Kr={},ZDe;function mXt(){if(ZDe)return Kr;ZDe=1;var e={env:{}};var t=Symbol.for("react.transitional.element"),n=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),s=Symbol.for("react.strict_mode"),a=Symbol.for("react.profiler"),i=Symbol.for("react.consumer"),l=Symbol.for("react.context"),c=Symbol.for("react.forward_ref"),u=Symbol.for("react.suspense"),d=Symbol.for("react.memo"),f=Symbol.for("react.lazy"),h=Symbol.for("react.activity"),p=Symbol.iterator;function m(M){return M===null||typeof M!="object"?null:(M=p&&M[p]||M["@@iterator"],typeof M=="function"?M:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function x(M,R,F){this.props=M,this.context=R,this.refs=b,this.updater=F||v}x.prototype.isReactComponent={},x.prototype.setState=function(M,R){if(typeof M!="object"&&typeof M!="function"&&M!=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,M,R,"setState")},x.prototype.forceUpdate=function(M){this.updater.enqueueForceUpdate(this,M,"forceUpdate")};function w(){}w.prototype=x.prototype;function k(M,R,F){this.props=M,this.context=R,this.refs=b,this.updater=F||v}var O=k.prototype=new w;O.constructor=k,y(O,x.prototype),O.isPureReactComponent=!0;var _=Array.isArray;function T(){}var E={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(M,R,F){var U=F.ref;return{$$typeof:t,type:M,key:R,ref:U!==void 0?U:null,props:F}}function A(M,R){return I(M.type,R,M.props)}function $(M){return typeof M=="object"&&M!==null&&M.$$typeof===t}function z(M){var R={"=":"=0",":":"=2"};return"$"+M.replace(/[=:]/g,function(F){return R[F]})}var D=/\/+/g;function q(M,R){return typeof M=="object"&&M!==null&&M.key!=null?z(""+M.key):R.toString(36)}function H(M){switch(M.status){case"fulfilled":return M.value;case"rejected":throw M.reason;default:switch(typeof M.status=="string"?M.then(T,T):(M.status="pending",M.then(function(R){M.status==="pending"&&(M.status="fulfilled",M.value=R)},function(R){M.status==="pending"&&(M.status="rejected",M.reason=R)})),M.status){case"fulfilled":return M.value;case"rejected":throw M.reason}}throw M}function V(M,R,F,U,Q){var te=typeof M;(te==="undefined"||te==="boolean")&&(M=null);var J=!1;if(M===null)J=!0;else switch(te){case"bigint":case"string":case"number":J=!0;break;case"object":switch(M.$$typeof){case t:case n:J=!0;break;case f:return J=M._init,V(J(M._payload),R,F,U,Q)}}if(J)return Q=Q(M),J=U===""?"."+q(M,0):U,_(Q)?(F="",J!=null&&(F=J.replace(D,"$&/")+"/"),V(Q,R,F,"",function(ae){return ae})):Q!=null&&($(Q)&&(Q=A(Q,F+(Q.key==null||M&&M.key===Q.key?"":(""+Q.key).replace(D,"$&/")+"/")+J)),R.push(Q)),1;J=0;var ee=U===""?".":U+":";if(_(M))for(var re=0;re<M.length;re++)U=M[re],te=ee+q(U,re),J+=V(U,R,F,te,Q);else if(re=m(M),typeof re=="function")for(M=re.call(M),re=0;!(U=M.next()).done;)U=U.value,te=ee+q(U,re++),J+=V(U,R,F,te,Q);else if(te==="object"){if(typeof M.then=="function")return V(H(M),R,F,U,Q);throw R=String(M),Error("Objects are not valid as a React child (found: "+(R==="[object Object]"?"object with keys {"+Object.keys(M).join(", ")+"}":R)+"). If you meant to render a collection of children, use an array instead.")}return J}function B(M,R,F){if(M==null)return M;var U=[],Q=0;return V(M,U,"","",function(te){return R.call(F,te,Q++)}),U}function W(M){if(M._status===-1){var R=M._result;R=R(),R.then(function(F){(M._status===0||M._status===-1)&&(M._status=1,M._result=F)},function(F){(M._status===0||M._status===-1)&&(M._status=2,M._result=F)}),M._status===-1&&(M._status=0,M._result=R)}if(M._status===1)return M._result.default;throw M._result}var L=typeof reportError=="function"?reportError:function(M){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var R=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof M=="object"&&M!==null&&typeof M.message=="string"?String(M.message):String(M),error:M});if(!window.dispatchEvent(R))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",M);return}console.error(M)},G={map:B,forEach:function(M,R,F){B(M,function(){R.apply(this,arguments)},F)},count:function(M){var R=0;return B(M,function(){R++}),R},toArray:function(M){return B(M,function(R){return R})||[]},only:function(M){if(!$(M))throw Error("React.Children.only expected to receive a single React element child.");return M}};return Kr.Activity=h,Kr.Children=G,Kr.Component=x,Kr.Fragment=r,Kr.Profiler=a,Kr.PureComponent=k,Kr.StrictMode=s,Kr.Suspense=u,Kr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=E,Kr.__COMPILER_RUNTIME={__proto__:null,c:function(M){return E.H.useMemoCache(M)}},Kr.cache=function(M){return function(){return M.apply(null,arguments)}},Kr.cacheSignal=function(){return null},Kr.cloneElement=function(M,R,F){if(M==null)throw Error("The argument must be a React element, but you passed "+M+".");var U=y({},M.props),Q=M.key;if(R!=null)for(te in R.key!==void 0&&(Q=""+R.key),R)!N.call(R,te)||te==="key"||te==="__self"||te==="__source"||te==="ref"&&R.ref===void 0||(U[te]=R[te]);var te=arguments.length-2;if(te===1)U.children=F;else if(1<te){for(var J=Array(te),ee=0;ee<te;ee++)J[ee]=arguments[ee+2];U.children=J}return I(M.type,Q,U)},Kr.createContext=function(M){return M={$$typeof:l,_currentValue:M,_currentValue2:M,_threadCount:0,Provider:null,Consumer:null},M.Provider=M,M.Consumer={$$typeof:i,_context:M},M},Kr.createElement=function(M,R,F){var U,Q={},te=null;if(R!=null)for(U in R.key!==void 0&&(te=""+R.key),R)N.call(R,U)&&U!=="key"&&U!=="__self"&&U!=="__source"&&(Q[U]=R[U]);var J=arguments.length-2;if(J===1)Q.children=F;else if(1<J){for(var ee=Array(J),re=0;re<J;re++)ee[re]=arguments[re+2];Q.children=ee}if(M&&M.defaultProps)for(U in J=M.defaultProps,J)Q[U]===void 0&&(Q[U]=J[U]);return I(M,te,Q)},Kr.createRef=function(){return{current:null}},Kr.forwardRef=function(M){return{$$typeof:c,render:M}},Kr.isValidElement=$,Kr.lazy=function(M){return{$$typeof:f,_payload:{_status:-1,_result:M},_init:W}},Kr.memo=function(M,R){return{$$typeof:d,type:M,compare:R===void 0?null:R}},Kr.startTransition=function(M){var R=E.T,F={};E.T=F;try{var U=M(),Q=E.S;Q!==null&&Q(F,U),typeof U=="object"&&U!==null&&typeof U.then=="function"&&U.then(T,L)}catch(te){L(te)}finally{R!==null&&F.types!==null&&(R.types=F.types),E.T=R}},Kr.unstable_useCacheRefresh=function(){return E.H.useCacheRefresh()},Kr.use=function(M){return E.H.use(M)},Kr.useActionState=function(M,R,F){return E.H.useActionState(M,R,F)},Kr.useCallback=function(M,R){return E.H.useCallback(M,R)},Kr.useContext=function(M){return E.H.useContext(M)},Kr.useDebugValue=function(){},Kr.useDeferredValue=function(M,R){return E.H.useDeferredValue(M,R)},Kr.useEffect=function(M,R){return E.H.useEffect(M,R)},Kr.useEffectEvent=function(M){return E.H.useEffectEvent(M)},Kr.useId=function(){return E.H.useId()},Kr.useImperativeHandle=function(M,R,F){return E.H.useImperativeHandle(M,R,F)},Kr.useInsertionEffect=function(M,R){return E.H.useInsertionEffect(M,R)},Kr.useLayoutEffect=function(M,R){return E.H.useLayoutEffect(M,R)},Kr.useMemo=function(M,R){return E.H.useMemo(M,R)},Kr.useOptimistic=function(M,R){return E.H.useOptimistic(M,R)},Kr.useReducer=function(M,R,F){return E.H.useReducer(M,R,F)},Kr.useRef=function(M){return E.H.useRef(M)},Kr.useState=function(M){return E.H.useState(M)},Kr.useSyncExternalStore=function(M,R,F){return E.H.useSyncExternalStore(M,R,F)},Kr.useTransition=function(){return E.H.useTransition()},Kr.version="19.2.7",Kr}var GDe;function wI(){return GDe||(GDe=1,vJ.exports=mXt()),vJ.exports}var g=wI();const ze=Hl(g),SI=fXt({__proto__:null,default:ze},[g]);var yJ={exports:{}},FR={},bJ={exports:{}},xJ={};var QDe;function gXt(){return QDe||(QDe=1,(function(e){function t(H,V){var B=H.length;H.push(V);e:for(;0<B;){var W=B-1>>>1,L=H[W];if(0<s(L,V))H[W]=V,H[B]=L,B=W;else break e}}function n(H){return H.length===0?null:H[0]}function r(H){if(H.length===0)return null;var V=H[0],B=H.pop();if(B!==V){H[0]=B;e:for(var W=0,L=H.length,G=L>>>1;W<G;){var M=2*(W+1)-1,R=H[M],F=M+1,U=H[F];if(0>s(R,B))F<L&&0>s(U,R)?(H[W]=U,H[F]=B,W=F):(H[W]=R,H[M]=B,W=M);else if(F<L&&0>s(U,B))H[W]=U,H[F]=B,W=F;else break e}}return V}function s(H,V){var B=H.sortIndex-V.sortIndex;return B!==0?B:H.id-V.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 i=Date,l=i.now();e.unstable_now=function(){return i.now()-l}}var c=[],u=[],d=1,f=null,h=3,p=!1,m=!1,v=!1,y=!1,b=typeof setTimeout=="function"?setTimeout:null,x=typeof clearTimeout=="function"?clearTimeout:null,w=typeof setImmediate<"u"?setImmediate:null;function k(H){for(var V=n(u);V!==null;){if(V.callback===null)r(u);else if(V.startTime<=H)r(u),V.sortIndex=V.expirationTime,t(c,V);else break;V=n(u)}}function O(H){if(v=!1,k(H),!m)if(n(c)!==null)m=!0,_||(_=!0,$());else{var V=n(u);V!==null&&q(O,V.startTime-H)}}var _=!1,T=-1,E=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<E)}function A(){if(y=!1,_){var H=e.unstable_now();N=H;var V=!0;try{e:{m=!1,v&&(v=!1,x(T),T=-1),p=!0;var B=h;try{t:{for(k(H),f=n(c);f!==null&&!(f.expirationTime>H&&I());){var W=f.callback;if(typeof W=="function"){f.callback=null,h=f.priorityLevel;var L=W(f.expirationTime<=H);if(H=e.unstable_now(),typeof L=="function"){f.callback=L,k(H),V=!0;break t}f===n(c)&&r(c),k(H)}else r(c);f=n(c)}if(f!==null)V=!0;else{var G=n(u);G!==null&&q(O,G.startTime-H),V=!1}}break e}finally{f=null,h=B,p=!1}V=void 0}}finally{V?$():_=!1}}}var $;if(typeof w=="function")$=function(){w(A)};else if(typeof MessageChannel<"u"){var z=new MessageChannel,D=z.port2;z.port1.onmessage=A,$=function(){D.postMessage(null)}}else $=function(){b(A,0)};function q(H,V){T=b(function(){H(e.unstable_now())},V)}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(H){H.callback=null},e.unstable_forceFrameRate=function(H){0>H||125<H?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):E=0<H?Math.floor(1e3/H):5},e.unstable_getCurrentPriorityLevel=function(){return h},e.unstable_next=function(H){switch(h){case 1:case 2:case 3:var V=3;break;default:V=h}var B=h;h=V;try{return H()}finally{h=B}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(H,V){switch(H){case 1:case 2:case 3:case 4:case 5:break;default:H=3}var B=h;h=H;try{return V()}finally{h=B}},e.unstable_scheduleCallback=function(H,V,B){var W=e.unstable_now();switch(typeof B=="object"&&B!==null?(B=B.delay,B=typeof B=="number"&&0<B?W+B:W):B=W,H){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=B+L,H={id:d++,callback:V,priorityLevel:H,startTime:B,expirationTime:L,sortIndex:-1},B>W?(H.sortIndex=B,t(u,H),n(c)===null&&H===n(u)&&(v?(x(T),T=-1):v=!0,q(O,B-W))):(H.sortIndex=L,t(c,H),m||p||(m=!0,_||(_=!0,$()))),H},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(H){var V=h;return function(){var B=h;h=V;try{return H.apply(this,arguments)}finally{h=B}}}})(xJ)),xJ}var YDe;function vXt(){return YDe||(YDe=1,bJ.exports=gXt()),bJ.exports}var wJ={exports:{}},Eu={};var KDe;function yXt(){if(KDe)return Eu;KDe=1;var e=wI();function t(c){var u="https://react.dev/errors/"+c;if(1<arguments.length){u+="?args[]="+encodeURIComponent(arguments[1]);for(var d=2;d<arguments.length;d++)u+="&args[]="+encodeURIComponent(arguments[d])}return"Minified React error #"+c+"; visit "+u+" 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},s=Symbol.for("react.portal");function a(c,u,d){var f=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:s,key:f==null?null:""+f,children:c,containerInfo:u,implementation:d}}var i=e.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function l(c,u){if(c==="font")return"";if(typeof u=="string")return u==="use-credentials"?u:""}return Eu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Eu.createPortal=function(c,u){var d=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!u||u.nodeType!==1&&u.nodeType!==9&&u.nodeType!==11)throw Error(t(299));return a(c,u,null,d)},Eu.flushSync=function(c){var u=i.T,d=r.p;try{if(i.T=null,r.p=2,c)return c()}finally{i.T=u,r.p=d,r.d.f()}},Eu.preconnect=function(c,u){typeof c=="string"&&(u?(u=u.crossOrigin,u=typeof u=="string"?u==="use-credentials"?u:"":void 0):u=null,r.d.C(c,u))},Eu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},Eu.preinit=function(c,u){if(typeof c=="string"&&u&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin),h=typeof u.integrity=="string"?u.integrity:void 0,p=typeof u.fetchPriority=="string"?u.fetchPriority:void 0;d==="style"?r.d.S(c,typeof u.precedence=="string"?u.precedence:void 0,{crossOrigin:f,integrity:h,fetchPriority:p}):d==="script"&&r.d.X(c,{crossOrigin:f,integrity:h,fetchPriority:p,nonce:typeof u.nonce=="string"?u.nonce:void 0})}},Eu.preinitModule=function(c,u){if(typeof c=="string")if(typeof u=="object"&&u!==null){if(u.as==null||u.as==="script"){var d=l(u.as,u.crossOrigin);r.d.M(c,{crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0})}}else u==null&&r.d.M(c)},Eu.preload=function(c,u){if(typeof c=="string"&&typeof u=="object"&&u!==null&&typeof u.as=="string"){var d=u.as,f=l(d,u.crossOrigin);r.d.L(c,d,{crossOrigin:f,integrity:typeof u.integrity=="string"?u.integrity:void 0,nonce:typeof u.nonce=="string"?u.nonce:void 0,type:typeof u.type=="string"?u.type:void 0,fetchPriority:typeof u.fetchPriority=="string"?u.fetchPriority:void 0,referrerPolicy:typeof u.referrerPolicy=="string"?u.referrerPolicy:void 0,imageSrcSet:typeof u.imageSrcSet=="string"?u.imageSrcSet:void 0,imageSizes:typeof u.imageSizes=="string"?u.imageSizes:void 0,media:typeof u.media=="string"?u.media:void 0})}},Eu.preloadModule=function(c,u){if(typeof c=="string")if(u){var d=l(u.as,u.crossOrigin);r.d.m(c,{as:typeof u.as=="string"&&u.as!=="script"?u.as:void 0,crossOrigin:d,integrity:typeof u.integrity=="string"?u.integrity:void 0})}else r.d.m(c)},Eu.requestFormReset=function(c){r.d.r(c)},Eu.unstable_batchedUpdates=function(c,u){return c(u)},Eu.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},Eu.useFormStatus=function(){return i.H.useHostTransitionStatus()},Eu.version="19.2.7",Eu}var XDe;function Cdt(){if(XDe)return wJ.exports;XDe=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(),wJ.exports=yXt(),wJ.exports}var JDe;function bXt(){if(JDe)return FR;JDe=1;var e={env:{}};var t=vXt(),n=wI(),r=Cdt();function s(S){var C="https://react.dev/errors/"+S;if(1<arguments.length){C+="?args[]="+encodeURIComponent(arguments[1]);for(var j=2;j<arguments.length;j++)C+="&args[]="+encodeURIComponent(arguments[j])}return"Minified React error #"+S+"; visit "+C+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function a(S){return!(!S||S.nodeType!==1&&S.nodeType!==9&&S.nodeType!==11)}function i(S){var C=S,j=S;if(S.alternate)for(;C.return;)C=C.return;else{S=C;do C=S,(C.flags&4098)!==0&&(j=C.return),S=C.return;while(S)}return C.tag===3?j:null}function l(S){if(S.tag===13){var C=S.memoizedState;if(C===null&&(S=S.alternate,S!==null&&(C=S.memoizedState)),C!==null)return C.dehydrated}return null}function c(S){if(S.tag===31){var C=S.memoizedState;if(C===null&&(S=S.alternate,S!==null&&(C=S.memoizedState)),C!==null)return C.dehydrated}return null}function u(S){if(i(S)!==S)throw Error(s(188))}function d(S){var C=S.alternate;if(!C){if(C=i(S),C===null)throw Error(s(188));return C!==S?null:S}for(var j=S,P=C;;){var Z=j.return;if(Z===null)break;var Y=Z.alternate;if(Y===null){if(P=Z.return,P!==null){j=P;continue}break}if(Z.child===Y.child){for(Y=Z.child;Y;){if(Y===j)return u(Z),S;if(Y===P)return u(Z),C;Y=Y.sibling}throw Error(s(188))}if(j.return!==P.return)j=Z,P=Y;else{for(var oe=!1,Oe=Z.child;Oe;){if(Oe===j){oe=!0,j=Z,P=Y;break}if(Oe===P){oe=!0,P=Z,j=Y;break}Oe=Oe.sibling}if(!oe){for(Oe=Y.child;Oe;){if(Oe===j){oe=!0,j=Y,P=Z;break}if(Oe===P){oe=!0,P=Y,j=Z;break}Oe=Oe.sibling}if(!oe)throw Error(s(189))}}if(j.alternate!==P)throw Error(s(190))}if(j.tag!==3)throw Error(s(188));return j.stateNode.current===j?S:C}function f(S){var C=S.tag;if(C===5||C===26||C===27||C===6)return S;for(S=S.child;S!==null;){if(C=f(S),C!==null)return C;S=S.sibling}return null}var h=Object.assign,p=Symbol.for("react.element"),m=Symbol.for("react.transitional.element"),v=Symbol.for("react.portal"),y=Symbol.for("react.fragment"),b=Symbol.for("react.strict_mode"),x=Symbol.for("react.profiler"),w=Symbol.for("react.consumer"),k=Symbol.for("react.context"),O=Symbol.for("react.forward_ref"),_=Symbol.for("react.suspense"),T=Symbol.for("react.suspense_list"),E=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),I=Symbol.for("react.activity"),A=Symbol.for("react.memo_cache_sentinel"),$=Symbol.iterator;function z(S){return S===null||typeof S!="object"?null:(S=$&&S[$]||S["@@iterator"],typeof S=="function"?S:null)}var D=Symbol.for("react.client.reference");function q(S){if(S==null)return null;if(typeof S=="function")return S.$$typeof===D?null:S.displayName||S.name||null;if(typeof S=="string")return S;switch(S){case y:return"Fragment";case x:return"Profiler";case b:return"StrictMode";case _:return"Suspense";case T:return"SuspenseList";case I:return"Activity"}if(typeof S=="object")switch(S.$$typeof){case v:return"Portal";case k:return S.displayName||"Context";case w:return(S._context.displayName||"Context")+".Consumer";case O:var C=S.render;return S=S.displayName,S||(S=C.displayName||C.name||"",S=S!==""?"ForwardRef("+S+")":"ForwardRef"),S;case E:return C=S.displayName||null,C!==null?C:q(S.type)||"Memo";case N:C=S._payload,S=S._init;try{return q(S(C))}catch{}}return null}var H=Array.isArray,V=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,B=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,W={pending:!1,data:null,method:null,action:null},L=[],G=-1;function M(S){return{current:S}}function R(S){0>G||(S.current=L[G],L[G]=null,G--)}function F(S,C){G++,L[G]=S.current,S.current=C}var U=M(null),Q=M(null),te=M(null),J=M(null);function ee(S,C){switch(F(te,C),F(Q,S),F(U,null),C.nodeType){case 9:case 11:S=(S=C.documentElement)&&(S=S.namespaceURI)?pDe(S):0;break;default:if(S=C.tagName,C=C.namespaceURI)C=pDe(C),S=mDe(C,S);else switch(S){case"svg":S=1;break;case"math":S=2;break;default:S=0}}R(U),F(U,S)}function re(){R(U),R(Q),R(te)}function ae(S){S.memoizedState!==null&&F(J,S);var C=U.current,j=mDe(C,S.type);C!==j&&(F(Q,S),F(U,j))}function X(S){Q.current===S&&(R(U),R(Q)),J.current===S&&(R(J),PR._currentValue=W)}var ne,se;function ce(S){if(ne===void 0)try{throw Error()}catch(j){var C=j.stack.trim().match(/\n( *(at )?)/);ne=C&&C[1]||"",se=-1<j.stack.indexOf(`
|
|
3
3
|
at`)?" (<anonymous>)":-1<j.stack.indexOf("@")?"@unknown:0:0":""}return`
|
|
4
4
|
`+ne+S+se}var le=!1;function ve(S,C){if(!S||le)return"";le=!0;var j=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var P={DetermineComponentFrameRoot:function(){try{if(C){var Pt=function(){throw Error()};if(Object.defineProperty(Pt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Pt,[])}catch(yt){var ut=yt}Reflect.construct(S,[],Pt)}else{try{Pt.call()}catch(yt){ut=yt}S.call(Pt.prototype)}}else{try{throw Error()}catch(yt){ut=yt}(Pt=S())&&typeof Pt.catch=="function"&&Pt.catch(function(){})}}catch(yt){if(yt&&ut&&typeof yt.stack=="string")return[yt.stack,ut.stack]}return[null,null]}};P.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var Z=Object.getOwnPropertyDescriptor(P.DetermineComponentFrameRoot,"name");Z&&Z.configurable&&Object.defineProperty(P.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var Y=P.DetermineComponentFrameRoot(),oe=Y[0],Oe=Y[1];if(oe&&Oe){var He=oe.split(`
|
|
@@ -231,7 +231,7 @@ attempted value: ${i}
|
|
|
231
231
|
\${}
|
|
232
232
|
}
|
|
233
233
|
}`,{label:"class",detail:"definition",type:"keyword"}),hf('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),hf('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],fCt=ACe.concat([hf("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),hf("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),hf("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),J7e=new m1t,hCt=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function uP(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const aZn=["FunctionDeclaration"],iZn={FunctionDeclaration:uP("function"),ClassDeclaration:uP("class"),ClassExpression:()=>!0,EnumDeclaration:uP("constant"),TypeAliasDeclaration:uP("type"),NamespaceDeclaration:uP("namespace"),VariableDefinition(e,t){e.matchContext(aZn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function pCt(e,t){let n=J7e.get(t);if(n)return n;let r=[],s=!0;function a(i,l){let c=e.sliceString(i.from,i.to);r.push({label:c,type:l})}return t.cursor(Ha.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=iZn[i.name];if(l&&l(i,a)||hCt.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of pCt(e,i.node))r.push(l);return!1}}),J7e.set(t,r),r}const MU=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,RCe=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function mCt(e){let t=xi(e.state).resolveInner(e.pos,-1);if(RCe.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&MU.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)hCt.has(s.name)&&(r=r.concat(pCt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:MU}}function one(e,t,n){var r;let s=[];for(;;){let a=t.firstChild,i;if(a?.name=="VariableName")return s.push(e(a)),{path:s.reverse(),name:n};if(a?.name=="MemberExpression"&&((r=i=a.lastChild)===null||r===void 0?void 0:r.name)=="PropertyName")s.push(e(i)),t=a;else return null}}function gCt(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=xi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?one(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?one(t,n.parent,""):RCe.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&MU.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?one(t,n,""):e.explicit?{path:[],name:""}:null}function oZn(e,t){let n=e,r=[],s=new Set;for(let a=0;;a++){for(let l of(Object.getOwnPropertyNames||Object.keys)(e)){if(!/^[a-zA-Z_$\xaa-\uffdc][\w$\xaa-\uffdc]*$/.test(l)||s.has(l))continue;s.add(l);let c;try{c=n[l]}catch{continue}r.push({label:l,type:typeof c=="function"?/^[A-Z]/.test(l)?"class":t?"function":"method":t?"variable":"property",boost:-a})}let i=Object.getPrototypeOf(e);if(!i)return r;e=i}}function lZn(e){let t=new Map;return n=>{let r=gCt(n);if(!r)return null;let s=e;for(let i of r.path)if(s=s[i],!s)return null;let a=t.get(s);return a||t.set(s,a=oZn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:MU}}}const om=pC.define({name:"javascript",parser:sZn.configure({props:[w_.add({IfStatement:jj({except:/^\s*({|else\b)/}),TryStatement:jj({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:nqn,SwitchBody:e=>{let t=e.textAfter,n=/^\s*\}/.test(t),r=/^\s*(case|default)\b/.test(t);return e.baseIndent+(n?0:r?1:2)*e.unit},Block:tqn({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":jj({except:/^\s*{/}),JSXElement(e){let t=/^\s*<\//.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},JSXEscape(e){let t=/\s*\}/.test(e.textAfter);return e.lineIndent(e.node.from)+(t?0:e.unit)},"JSXOpenTag JSXSelfClosingTag"(e){return e.column(e.node.from)+e.unit}}),S_.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":fCe,BlockComment(e){return{from:e.from+2,to:e.to-2}},JSXElement(e){let t=e.firstChild;if(!t||t.name=="JSXSelfClosingTag")return null;let n=e.lastChild;return{from:t.to,to:n.type.isError?e.to:n.from}},"JSXSelfClosingTag JSXOpenTag"(e){var t;let n=(t=e.firstChild)===null||t===void 0?void 0:t.nextSibling,r=e.lastChild;return!n||n.type.isError?null:{from:n.to,to:r.type.isError?e.to:r.from}}})]}),languageData:{closeBrackets:{brackets:["(","[","{","'",'"',"`"]},commentTokens:{line:"//",block:{open:"/*",close:"*/"}},indentOnInput:/^\s*(?:case |default:|\{|\}|<\/)$/,wordChars:"$"}}),vCt={test:e=>/^JSX/.test(e.name),facet:eZ({commentTokens:{block:{open:"{/*",close:"*/}"}}})},PCe=om.configure({dialect:"ts"},"typescript"),$Ce=om.configure({dialect:"jsx",props:[cCe.add(e=>e.isTop?[vCt]:void 0)]}),MCe=om.configure({dialect:"jsx ts",props:[cCe.add(e=>e.isTop?[vCt]:void 0)]},"typescript");let yCt=e=>({label:e,type:"keyword"});const bCt="break case const continue default delete export extends false finally in instanceof let new return static super switch this throw true typeof var yield".split(" ").map(yCt),cZn=bCt.concat(["declare","implements","private","protected","public"].map(yCt));function DU(e={}){let t=e.jsx?e.typescript?MCe:$Ce:e.typescript?PCe:om,n=e.typescript?fCt.concat(cZn):ACe.concat(bCt);return new gC(t,[om.data.of({autocomplete:Bqn(RCe,vOt(n))}),om.data.of({autocomplete:mCt}),e.jsx?xCt:[]])}function uZn(e){for(;;){if(e.name=="JSXOpenTag"||e.name=="JSXSelfClosingTag"||e.name=="JSXFragmentTag")return e;if(e.name=="JSXEscape"||!e.parent)return null;e=e.parent}}function eBe(e,t,n=e.length){for(let r=t?.firstChild;r;r=r.nextSibling)if(r.name=="JSXIdentifier"||r.name=="JSXBuiltin"||r.name=="JSXNamespacedName"||r.name=="JSXMemberExpression")return e.sliceString(r.from,Math.min(r.to,n));return""}const dZn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),xCt=Rt.inputHandler.of((e,t,n,r,s)=>{if((dZn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!om.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=xi(i).resolveInner(d-1,-1),h;if(f.name=="JSXStartTag"&&(f=f.parent),!(i.doc.sliceString(d-1,d)!=r||f.name=="JSXAttributeValue"&&f.to>d)){if(r==">"&&f.name=="JSXFragmentTag")return{range:c,changes:{from:d,insert:"</>"}};if(r=="/"&&f.name=="JSXStartCloseTag"){let p=f.parent,m=p.parent;if(m&&p.from==d-2&&((h=eBe(i.doc,m.firstChild,d))||((u=m.firstChild)===null||u===void 0?void 0:u.name)=="JSXFragmentTag")){let v=`${h}>`;return{range:St.cursor(d+v.length,-1),changes:{from:d,insert:v}}}}else if(r==">"){let p=uZn(f);if(p&&p.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(h=eBe(i.doc,p,d)))return{range:c,changes:{from:d,insert:`</${h}>`}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)});function fZn(e,t){return t||(t={parserOptions:{ecmaVersion:2019,sourceType:"module"},env:{browser:!0,node:!0,es6:!0,es2015:!0,es2017:!0,es2020:!0},rules:{}},e.getRules().forEach((n,r)=>{var s;!((s=n.meta.docs)===null||s===void 0)&&s.recommended&&(t.rules[r]=2)})),n=>{let{state:r}=n,s=[];for(let{from:a,to:i}of om.findRegions(r)){let l=r.doc.lineAt(a),c={line:l.number-1,col:a-l.from,pos:a};for(let u of e.verify(r.sliceDoc(a,i),t))s.push(hZn(u,r.doc,c))}return s}}function tBe(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function hZn(e,t,n){let r=tBe(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?tBe(e.endLine,e.endColumn,t,n):r,message:e.message,source:e.ruleId?"eslint:"+e.ruleId:"eslint",severity:e.severity==1?"warning":"error"};if(e.fix){let{range:a,text:i}=e.fix,l=a[0]+n.pos-r,c=a[1]+n.pos-r;s.actions=[{name:"fix",apply(u,d){u.dispatch({changes:{from:d+l,to:d+c,insert:i},scrollIntoView:!0})}}]}return s}const XF=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:xCt,completionPath:gCt,esLint:fZn,javascript:DU,javascriptLanguage:om,jsxLanguage:$Ce,localCompletionSource:mCt,scopeCompletionSource:lZn,snippets:ACe,tsxLanguage:MCe,typescriptLanguage:PCe,typescriptSnippets:fCt},Symbol.toStringTag,{value:"Module"})),dP=["_blank","_self","_top","_parent"],lne=["ascii","utf-8","utf-16","latin1","latin1"],cne=["get","post","put","delete"],une=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],gh=["true","false"],nr={},pZn={a:{attrs:{href:null,ping:null,type:null,media:null,target:dP,hreflang:null}},abbr:nr,address:nr,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:nr,aside:nr,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:nr,base:{attrs:{href:null,target:dP}},bdi:nr,bdo:nr,blockquote:{attrs:{cite:null}},body:nr,br:nr,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:une,formmethod:cne,formnovalidate:["novalidate"],formtarget:dP,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:nr,center:nr,cite:nr,code:nr,col:{attrs:{span:null}},colgroup:{attrs:{span:null}},command:{attrs:{type:["command","checkbox","radio"],label:null,icon:null,radiogroup:null,command:null,title:null,disabled:["disabled"],checked:["checked"]}},data:{attrs:{value:null}},datagrid:{attrs:{disabled:["disabled"],multiple:["multiple"]}},datalist:{attrs:{data:null}},dd:nr,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:nr,div:nr,dl:nr,dt:nr,em:nr,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:nr,figure:nr,footer:nr,form:{attrs:{action:null,name:null,"accept-charset":lne,autocomplete:["on","off"],enctype:une,method:cne,novalidate:["novalidate"],target:dP}},h1:nr,h2:nr,h3:nr,h4:nr,h5:nr,h6:nr,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:nr,hgroup:nr,hr:nr,html:{attrs:{manifest:null}},i:nr,iframe:{attrs:{src:null,srcdoc:null,name:null,width:null,height:null,sandbox:["allow-top-navigation","allow-same-origin","allow-forms","allow-scripts"],seamless:["seamless"]}},img:{attrs:{alt:null,src:null,ismap:null,usemap:null,width:null,height:null,crossorigin:["anonymous","use-credentials"]}},input:{attrs:{alt:null,dirname:null,form:null,formaction:null,height:null,list:null,max:null,maxlength:null,min:null,name:null,pattern:null,placeholder:null,size:null,src:null,step:null,value:null,width:null,accept:["audio/*","video/*","image/*"],autocomplete:["on","off"],autofocus:["autofocus"],checked:["checked"],disabled:["disabled"],formenctype:une,formmethod:cne,formnovalidate:["novalidate"],formtarget:dP,multiple:["multiple"],readonly:["readonly"],required:["required"],type:["hidden","text","search","tel","url","email","password","datetime","date","month","week","time","datetime-local","number","range","color","checkbox","radio","file","submit","image","reset","button"]}},ins:{attrs:{cite:null,datetime:null}},kbd:nr,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:nr,li:{attrs:{value:null}},link:{attrs:{href:null,type:null,hreflang:null,media:null,sizes:["all","16x16","16x16 32x32","16x16 32x32 64x64"]}},map:{attrs:{name:null}},mark:nr,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:lne,name:["viewport","application-name","author","description","generator","keywords"],"http-equiv":["content-language","content-type","default-style","refresh"]}},meter:{attrs:{value:null,min:null,low:null,high:null,max:null,optimum:null}},nav:nr,noscript:nr,object:{attrs:{data:null,type:null,name:null,usemap:null,form:null,width:null,height:null,typemustmatch:["typemustmatch"]}},ol:{attrs:{reversed:["reversed"],start:null,type:["1","a","A","i","I"]},children:["li","script","template","ul","ol"]},optgroup:{attrs:{disabled:["disabled"],label:null}},option:{attrs:{disabled:["disabled"],label:null,selected:["selected"],value:null}},output:{attrs:{for:null,form:null,name:null}},p:nr,param:{attrs:{name:null,value:null}},pre:nr,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:nr,rt:nr,ruby:nr,samp:nr,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:lne}},section:nr,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:nr,source:{attrs:{src:null,type:null,media:null}},span:nr,strong:nr,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:nr,summary:nr,sup:nr,table:nr,tbody:nr,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:nr,textarea:{attrs:{dirname:null,form:null,maxlength:null,name:null,placeholder:null,rows:null,cols:null,autofocus:["autofocus"],disabled:["disabled"],readonly:["readonly"],required:["required"],wrap:["soft","hard"]}},tfoot:nr,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:nr,time:{attrs:{datetime:null}},title:nr,tr:nr,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:nr,video:{attrs:{src:null,poster:null,width:null,height:null,crossorigin:["anonymous","use-credentials"],preload:["auto","metadata","none"],autoplay:["autoplay"],mediagroup:["movie"],muted:["muted"],controls:["controls"]}},wbr:nr},wCt={accesskey:null,class:null,contenteditable:gh,contextmenu:null,dir:["ltr","rtl","auto"],draggable:["true","false","auto"],dropzone:["copy","move","link","string:","file:"],hidden:["hidden"],id:null,inert:["inert"],itemid:null,itemprop:null,itemref:null,itemscope:["itemscope"],itemtype:null,lang:["ar","bn","de","en-GB","en-US","es","fr","hi","id","ja","pa","pt","ru","tr","zh"],spellcheck:gh,autocorrect:gh,autocapitalize:gh,style:null,tabindex:null,title:null,translate:["yes","no"],rel:["stylesheet","alternate","author","bookmark","help","license","next","nofollow","noreferrer","prefetch","prev","search","tag"],role:"alert application article banner button cell checkbox complementary contentinfo dialog document feed figure form grid gridcell heading img list listbox listitem main navigation region row rowgroup search switch tab table tabpanel textbox timer".split(" "),"aria-activedescendant":null,"aria-atomic":gh,"aria-autocomplete":["inline","list","both","none"],"aria-busy":gh,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":gh,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":gh,"aria-hidden":gh,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":gh,"aria-multiselectable":gh,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":gh,"aria-relevant":null,"aria-required":gh,"aria-selected":["true","false","undefined"],"aria-setsize":null,"aria-sort":["ascending","descending","none","other"],"aria-valuemax":null,"aria-valuemin":null,"aria-valuenow":null,"aria-valuetext":null},SCt="beforeunload copy cut dragstart dragover dragleave dragenter dragend drag paste focus blur change click load mousedown mouseenter mouseleave mouseup keydown keyup resize scroll unload".split(" ").map(e=>"on"+e);for(let e of SCt)wCt[e]=null;class uD{constructor(t,n){this.tags={...pZn,...t},this.globalAttrs={...wCt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}uD.default=new uD;function wN(e,t,n=e.length){if(!t)return"";let r=t.firstChild,s=r&&r.getChild("TagName");return s?e.sliceString(s.from,Math.min(s.to,n)):""}function SN(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function kCt(e,t,n){let r=n.tags[wN(e,SN(t))];return r?.children||n.allTags}function DCe(e,t){let n=[];for(let r=SN(t);r&&!r.type.isTop;r=SN(r.parent)){let s=wN(e,r);if(s&&r.lastChild.name=="CloseTag")break;s&&n.indexOf(s)<0&&(t.name=="EndTag"||t.from>=r.firstChild.to)&&n.push(s)}return n}const OCt=/^[:\-\.\w\u00b7-\uffff]*$/;function nBe(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=SN(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:kCt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(DCe(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function rBe(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:DCe(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:OCt}}function mZn(e,t,n,r){let s=[],a=0;for(let i of kCt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of DCe(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function gZn(e,t,n,r,s){let a=SN(n),i=a?t.tags[wN(e.doc,a)]:null,l=i&&i.attrs?Object.keys(i.attrs):[],c=i&&i.globalAttrs===!1?l:l.length?l.concat(t.globalAttrNames):t.globalAttrNames;return{from:r,to:s,options:c.map(u=>({label:u,type:"property"})),validFor:OCt}}function vZn(e,t,n,r,s){var a;let i=(a=n.parent)===null||a===void 0?void 0:a.getChild("AttributeName"),l=[],c;if(i){let u=e.sliceDoc(i.from,i.to),d=t.globalAttrs[u];if(!d){let f=SN(n),h=f?t.tags[wN(e.doc,f)]:null;d=h?.attrs&&h.attrs[u]}if(d){let f=e.sliceDoc(r,s).toLowerCase(),h='"',p='"';/^['"]/.test(f)?(c=f[0]=='"'?/^[^"]*$/:/^[^']*$/,h="",p=e.sliceDoc(s,s+1)==f[0]?"":f[0],f=f.slice(1),r++):c=/^[^\s<>='"]*$/;for(let m of d)l.push({label:m,apply:h+m+p,type:"constant"})}}return{from:r,to:s,options:l,validFor:c}}function CCt(e,t){let{state:n,pos:r}=t,s=xi(n).resolveInner(r,-1),a=s.resolve(r);for(let i=r,l;a==s&&(l=s.childBefore(i));){let c=l.lastChild;if(!c||!c.type.isError||c.from<c.to)break;a=s=l,i=c.from}return s.name=="TagName"?s.parent&&/CloseTag$/.test(s.parent.name)?rBe(n,s,s.from,r):nBe(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?nBe(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?rBe(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?gZn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?vZn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?mZn(n,e,s,r):null}function yZn(e){return CCt(uD.default,e)}function bZn(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new uD(t,n):uD.default;return s=>CCt(r,s)}const xZn=om.parser.configure({top:"SingleExpression"}),_Ct=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:PCe.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:$Ce.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:MCe.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:xZn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:om.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:$U.parser}],ECt=[{name:"style",parser:$U.parser.configure({top:"Styles"})}].concat(SCt.map(e=>({name:e,parser:om.parser}))),TCt=pC.define({name:"html",parser:HHn.configure({props:[w_.add({Element(e){let t=/^(\s*)(<\/)?/.exec(e.textAfter);return e.node.to<=e.pos+t[0].length?e.continue():e.lineIndent(e.node.from)+(t[2]?0:e.unit)},"OpenTag CloseTag SelfClosingTag"(e){return e.column(e.node.from)+e.unit},Document(e){if(e.pos+/\s*/.exec(e.textAfter)[0].length<e.node.to)return e.continue();let t=null,n;for(let r=e.node;;){let s=r.lastChild;if(!s||s.name!="Element"||s.to!=r.to)break;t=r=s}return t&&!((n=t.lastChild)&&(n.name=="CloseTag"||n.name=="SelfClosingTag"))?e.lineIndent(t.from)+e.unit:null}}),S_.add({Element(e){let t=e.firstChild,n=e.lastChild;return!t||t.name!="OpenTag"?null:{from:t.to,to:n.name=="CloseTag"?n.from:e.to}}}),uOt.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),M9=TCt.configure({wrap:aCt(_Ct,ECt)});function wZn(e={}){let t="",n;e.matchClosingTags===!1&&(t="noMatch"),e.selfClosingTags===!0&&(t=(t?t+" ":"")+"selfClosing"),(e.nestedLanguages&&e.nestedLanguages.length||e.nestedAttributes&&e.nestedAttributes.length)&&(n=aCt((e.nestedLanguages||[]).concat(_Ct),(e.nestedAttributes||[]).concat(ECt)));let r=n?TCt.configure({wrap:n,dialect:t}):t?M9.configure({dialect:t}):M9;return new gC(r,[M9.data.of({autocomplete:bZn(e)}),e.autoCloseTags!==!1?SZn:[],DU().support,EWn().support])}const sBe=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),SZn=Rt.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!M9.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u,d,f;let h=i.doc.sliceString(c.from-1,c.to)==r,{head:p}=c,m=xi(i).resolveInner(p,-1),v;if(h&&r==">"&&m.name=="EndTag"){let y=m.parent;if(((d=(u=y.parent)===null||u===void 0?void 0:u.lastChild)===null||d===void 0?void 0:d.name)!="CloseTag"&&(v=wN(i.doc,y.parent,p))&&!sBe.has(v)){let b=p+(i.doc.sliceString(p,p+1)===">"?1:0),x=`</${v}>`;return{range:c,changes:{from:p,to:b,insert:x}}}}else if(h&&r=="/"&&m.name=="IncompleteCloseTag"){let y=m.parent;if(m.from==p-2&&((f=y.lastChild)===null||f===void 0?void 0:f.name)!="CloseTag"&&(v=wN(i.doc,y,p))&&!sBe.has(v)){let b=p+(i.doc.sliceString(p,p+1)===">"?1:0),x=`${v}>`;return{range:St.cursor(p+x.length,-1),changes:{from:p,to:b,insert:x}}}}return{range:c}});return l.changes.empty?!1:(e.dispatch([a,i.update(l,{userEvent:"input.complete",scrollIntoView:!0})]),!0)}),jCt=eZ({commentTokens:{block:{open:"<!--",close:"-->"}}}),NCt=new Lr,ICt=ZVn.configure({props:[S_.add(e=>!e.is("Block")||e.is("Document")||Pye(e)!=null||kZn(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),NCt.add(Pye),w_.add({Document:()=>null}),Kw.add({Document:jCt})]});function Pye(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function kZn(e){return e.name=="OrderedList"||e.name=="BulletList"}function OZn(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=Pye(r.type))!=null&&s<=t)break;n=r}return n.to}const CZn=Xkt.of((e,t,n)=>{for(let r=xi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(NCt);if(s==null)continue;let a=OZn(r,s);if(a>n)return{from:n,to:a}}return null});function LCe(e){return new Lh(jCt,e,[],"markdown")}const ACt=LCe(ICt),_Zn=ICt.configure([sHn,iHn,aHn,oHn,{props:[S_.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),bC=LCe(_Zn);function EZn(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=vg.matchLanguageName(e,n,!0),r instanceof vg)return r.support?r.support.language.parser:mC.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class dne{constructor(t,n,r,s,a,i,l){this.node=t,this.from=n,this.to=r,this.spaceBefore=s,this.spaceAfter=a,this.type=i,this.item=l}blank(t,n=!0){let r=this.spaceBefore+(this.node.name=="Blockquote"?">":"");if(t!=null){for(;r.length<t;)r+=" ";return r}else{for(let s=this.to-this.from-r.length-this.spaceAfter.length;s>0;s--)r+=" ";return r+(n?this.spaceAfter:"")}}marker(t,n){let r=this.node.name=="OrderedList"?String(+PCt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function RCt(e,t){let n=[],r=[];for(let s=e;s;s=s.parent){if(s.name=="FencedCode")return r;(s.name=="ListItem"||s.name=="Blockquote")&&n.push(s)}for(let s=n.length-1;s>=0;s--){let a=n[s],i,l=t.lineAt(a.from),c=a.from-l.from;if(a.name=="Blockquote"&&(i=/^ *>( ?)/.exec(l.text.slice(c))))r.push(new dne(a,c,c+i[0].length,"",i[1],">",null));else if(a.name=="ListItem"&&a.parent.name=="OrderedList"&&(i=/^( *)\d+([.)])( *)/.exec(l.text.slice(c)))){let u=i[3],d=i[0].length;u.length>=4&&(u=u.slice(0,u.length-4),d-=4),r.push(new dne(a.parent,c,c+d,i[1],u,i[2],a))}else if(a.name=="ListItem"&&a.parent.name=="BulletList"&&(i=/^( *)([-+*])( {1,4}\[[ xX]\])?( +)/.exec(l.text.slice(c)))){let u=i[4],d=i[0].length;u.length>4&&(u=u.slice(0,u.length-4),d-=4);let f=i[2];i[3]&&(f+=i[3].replace(/[xX]/," ")),r.push(new dne(a.parent,c,c+d,i[1],u,f,a))}}return r}function PCt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function fne(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=PCt(a,t),c=+l[2];if(s>=0){if(c!=s+1)return;n.push({from:a.from+l[1].length,to:a.from+l[0].length,insert:String(s+2+r)})}s=c}let i=a.nextSibling;if(!i)break;a=i}}function FCe(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(ZI)!=" ")return e;let r=Wg(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const $Ct=(e={})=>({state:t,dispatch:n})=>{let r=xi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!bC.isActiveAt(t,l.from,-1)&&!bC.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=RCt(r.resolveInner(c,-1),s);for(;d.length&&d[d.length-1].from>c-u.from;)d.pop();if(!d.length)return a={range:l};let f=d[d.length-1];if(f.to-f.spaceAfter.length>c-u.from)return a={range:l};let h=c>=f.to-f.spaceAfter.length&&!/\S/.test(u.text.slice(f.to));if(f.item&&h){let b=f.node.firstChild,x=f.node.getChild("ListItem","ListItem");if(b.to>=c||x&&x.to<c||u.from>0&&!/[^\s>]/.test(s.lineAt(u.from-1).text)||e.nonTightLists===!1){let w=d.length>1?d[d.length-2]:null,k,O="";w&&w.item?(k=u.from+w.from,O=w.marker(s,1)):k=u.from+(w?w.to:0);let _=[{from:k,to:c,insert:O}];return f.node.name=="OrderedList"&&fne(f.item,s,_,-2),w&&w.node.name=="OrderedList"&&fne(w.item,s,_),{range:St.cursor(k+O.length),changes:_}}else{let w=iBe(d,t,u);return{range:St.cursor(c+w.length+1),changes:{from:u.from,insert:w+t.lineBreak}}}}if(f.node.name=="Blockquote"&&h&&u.from){let b=s.lineAt(u.from-1),x=/>\s*$/.exec(b.text);if(x&&x.index==f.from){let w=t.changes([{from:b.from+x.index,to:b.to},{from:u.from+f.from,to:u.to}]);return{range:l.map(w),changes:w}}}let p=[];f.node.name=="OrderedList"&&fne(f.item,s,p);let m=f.item&&f.item.from<u.from,v="";if(!m||/^[\s\d.)\-+*>]*/.exec(u.text)[0].length>=f.to)for(let b=0,x=d.length-1;b<=x;b++)v+=b==x&&!m?d[b].marker(s,1):d[b].blank(b<x?Wg(u.text,4,d[b+1].from)-v.length:null);let y=c;for(;y>u.from&&/\s/.test(u.text.charAt(y-u.from-1));)y--;return v=FCe(v,t),TZn(f.node,t.doc)&&(v=iBe(d,t,u)+t.lineBreak+v),p.push({from:y,to:c,insert:t.lineBreak+v}),{range:St.cursor(y+v.length+1),changes:p}});return a?!1:(n(t.update(i,{scrollIntoView:!0,userEvent:"input"})),!0)},MCt=$Ct();function aBe(e){return e.name=="QuoteMark"||e.name=="ListMark"}function TZn(e,t){if(e.name!="OrderedList"&&e.name!="BulletList")return!1;let n=e.firstChild,r=e.getChild("ListItem","ListItem");if(!r)return!1;let s=t.lineAt(n.to),a=t.lineAt(r.from),i=/^[\s>]*$/.test(s.text);return s.number+(i?0:1)<a.number}function iBe(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?Wg(n.text,4,e[s+1].from)-r.length:null,s<a);return FCe(r,t)}function jZn(e,t){let n=e.resolveInner(t,-1),r=t;aBe(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(aBe(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const DCt=({state:e,dispatch:t})=>{let n=xi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&bC.isActiveAt(e,a.from)){let c=l.lineAt(i),u=RCt(jZn(n,i),l);if(u.length){let d=u[u.length-1],f=d.to-d.spaceAfter.length+(d.spaceAfter?1:0);if(i-c.from>f&&!/\S/.test(c.text.slice(f,i-c.from)))return{range:St.cursor(c.from+f),changes:{from:c.from+f,to:i}};if(i-c.from==f&&(!d.item||c.from<=d.item.from||!/\S/.test(c.text.slice(0,d.to)))){let h=c.from+d.from;if(d.item&&d.node.from<d.item.from&&/\S/.test(c.text.slice(d.from,d.to))){let p=d.blank(Wg(c.text,4,d.to)-Wg(c.text,4,d.from));return h==c.from&&(p=FCe(p,e)),{range:St.cursor(h+p.length),changes:{from:h,to:c.from+d.to,insert:p}}}if(h<i)return{range:St.cursor(h),changes:{from:h,to:i}}}}}return r={range:a}});return r?!1:(t(e.update(s,{scrollIntoView:!0,userEvent:"delete"})),!0)},LCt=[{key:"Enter",run:MCt},{key:"Backspace",run:DCt}],FCt=wZn({matchClosingTags:!1});function zCe(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=ACt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=FCt}=e;if(!(s instanceof sZ))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,CZn],d;i&&u.push(zCt),n instanceof gC?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?EZn(t,d):void 0;c.push(QVn({codeParser:f,htmlParser:l.language.parser})),r&&u.push(lp.high(WI.of(LCt)));let h=LCe(s.configure(c));return a&&u.push(h.data.of({autocomplete:NZn})),new gC(h,u)}function NZn(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=xi(t).resolveInner(n,-1);for(;s&&!s.type.isTop;){if(s.name=="CodeBlock"||s.name=="FencedCode"||s.name=="ProcessingInstructionBlock"||s.name=="CommentBlock"||s.name=="Link"||s.name=="Image")return null;s=s.parent}return{from:n-r[0].length,to:n,options:IZn(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let hne=null;function IZn(){if(hne)return hne;let e=yZn(new gCe(ps.create({extensions:FCt}),0,!0));return hne=e?e.options:[]}const AZn=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,zCt=Rt.domEventHandlers({paste:(e,t)=>{var n;let{main:r}=t.state.selection;if(r.empty)return!1;let s=(n=e.clipboardData)===null||n===void 0?void 0:n.getData("text/plain");if(!s||!/^(https?:\/\/|mailto:|xmpp:|www\.)/.test(s)||(/^www\./.test(s)&&(s="https://"+s),!bC.isActiveAt(t.state,r.from,1)))return!1;let a=xi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||AZn.test(l.name))&&(i=!0)},leave:l=>{l.to<r.to&&(i=!0)}}),i?!1:(t.dispatch({changes:[{from:r.from,insert:"["},{from:r.to,insert:`](${s})`}],userEvent:"input.paste",scrollIntoView:!0}),!0)}}),RZn=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:ACt,deleteMarkupBackward:DCt,insertNewlineContinueMarkup:MCt,insertNewlineContinueMarkupCommand:$Ct,markdown:zCe,markdownKeymap:LCt,markdownLanguage:bC,pasteURLAsLink:zCt},Symbol.toStringTag,{value:"Module"}));function xC(){return xC=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},xC.apply(null,arguments)}var PZn=e=>{var t=e.theme,n=e.settings,r=n===void 0?{}:n,s=e.styles,a=s===void 0?[]:s,i={".cm-gutters":{}},l={};r.background&&(l.backgroundColor=r.background),r.backgroundImage&&(l.backgroundImage=r.backgroundImage),r.foreground&&(l.color=r.foreground),r.fontSize&&(l.fontSize=r.fontSize),(r.background||r.foreground)&&(i["&"]=l),r.fontFamily&&(i["&.cm-editor .cm-scroller"]={fontFamily:r.fontFamily}),r.gutterBackground&&(i[".cm-gutters"].backgroundColor=r.gutterBackground),r.gutterForeground&&(i[".cm-gutters"].color=r.gutterForeground),r.gutterBorder&&(i[".cm-gutters"].borderRightColor=r.gutterBorder),r.caret&&(i[".cm-content"]={caretColor:r.caret},i[".cm-cursor, .cm-dropCursor"]={borderLeftColor:r.caret});var c={};r.gutterActiveForeground&&(c.color=r.gutterActiveForeground),r.lineHighlight&&(i[".cm-activeLine"]={backgroundColor:r.lineHighlight},c.backgroundColor=r.lineHighlight),i[".cm-activeLineGutter"]=c,r.selection&&(i["&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection"]={background:r.selection+" !important"}),r.selectionMatch&&(i["& .cm-selectionMatch"]={backgroundColor:r.selectionMatch});var u=Rt.theme(i,{dark:t==="dark"}),d=rv.define(a),f=[u,T1(d)];return f},$Zn={background:"#282a36",foreground:"#f8f8f2",caret:"#f8f8f0",selection:"rgba(255, 255, 255, 0.1)",selectionMatch:"rgba(255, 255, 255, 0.2)",gutterBackground:"#282a36",gutterForeground:"#6D8A88",gutterBorder:"transparent",lineHighlight:"rgba(255, 255, 255, 0.1)"},MZn=[{tag:ue.comment,color:"#6272a4"},{tag:ue.string,color:"#f1fa8c"},{tag:ue.atom,color:"#bd93f9"},{tag:ue.meta,color:"#f8f8f2"},{tag:[ue.keyword,ue.operator,ue.tagName],color:"#ff79c6"},{tag:[ue.function(ue.propertyName),ue.propertyName],color:"#66d9ef"},{tag:[ue.definition(ue.variableName),ue.function(ue.variableName),ue.className,ue.attributeName],color:"#50fa7b"},{tag:ue.atom,color:"#bd93f9"}],QI=e=>{var t=e||{},n=t.theme,r=n===void 0?"dark":n,s=t.settings,a=s===void 0?{}:s,i=t.styles,l=i===void 0?[]:i;return PZn({theme:r,settings:xC({},$Zn,a),styles:[...MZn,...l]})};QI();function BCt(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}const DZn=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=UCe(e.state,n.from);return r.line?LZn(e):r.block?zZn(e):!1};function BCe(e,t){return({state:n,dispatch:r})=>{if(n.readOnly)return!1;let s=e(t,n);return s?(r(n.update(s)),!0):!1}}const LZn=BCe(qZn,0),FZn=BCe(UCt,0),zZn=BCe((e,t)=>UCt(e,t,UZn(t)),0);function UCe(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const fP=50;function BZn(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-fP,r),i=e.sliceDoc(s,s+fP),l=/\s*$/.exec(a)[0].length,c=/^\s*/.exec(i)[0].length,u=a.length-l;if(a.slice(u-t.length,u)==t&&i.slice(c,c+n.length)==n)return{open:{pos:r-l,margin:l&&1},close:{pos:s+c,margin:c&&1}};let d,f;s-r<=2*fP?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+fP),f=e.sliceDoc(s-fP,s));let h=/^\s*/.exec(d)[0].length,p=/\s*$/.exec(f)[0].length,m=f.length-p-n.length;return d.slice(h,h+t.length)==t&&f.slice(m,m+n.length)==n?{open:{pos:r+h+t.length,margin:/\s/.test(d.charAt(h+t.length))?1:0},close:{pos:s-p-n.length,margin:/\s/.test(f.charAt(m-1))?1:0}}:null}function UZn(e){let t=[];for(let n of e.selection.ranges){let r=e.doc.lineAt(n.from),s=n.to<=r.to?r:e.doc.lineAt(n.to);s.from>r.from&&s.from==n.to&&(s=n.to==r.to+1?r:e.doc.lineAt(n.to-1));let a=t.length-1;a>=0&&t[a].to>r.from?t[a].to=s.to:t.push({from:r.from+/^\s*/.exec(r.text)[0].length,to:s.to})}return t}function UCt(e,t,n=t.selection.ranges){let r=n.map(a=>UCe(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>BZn(t,r[i],a.from,a.to));if(e!=2&&!s.every(a=>a))return{changes:t.changes(n.map((a,i)=>s[i]?[]:[{from:a.from,insert:r[i].open+" "},{from:a.to,insert:" "+r[i].close}]))};if(e!=1&&s.some(a=>a)){let a=[];for(let i=0,l;i<s.length;i++)if(l=s[i]){let c=r[i],{open:u,close:d}=l;a.push({from:u.pos-c.open.length,to:u.pos+u.margin},{from:d.pos-d.margin,to:d.pos+c.close.length})}return{changes:a}}return null}function qZn(e,t,n=t.selection.ranges){let r=[],s=-1;e:for(let{from:a,to:i}of n){let l=r.length,c=1e9,u;for(let d=a;d<=i;){let f=t.doc.lineAt(d);if(u==null&&(u=UCe(t,f.from).line,!u))continue e;if(f.from>s&&(a==i||i>f.from)){s=f.from;let h=/^\s*/.exec(f.text)[0].length,p=h==f.length,m=f.text.slice(h,h+u.length)==u?h:-1;h<f.text.length&&h<c&&(c=h),r.push({line:f,comment:m,token:u,indent:h,empty:p,single:!1})}d=f.to+1}if(c<1e9)for(let d=l;d<r.length;d++)r[d].indent<r[d].line.text.length&&(r[d].indent=c);r.length==l+1&&(r[l].single=!0)}if(e!=2&&r.some(a=>a.comment<0&&(!a.empty||a.single))){let a=[];for(let{line:l,token:c,indent:u,empty:d,single:f}of r)(f||!d)&&a.push({from:l.from+u,insert:c+" "});let i=t.changes(a);return{changes:i,selection:t.selection.map(i,1)}}else if(e!=1&&r.some(a=>a.comment>=0)){let a=[];for(let{line:i,comment:l,token:c}of r)if(l>=0){let u=i.from+l,d=u+c.length;i.text[d-i.from]==" "&&d++,a.push({from:u,to:d})}return{changes:a}}return null}const $ye=Xy.define(),VZn=Xy.define(),HZn=On.define(),qCt=On.define({combine(e){return Jy(e,{minDepth:100,newGroupDelay:500,joinToEvent:(t,n)=>n},{minDepth:Math.max,newGroupDelay:Math.min,joinToEvent:(t,n)=>(r,s)=>t(r,s)||n(r,s)})}}),VCt=wl.define({create(){return uy.empty},update(e,t){let n=t.state.facet(qCt),r=t.annotation($ye);if(r){let c=jf.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=LU(d,d.length,n.minDepth,c):d=ZCt(d,t.startState.selection),new uy(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(VZn);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(Ml.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=jf.fromTransaction(t),i=t.annotation(Ml.time),l=t.annotation(Ml.userEvent);return a?e=e.addChanges(a,i,l,n,t):t.selection&&(e=e.addSelection(t.startState.selection,i,l,n.newGroupDelay)),(s=="full"||s=="after")&&(e=e.isolate()),e},toJSON(e){return{done:e.done.map(t=>t.toJSON()),undone:e.undone.map(t=>t.toJSON())}},fromJSON(e){return new uy(e.done.map(jf.fromJSON),e.undone.map(jf.fromJSON))}});function WZn(e={}){return[VCt,qCt.of(e),Rt.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?HCt:t.inputType=="historyRedo"?Mye:null;return r?(t.preventDefault(),r(n)):!1}})]}function aZ(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(VCt,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const HCt=aZ(0,!1),Mye=aZ(1,!1),ZZn=aZ(0,!0),GZn=aZ(1,!0);class jf{constructor(t,n,r,s,a){this.changes=t,this.effects=n,this.mapped=r,this.startSelection=s,this.selectionsAfter=a}setSelAfter(t){return new jf(this.changes,this.effects,this.mapped,this.startSelection,t)}toJSON(){var t,n,r;return{changes:(t=this.changes)===null||t===void 0?void 0:t.toJSON(),mapped:(n=this.mapped)===null||n===void 0?void 0:n.toJSON(),startSelection:(r=this.startSelection)===null||r===void 0?void 0:r.toJSON(),selectionsAfter:this.selectionsAfter.map(s=>s.toJSON())}}static fromJSON(t){return new jf(t.changes&&Pl.fromJSON(t.changes),[],t.mapped&&Sy.fromJSON(t.mapped),t.startSelection&&St.fromJSON(t.startSelection),t.selectionsAfter.map(St.fromJSON))}static fromTransaction(t,n){let r=Xp;for(let s of t.startState.facet(HZn)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new jf(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,Xp)}static selection(t){return new jf(void 0,Xp,void 0,void 0,t)}}function LU(e,t,n,r){let s=t+1>n+20?t-n-1:0,a=e.slice(s,t);return a.push(r),a}function QZn(e,t){let n=[],r=!1;return e.iterChangedRanges((s,a)=>n.push(s,a)),t.iterChangedRanges((s,a,i,l)=>{for(let c=0;c<n.length;){let u=n[c++],d=n[c++];l>=u&&i<=d&&(r=!0)}}),r}function YZn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function WCt(e,t){return e.length?t.length?e.concat(t):e:t}const Xp=[],KZn=200;function ZCt(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-KZn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),LU(e,e.length-1,1e9,n.setSelAfter(r)))}else return[jf.selection([t])]}function XZn(e){let t=e[e.length-1],n=e.slice();return n[e.length-1]=t.setSelAfter(t.selectionsAfter.slice(0,t.selectionsAfter.length-1)),n}function pne(e,t){if(!e.length)return e;let n=e.length,r=Xp;for(;n;){let s=JZn(e[n-1],t,r);if(s.changes&&!s.changes.empty||s.effects.length){let a=e.slice(0,n);return a[n-1]=s,a}else t=s.mapped,n--,r=s.selectionsAfter}return r.length?[jf.selection(r)]:Xp}function JZn(e,t,n){let r=WCt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):Xp,n);if(!e.changes)return jf.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new jf(s,pr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const eGn=/^(input\.type|delete)($|\.)/;class uy{constructor(t,n,r=0,s=void 0){this.done=t,this.undone=n,this.prevTime=r,this.prevUserEvent=s}isolate(){return this.prevTime?new uy(this.done,this.undone):this}addChanges(t,n,r,s,a){let i=this.done,l=i[i.length-1];return l&&l.changes&&!l.changes.empty&&t.changes&&(!r||eGn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,QZn(l.changes,t.changes))||r=="input.type.compose")?i=LU(i,i.length-1,s.minDepth,new jf(t.changes.compose(l.changes),WCt(pr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,Xp)):i=LU(i,i.length,s.minDepth,t),new uy(i,Xp,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:Xp;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&YZn(a[a.length-1],t)?this:new uy(ZCt(this.done,t),this.undone,n,r)}addMapping(t){return new uy(pne(this.done,t),pne(this.undone,t),this.prevTime,this.prevUserEvent)}pop(t,n,r){let s=t==0?this.done:this.undone;if(s.length==0)return null;let a=s[s.length-1],i=a.selectionsAfter[0]||(a.startSelection?a.startSelection.map(a.changes.invertedDesc,1):n.selection);if(r&&a.selectionsAfter.length)return n.update({selection:a.selectionsAfter[a.selectionsAfter.length-1],annotations:$ye.of({side:t,rest:XZn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?Xp:s.slice(0,s.length-1);return a.mapped&&(l=pne(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:$ye.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}uy.empty=new uy(Xp,Xp);const tGn=[{key:"Mod-z",run:HCt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:Mye,preventDefault:!0},{linux:"Ctrl-Shift-z",run:Mye,preventDefault:!0},{key:"Mod-u",run:ZZn,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:GZn,preventDefault:!0}];function YI(e,t){return St.create(e.ranges.map(t),e.mainIndex)}function sv(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function av({state:e,dispatch:t},n){let r=YI(e.selection,n);return r.eq(e.selection,!0)?!1:(t(sv(e,r)),!0)}function iZ(e,t){return St.cursor(t?e.to:e.from)}function GCt(e,t){return av(e,n=>n.empty?e.moveByChar(n,t):iZ(n,t))}function od(e){return e.textDirectionAt(e.state.selection.main.head)==Ei.LTR}const QCt=e=>GCt(e,!od(e)),YCt=e=>GCt(e,od(e));function KCt(e,t){return av(e,n=>n.empty?e.moveByGroup(n,t):iZ(n,t))}const nGn=e=>KCt(e,!od(e)),rGn=e=>KCt(e,od(e));function sGn(e,t,n){if(t.type.prop(n))return!0;let r=t.to-t.from;return r&&(r>2||/[^\s,.;:]/.test(e.sliceDoc(t.from,t.to)))||t.firstChild}function oZ(e,t,n){let r=xi(e).resolveInner(t.head),s=n?Lr.closedBy:Lr.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;sGn(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?cy(e,r.from,1):cy(e,r.to,-1))&&i.matched?l=n?i.end.to:i.end.from:l=n?r.to:r.from,St.cursor(l,n?-1:1)}const aGn=e=>av(e,t=>oZ(e.state,t,!od(e))),iGn=e=>av(e,t=>oZ(e.state,t,od(e)));function XCt(e,t){return av(e,n=>{if(!n.empty)return iZ(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const JCt=e=>XCt(e,!1),e_t=e=>XCt(e,!0);function t_t(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(Rt.scrollMargins)){let i=a(e);i?.top&&(n=Math.max(i?.top,n)),i?.bottom&&(r=Math.max(i?.bottom,r))}s=e.scrollDOM.clientHeight-n-r}else s=(e.dom.ownerDocument.defaultView||window).innerHeight;return{marginTop:n,marginBottom:r,selfScroll:t,height:Math.max(e.defaultLineHeight,s-5)}}function n_t(e,t){let n=t_t(e),{state:r}=e,s=YI(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):iZ(i,t));if(s.eq(r.selection))return!1;let a;if(n.selfScroll){let i=e.coordsAtPos(r.selection.main.head),l=e.scrollDOM.getBoundingClientRect(),c=l.top+n.marginTop,u=l.bottom-n.marginBottom;i&&i.top>c&&i.bottom<u&&(a=Rt.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(sv(r,s),{effects:a}),!0}const oBe=e=>n_t(e,!1),Dye=e=>n_t(e,!0);function j1(e,t,n){let r=e.lineBlockAt(t.head),s=e.moveToLineBoundary(t,n);if(s.head==t.head&&s.head!=(n?r.to:r.from)&&(s=e.moveToLineBoundary(t,n,!1)),!n&&s.head==r.from&&r.length){let a=/^\s*/.exec(e.state.sliceDoc(r.from,Math.min(r.from+100,r.to)))[0].length;a&&t.head!=r.from+a&&(s=St.cursor(r.from+a))}return s}const oGn=e=>av(e,t=>j1(e,t,!0)),lGn=e=>av(e,t=>j1(e,t,!1)),cGn=e=>av(e,t=>j1(e,t,!od(e))),uGn=e=>av(e,t=>j1(e,t,od(e))),dGn=e=>av(e,t=>St.cursor(e.lineBlockAt(t.head).from,1)),fGn=e=>av(e,t=>St.cursor(e.lineBlockAt(t.head).to,-1));function hGn(e,t,n){let r=!1,s=YI(e.selection,a=>{let i=cy(e,a.head,-1)||cy(e,a.head,1)||a.head>0&&cy(e,a.head-1,1)||a.head<e.doc.length&&cy(e,a.head+1,-1);if(!i||!i.end)return a;r=!0;let l=i.start.from==a.head?i.end.to:i.end.from;return St.cursor(l)});return r?(t(sv(e,s)),!0):!1}const pGn=({state:e,dispatch:t})=>hGn(e,t);function Dm(e,t,n){let r=YI(e.state.selection,s=>{s.undirectional&&s.head>=s.anchor!=t&&(s=St.range(s.head,s.anchor));let a=n(s);return St.range(s.anchor,a.head,a.goalColumn,a.bidiLevel||void 0,a.assoc)});return r.eq(e.state.selection)?!1:(e.dispatch(sv(e.state,r)),!0)}function r_t(e,t){return Dm(e,t,n=>e.moveByChar(n,t))}const s_t=e=>r_t(e,!od(e)),a_t=e=>r_t(e,od(e));function i_t(e,t){return Dm(e,t,n=>e.moveByGroup(n,t))}const mGn=e=>i_t(e,!od(e)),gGn=e=>i_t(e,od(e)),vGn=e=>{let t=!od(e);return Dm(e,t,n=>oZ(e.state,n,t))},yGn=e=>{let t=od(e);return Dm(e,t,n=>oZ(e.state,n,t))};function o_t(e,t){return Dm(e,t,n=>e.moveVertically(n,t))}const l_t=e=>o_t(e,!1),c_t=e=>o_t(e,!0);function u_t(e,t){return Dm(e,t,n=>e.moveVertically(n,t,t_t(e).height))}const lBe=e=>u_t(e,!1),cBe=e=>u_t(e,!0),bGn=e=>Dm(e,!0,t=>j1(e,t,!0)),xGn=e=>Dm(e,!1,t=>j1(e,t,!1)),wGn=e=>{let t=!od(e);return Dm(e,t,n=>j1(e,n,t))},SGn=e=>{let t=od(e);return Dm(e,t,n=>j1(e,n,t))},kGn=e=>Dm(e,!1,t=>St.cursor(e.lineBlockAt(t.head).from)),OGn=e=>Dm(e,!0,t=>St.cursor(e.lineBlockAt(t.head).to)),uBe=({state:e,dispatch:t})=>(t(sv(e,{anchor:0})),!0),dBe=({state:e,dispatch:t})=>(t(sv(e,{anchor:e.doc.length})),!0),fBe=({state:e,dispatch:t})=>(t(sv(e,{anchor:e.selection.main.anchor,head:0})),!0),hBe=({state:e,dispatch:t})=>(t(sv(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),CGn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),_Gn=({state:e,dispatch:t})=>{let n=lZ(e).map(({from:r,to:s})=>St.range(r,Math.min(s+1,e.doc.length)));return t(e.update({selection:St.create(n),userEvent:"select"})),!0},EGn=({state:e,dispatch:t})=>{let n=YI(e.selection,r=>{let s=xi(e),a=s.resolveStack(r.from,1);if(r.empty){let i=s.resolveStack(r.from,-1);i.node.from>=a.node.from&&i.node.to<=a.node.to&&(a=i)}for(let i=a;i;i=i.next){let{node:l}=i;if((l.from<r.from&&l.to>=r.to||l.to>r.to&&l.from<=r.from)&&i.next)return St.range(l.to,l.from)}return r});return n.eq(e.selection)?!1:(t(sv(e,n)),!0)};function d_t(e,t){let{state:n}=e,r=n.selection,s=n.selection.ranges.slice();for(let a of n.selection.ranges){let i=n.doc.lineAt(a.head);if(t?i.to<e.state.doc.length:i.from>0)for(let l=a;;){let c=e.moveVertically(l,t);if(c.head<i.from||c.head>i.to){s.some(u=>u.head==c.head)||s.push(c);break}else{if(c.head==l.head)break;l=c}}}return s.length==r.ranges.length?!1:(e.dispatch(sv(n,St.create(s,s.length-1))),!0)}const TGn=e=>d_t(e,!1),jGn=e=>d_t(e,!0),NGn=({state:e,dispatch:t})=>{let n=e.selection,r=null;return n.ranges.length>1?r=St.create([n.main]):n.main.empty||(r=St.create([St.cursor(n.main.head)])),r?(t(sv(e,r)),!0):!1};function AL(e,t){if(e.state.readOnly)return!1;let n="delete.selection",{state:r}=e,s=r.changeByRange(a=>{let{from:i,to:l}=a;if(i==l){let c=t(a);c<i?(n="delete.backward",c=JF(e,c,!1)):c>i&&(n="delete.forward",c=JF(e,c,!0)),i=Math.min(i,c),l=Math.max(l,c)}else i=JF(e,i,!1),l=JF(e,l,!0);return i==l?{range:a}:{changes:{from:i,to:l},range:St.cursor(i,i<a.head?-1:1)}});return s.changes.empty?!1:(e.dispatch(r.update(s,{scrollIntoView:!0,userEvent:n,effects:n=="delete.selection"?Rt.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function JF(e,t,n){if(e instanceof Rt)for(let r of e.state.facet(Rt.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const f_t=(e,t,n)=>AL(e,r=>{let s=r.from,{state:a}=e,i=a.doc.lineAt(s),l,c;if(n&&!t&&s>i.from&&s<i.from+200&&!/[^ \t]/.test(l=i.text.slice(0,s-i.from))){if(l[l.length-1]==" ")return s-1;let u=Wg(l,a.tabSize),d=u%vC(a)||vC(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=Nc(i.text,s-i.from,t,t)+i.from,c==s&&i.number!=(t?a.doc.lines:1)?c+=t?1:-1:!t&&/[\ufe00-\ufe0f]/.test(i.text.slice(c-i.from,s-i.from))&&(c=Nc(i.text,c-i.from,!1,!1)+i.from);return c}),Lye=e=>f_t(e,!1,!0),h_t=e=>f_t(e,!0,!1),p_t=(e,t)=>AL(e,n=>{let r=n.head,{state:s}=e,a=s.doc.lineAt(r),i=s.charCategorizer(r);for(let l=null;;){if(r==(t?a.to:a.from)){r==n.head&&a.number!=(t?s.doc.lines:1)&&(r+=t?1:-1);break}let c=Nc(a.text,r-a.from,t)+a.from,u=a.text.slice(Math.min(r,c)-a.from,Math.max(r,c)-a.from),d=i(u);if(l!=null&&d!=l)break;(u!=" "||r!=n.head)&&(l=d),r=c}return r}),m_t=e=>p_t(e,!1),IGn=e=>p_t(e,!0),AGn=e=>AL(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),RGn=e=>AL(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),PGn=e=>AL(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),$Gn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>({changes:{from:r.from,to:r.to,insert:ea.of(["",""])},range:St.cursor(r.from)}));return t(e.update(n,{scrollIntoView:!0,userEvent:"input"})),!0},MGn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=e.changeByRange(r=>{if(!r.empty||r.from==0||r.from==e.doc.length)return{range:r};let s=r.from,a=e.doc.lineAt(s),i=s==a.from?s-1:Nc(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:Nc(a.text,s-a.from,!0)+a.from;return{changes:{from:i,to:l,insert:e.doc.slice(s,l).append(e.doc.slice(i,s))},range:St.cursor(l)}});return n.changes.empty?!1:(t(e.update(n,{scrollIntoView:!0,userEvent:"move.character"})),!0)};function lZ(e){let t=[],n=-1;for(let r of e.selection.ranges){let s=e.doc.lineAt(r.from),a=e.doc.lineAt(r.to);if(!r.empty&&r.to==a.from&&(a=e.doc.lineAt(r.to-1)),n>=s.number){let i=t[t.length-1];i.to=a.to,i.ranges.push(r)}else t.push({from:s.from,to:a.to,ranges:[r]});n=a.number+1}return t}function g_t(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of lZ(e)){if(n?a.to==e.doc.length:a.from==0)continue;let i=e.doc.lineAt(n?a.to+1:a.from-1),l=i.length+1;if(n){r.push({from:a.to,to:i.to},{from:a.from,insert:i.text+e.lineBreak});for(let c of a.ranges)s.push(St.range(Math.min(e.doc.length,c.anchor+l),Math.min(e.doc.length,c.head+l)))}else{r.push({from:i.from,to:a.from},{from:a.to,insert:e.lineBreak+i.text});for(let c of a.ranges)s.push(St.range(c.anchor-l,c.head-l))}}return r.length?(t(e.update({changes:r,scrollIntoView:!0,selection:St.create(s,e.selection.mainIndex),userEvent:"move.line"})),!0):!1}const DGn=({state:e,dispatch:t})=>g_t(e,t,!1),LGn=({state:e,dispatch:t})=>g_t(e,t,!0);function v_t(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of lZ(e))n?r.push({from:a.from,insert:e.doc.slice(a.from,a.to)+e.lineBreak}):r.push({from:a.to,insert:e.lineBreak+e.doc.slice(a.from,a.to)});let s=e.changes(r);return t(e.update({changes:s,selection:e.selection.map(s,n?1:-1),scrollIntoView:!0,userEvent:"input.copyline"})),!0}const FGn=({state:e,dispatch:t})=>v_t(e,t,!1),zGn=({state:e,dispatch:t})=>v_t(e,t,!0),BGn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(lZ(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=YI(t.selection,s=>{let a;if(e.lineWrapping){let i=e.lineBlockAt(s.head),l=e.coordsAtPos(s.head,s.assoc||1);l&&(a=i.bottom+e.documentTop-l.bottom+e.defaultLineHeight/2)}return e.moveVertically(s,!0,a)}).map(n);return e.dispatch({changes:n,selection:r,scrollIntoView:!0,userEvent:"delete.line"}),!0};function UGn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=xi(e).resolveInner(t),r=n.childBefore(t),s=n.childAfter(t),a;return r&&s&&r.to<=t&&s.from>=t&&(a=r.type.prop(Lr.closedBy))&&a.indexOf(s.name)>-1&&e.doc.lineAt(r.to).from==e.doc.lineAt(s.from).from&&!/\S/.test(e.sliceDoc(r.to,s.from))?{from:r.to,to:s.from}:null}const pBe=y_t(!1),qGn=y_t(!0);function y_t(e){return({state:t,dispatch:n})=>{if(t.readOnly)return!1;let r=t.changeByRange(s=>{let{from:a,to:i}=s,l=t.doc.lineAt(a),c=!e&&a==i&&UGn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new tZ(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=uCe(u,a);for(d==null&&(d=Wg(/^\s*/.exec(t.doc.lineAt(a).text)[0],t.tabSize));i<l.to&&/\s/.test(l.text[i-l.from]);)i++;c?{from:a,to:i}=c:a>l.from&&a<l.from+100&&!/\S/.test(l.text.slice(0,a))&&(a=l.from);let f=["",nD(t,d)];return c&&f.push(nD(t,u.lineIndent(l.from,-1))),{changes:{from:a,to:i,insert:ea.of(f)},range:St.cursor(a+1+f[1].length)}});return n(t.update(r,{scrollIntoView:!0,userEvent:"input"})),!0}}function qCe(e,t){let n=-1;return e.changeByRange(r=>{let s=[];for(let i=r.from;i<=r.to;){let l=e.doc.lineAt(i);l.number>n&&(r.empty||r.to>l.from)&&(t(l,s,r),n=l.number),i=l.to+1}let a=e.changes(s);return{changes:s,range:St.range(a.mapPos(r.anchor,1),a.mapPos(r.head,1))}})}const VGn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new tZ(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=qCe(e,(a,i,l)=>{let c=uCe(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=nD(e,c);(u!=d||l.from<a.from+u.length)&&(n[a.from]=c,i.push({from:a.from,to:a.from+u.length,insert:d}))});return s.changes.empty||t(e.update(s,{userEvent:"indent"})),!0},b_t=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(qCe(e,(n,r)=>{r.push({from:n.from,insert:e.facet(ZI)})}),{userEvent:"input.indent"})),!0),x_t=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(qCe(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=Wg(s,e.tabSize),i=0,l=nD(e,Math.max(0,a-vC(e)));for(;i<s.length&&i<l.length&&s.charCodeAt(i)==l.charCodeAt(i);)i++;r.push({from:n.from+i,to:n.from+s.length,insert:l.slice(i)})}),{userEvent:"delete.dedent"})),!0),HGn=e=>(e.setTabFocusMode(),!0),WGn=[{key:"Ctrl-b",run:QCt,shift:s_t,preventDefault:!0},{key:"Ctrl-f",run:YCt,shift:a_t},{key:"Ctrl-p",run:JCt,shift:l_t},{key:"Ctrl-n",run:e_t,shift:c_t},{key:"Ctrl-a",run:dGn,shift:kGn},{key:"Ctrl-e",run:fGn,shift:OGn},{key:"Ctrl-d",run:h_t},{key:"Ctrl-h",run:Lye},{key:"Ctrl-k",run:AGn},{key:"Ctrl-Alt-h",run:m_t},{key:"Ctrl-o",run:$Gn},{key:"Ctrl-t",run:MGn},{key:"Ctrl-v",run:Dye}],ZGn=[{key:"ArrowLeft",run:QCt,shift:s_t,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:nGn,shift:mGn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:cGn,shift:wGn,preventDefault:!0},{key:"ArrowRight",run:YCt,shift:a_t,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:rGn,shift:gGn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:uGn,shift:SGn,preventDefault:!0},{key:"ArrowUp",run:JCt,shift:l_t,preventDefault:!0},{mac:"Cmd-ArrowUp",run:uBe,shift:fBe},{mac:"Ctrl-ArrowUp",run:oBe,shift:lBe},{key:"ArrowDown",run:e_t,shift:c_t,preventDefault:!0},{mac:"Cmd-ArrowDown",run:dBe,shift:hBe},{mac:"Ctrl-ArrowDown",run:Dye,shift:cBe},{key:"PageUp",run:oBe,shift:lBe},{key:"PageDown",run:Dye,shift:cBe},{key:"Home",run:lGn,shift:xGn,preventDefault:!0},{key:"Mod-Home",run:uBe,shift:fBe},{key:"End",run:oGn,shift:bGn,preventDefault:!0},{key:"Mod-End",run:dBe,shift:hBe},{key:"Enter",run:pBe,shift:pBe},{key:"Mod-a",run:CGn},{key:"Backspace",run:Lye,shift:Lye,preventDefault:!0},{key:"Delete",run:h_t,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:m_t,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:IGn,preventDefault:!0},{mac:"Mod-Backspace",run:RGn,preventDefault:!0},{mac:"Mod-Delete",run:PGn,preventDefault:!0}].concat(WGn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),GGn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:aGn,shift:vGn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:iGn,shift:yGn},{key:"Alt-ArrowUp",run:DGn},{key:"Shift-Alt-ArrowUp",run:FGn},{key:"Alt-ArrowDown",run:LGn},{key:"Shift-Alt-ArrowDown",run:zGn},{key:"Mod-Alt-ArrowUp",run:TGn},{key:"Mod-Alt-ArrowDown",run:jGn},{key:"Escape",run:NGn},{key:"Mod-Enter",run:qGn},{key:"Alt-l",mac:"Ctrl-l",run:_Gn},{key:"Mod-i",run:EGn,preventDefault:!0},{key:"Mod-[",run:x_t},{key:"Mod-]",run:b_t},{key:"Mod-Alt-\\",run:VGn},{key:"Shift-Mod-k",run:BGn},{key:"Shift-Mod-\\",run:pGn},{key:"Mod-/",run:DZn},{key:"Alt-A",run:FZn},{key:"Ctrl-m",mac:"Shift-Alt-m",run:HGn}].concat(ZGn),QGn={key:"Tab",run:b_t,shift:x_t},mBe=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class Zx{constructor(t,n,r=0,s=t.length,a,i){this.test=i,this.value={from:0,to:0,precise:!1},this.done=!1,this.matches=[],this.buffer="",this.bufferPos=0,this.iter=t.iterRange(r,s),this.bufferStart=r,this.normalize=a?l=>a(mBe(l)):mBe,this.query=this.normalize(n)}peek(){if(this.bufferPos==this.buffer.length){if(this.bufferStart+=this.buffer.length,this.iter.next(),this.iter.done)return-1;this.bufferPos=0,this.buffer=this.iter.value}return wf(this.buffer,this.bufferPos)}next(){for(;this.matches.length;)this.matches.pop();return this.nextOverlapping()}nextOverlapping(){for(;;){let t=this.peek();if(t<0)return this.done=!0,this;let n=HOe(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Xv(t);let s=this.normalize(n);if(s.length)for(let a=0,i=r,l=!0;;a++){let c=s.charCodeAt(a),u=this.match(c,i,l,this.bufferPos+this.bufferStart,a==s.length-1);if(u)return this.value=u,this;if(a==s.length-1)break;l&&a<n.length&&n.charCodeAt(a)==c?i++:l=!1}}}match(t,n,r,s,a){let i=null;for(let l=0;l<this.matches.length;){let c=this.matches[l],u=!1;this.query.charCodeAt(c.index)==t&&(c.index==this.query.length-1?i={from:c.from,to:s,precise:a&&c.precise}:(c.index++,u=!0)),u?l++:this.matches.splice(l,1)}return this.query.charCodeAt(0)==t&&(this.query.length==1?i={from:n,to:s,precise:r&&a}:this.matches.push({from:n,index:1,precise:r})),i&&this.test&&!this.test(i.from,i.to,this.buffer,this.bufferStart)&&(i=null),i}}typeof Symbol<"u"&&(Zx.prototype[Symbol.iterator]=function(){return this});const w_t={from:-1,to:-1,match:/.*/.exec(""),precise:!0},VCe="gm"+(/x/.unicode==null?"":"u");class S_t{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=w_t,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new k_t(t,n,r,s,a);this.re=new RegExp(n,VCe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=FU(t,s),this.getLine(this.curLineStart)}getLine(t){this.iter.next(t),this.iter.lineBreak?this.curLine="":(this.curLine=this.iter.value,this.curLineStart+this.curLine.length>this.to&&(this.curLine=this.curLine.slice(0,this.to-this.curLineStart)),this.iter.next())}nextLine(){this.curLineStart=this.curLineStart+this.curLine.length+1,this.curLineStart>this.to?this.curLine="":this.getLine(0)}next(){for(let t=this.matchPos-this.curLineStart;;){this.re.lastIndex=t;let n=this.matchPos<=this.to&&this.re.exec(this.curLine);if(n){let r=this.curLineStart+n.index,s=r+n[0].length;if(this.matchPos=FU(this.text,s+(r==s?1:0)),r==this.curLineStart+this.curLine.length&&this.nextLine(),(r<s||r>this.value.to)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,precise:!0,match:n},this;t=this.matchPos-this.curLineStart}else if(this.curLineStart+this.curLine.length<this.to)this.nextLine(),t=0;else return this.done=!0,this}}}const mne=new WeakMap;class Ij{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=mne.get(t);if(!s||s.from>=r||s.to<=n){let l=new Ij(n,t.sliceString(n,r));return mne.set(t,l),l}if(s.from==n&&s.to==r)return s;let{text:a,from:i}=s;return i>n&&(a=t.sliceString(n,i)+a,i=n),s.to<r&&(a+=t.sliceString(s.to,r)),mne.set(t,new Ij(i,a)),new Ij(n,a.slice(n-i,r-i))}}class k_t{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=w_t,this.matchPos=FU(t,s),this.re=new RegExp(n,VCe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=Ij.get(t,s,this.chunkEnd(s+5e3))}chunkEnd(t){return t>=this.to?this.to:this.text.lineAt(t).to}next(){for(;;){let t=this.re.lastIndex=this.matchPos-this.flat.from,n=this.re.exec(this.flat.text);if(n&&!n[0]&&n.index==t&&(this.re.lastIndex=t+1,n=this.re.exec(this.flat.text)),n){let r=this.flat.from+n.index,s=r+n[0].length;if((this.flat.to>=this.to||n.index+n[0].length<=this.flat.text.length-10)&&(!this.test||this.test(r,s,n)))return this.value={from:r,to:s,precise:!0,match:n},this.matchPos=FU(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=Ij.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(S_t.prototype[Symbol.iterator]=k_t.prototype[Symbol.iterator]=function(){return this});function YGn(e){try{return new RegExp(e,VCe),!0}catch{return!1}}function FU(e,t){if(t>=e.length)return t;let n=e.lineAt(t),r;for(;t<n.to&&(r=n.text.charCodeAt(t-n.from))>=56320&&r<57344;)t++;return t}const KGn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=RUn(e,{label:t.phrase("Go to line"),input:{type:"text",name:"line",value:n},focus:!0,submitLabel:t.phrase("go")});return s.then(a=>{let i=a&&/^([+-])?(\d+)?(:\d+)?(%)?$/.exec(a.elements.line.value);if(!i){e.dispatch({effects:r});return}let l=t.doc.lineAt(t.selection.main.head),[,c,u,d,f]=i,h=d?+d.slice(1):0,p=u?+u:l.number;if(u&&f){let y=p/100;c&&(y=y*(c=="-"?-1:1)+l.number/t.doc.lines),p=Math.round(t.doc.lines*y)}else u&&c&&(p=p*(c=="-"?-1:1)+l.number);let m=t.doc.line(Math.max(1,Math.min(t.doc.lines,p))),v=St.cursor(m.from+Math.max(0,Math.min(h,m.length)));e.dispatch({effects:[r,Rt.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},XGn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},JGn=On.define({combine(e){return Jy(e,XGn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function eQn(e){return[aQn,sQn]}const tQn=jn.mark({class:"cm-selectionMatch"}),nQn=jn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function gBe(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=wo.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=wo.Word)}function rQn(e,t,n,r){return e(t.sliceDoc(n,n+1))==wo.Word&&e(t.sliceDoc(r-1,r))==wo.Word}const sQn=_o.fromClass(class{constructor(e){this.decorations=this.getDeco(e)}update(e){(e.selectionSet||e.docChanged||e.viewportChanged)&&(this.decorations=this.getDeco(e.view))}getDeco(e){let t=e.state.facet(JGn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return jn.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return jn.none;let c=n.wordAt(s.head);if(!c)return jn.none;i=n.charCategorizer(s.head),a=n.sliceDoc(c.from,c.to)}else{let c=s.to-s.from;if(c<t.minSelectionLength||c>200)return jn.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(gBe(i,n,s.from,s.to)&&rQn(i,n,s.from,s.to)))return jn.none}else if(a=n.sliceDoc(s.from,s.to),!a)return jn.none}let l=[];for(let c of e.visibleRanges){let u=new Zx(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||gBe(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(nQn.range(d,f)):(d>=s.to||f<=s.from)&&l.push(tQn.range(d,f)),l.length>t.maxMatches))return jn.none}}return jn.set(l)}},{decorations:e=>e.decorations}),aQn=Rt.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),iQn=({state:e,dispatch:t})=>{let{selection:n}=e,r=St.create(n.ranges.map(s=>e.wordAt(s.head)||St.cursor(s.head)),n.mainIndex);return r.eq(n)?!1:(t(e.update({selection:r})),!0)};function oQn(e,t){let{main:n,ranges:r}=e.selection,s=e.wordAt(n.head),a=s&&s.from==n.from&&s.to==n.to;for(let i=!1,l=new Zx(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new Zx(e.doc,t,0,Math.max(0,r[r.length-1].from-1)),i=!0}else{if(i&&r.some(c=>c.from==l.value.from))continue;if(a){let c=e.wordAt(l.value.from);if(!c||c.from!=l.value.from||c.to!=l.value.to)continue}return l.value}}const lQn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return iQn({state:e,dispatch:t});let r=e.sliceDoc(n[0].from,n[0].to);if(e.selection.ranges.some(a=>e.sliceDoc(a.from,a.to)!=r))return!1;let s=oQn(e,r);return s?(t(e.update({selection:e.selection.addRange(St.range(s.from,s.to),!1),effects:Rt.scrollIntoView(s.to)})),!0):!1},KI=On.define({combine(e){return Jy(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new SQn(t),scrollToMatch:t=>Rt.scrollIntoView(t)})}});class O_t{constructor(t){this.search=t.search,this.caseSensitive=!!t.caseSensitive,this.literal=!!t.literal,this.regexp=!!t.regexp,this.replace=t.replace||"",this.valid=!!this.search&&(!this.regexp||YGn(this.search)),this.unquoted=this.unquote(this.search),this.wholeWord=!!t.wholeWord,this.test=t.test}unquote(t){return this.literal?t:t.replace(/\\([nrt\\])/g,(n,r)=>r=="n"?`
|
|
234
|
-
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new pQn(this):new dQn(this)}getCursor(t,n=0,r){let s=t.doc?t:ps.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?kT(this,s,n,r):ST(this,s,n,r)}}class C_t{constructor(t){this.spec=t}}function cQn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function ST(e,t,n,r){let s;return e.wholeWord&&(s=uQn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=cQn(e.test,t,s)),new Zx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function uQn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(zU(s,n-a))!=wo.Word||t(BU(s,n-a))!=wo.Word)&&(t(BU(s,r-a))!=wo.Word||t(zU(s,r-a))!=wo.Word))}class dQn extends C_t{constructor(t){super(t)}nextMatch(t,n,r){let s=ST(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=ST(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=ST(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=ST(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=ST(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function fQn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function kT(e,t,n,r){let s;return e.wholeWord&&(s=hQn(t.charCategorizer(t.selection.main.head))),e.test&&(s=fQn(e.test,t,s)),new S_t(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function zU(e,t){return e.slice(Nc(e,t,!1),t)}function BU(e,t){return e.slice(t,Nc(e,t))}function hQn(e){return(t,n,r)=>!r[0].length||(e(zU(r.input,r.index))!=wo.Word||e(BU(r.input,r.index))!=wo.Word)&&(e(BU(r.input,r.index+r[0].length))!=wo.Word||e(zU(r.input,r.index+r[0].length))!=wo.Word)}class pQn extends C_t{nextMatch(t,n,r){let s=kT(this.spec,t,r,t.doc.length).next();return s.done&&(s=kT(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=kT(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=kT(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=kT(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const dD=pr.define(),HCe=pr.define(),hS=wl.define({create(e){return new gne(Fye(e).create(),null)},update(e,t){for(let n of t.effects)n.is(dD)?e=new gne(n.value.create(),e.panel):n.is(HCe)&&(e=new gne(e.query,n.value?WCe:null));return e},provide:e=>tD.from(e,t=>t.panel)});class gne{constructor(t,n){this.query=t,this.panel=n}}const mQn=jn.mark({class:"cm-searchMatch"}),gQn=jn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),vQn=_o.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(hS))}update(e){let t=e.state.field(hS);(t!=e.startState.field(hS)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return jn.none;let{view:n}=this,r=new nd;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(h=>h.from==u&&h.to==d);r.add(u,d,f?gQn:mQn)})}return r.finish()}},{decorations:e=>e.decorations});function RL(e){return t=>{let n=t.state.field(hS,!1);return n&&n.query.spec.valid?e(t,n):T_t(t)}}const UU=RL((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=St.single(r.from,r.to),a=e.state.facet(KI);return e.dispatch({selection:s,effects:[ZCe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),E_t(e),!0}),qU=RL((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=St.single(s.from,s.to),i=e.state.facet(KI);return e.dispatch({selection:a,effects:[ZCe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),E_t(e),!0}),yQn=RL((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:St.create(n.map(r=>St.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),bQn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new Zx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(St.range(l.value.from,l.value.to))}return t(e.update({selection:St.create(a,i),userEvent:"select.search.matches"})),!0},vBe=RL((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(Rt.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=St.single(i.from,i.to).map(f),d.push(ZCe(e,i)),d.push(n.facet(KI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),xQn=RL((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Rt.announce.of(r),userEvent:"input.replace.all"}),!0});function WCe(e){return e.state.facet(KI).createPanel(e)}function Fye(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(KI);return new O_t({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function __t(e){let t=lCe(e,WCe);return t&&t.dom.querySelector("[main-field]")}function E_t(e){let t=__t(e);t&&t==e.root.activeElement&&t.select()}const T_t=e=>{let t=e.state.field(hS,!1);if(t&&t.panel){let n=__t(e);if(n&&n!=e.root.activeElement){let r=Fye(e.state,t.query.spec);r.valid&&e.dispatch({effects:dD.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[HCe.of(!0),t?dD.of(Fye(e.state,t.query.spec)):pr.appendConfig.of(OQn)]});return!0},j_t=e=>{let t=e.state.field(hS,!1);if(!t||!t.panel)return!1;let n=lCe(e,WCe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:HCe.of(!1)}),!0},wQn=[{key:"Mod-f",run:T_t,scope:"editor search-panel"},{key:"F3",run:UU,shift:qU,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:UU,shift:qU,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:j_t,scope:"editor search-panel"},{key:"Mod-Shift-l",run:bQn},{key:"Mod-Alt-g",run:KGn},{key:"Mod-d",run:lQn,preventDefault:!0}];class SQn{constructor(t){this.view=t;let n=this.query=t.state.field(hS).query.spec;this.commit=this.commit.bind(this),this.searchField=pi("input",{value:n.search,placeholder:vh(t,"Find"),"aria-label":vh(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=pi("input",{value:n.replace,placeholder:vh(t,"Replace"),"aria-label":vh(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=pi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=pi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=pi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return pi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=pi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>UU(t),[vh(t,"next")]),r("prev",()=>qU(t),[vh(t,"previous")]),r("select",()=>yQn(t),[vh(t,"all")]),pi("label",null,[this.caseField,vh(t,"match case")]),pi("label",null,[this.reField,vh(t,"regexp")]),pi("label",null,[this.wordField,vh(t,"by word")]),...t.state.readOnly?[]:[pi("br"),this.replaceField,r("replace",()=>vBe(t),[vh(t,"replace")]),r("replaceAll",()=>xQn(t),[vh(t,"replace all")])],pi("button",{name:"close",onclick:()=>j_t(t),"aria-label":vh(t,"close"),type:"button"},["×"])])}commit(){let t=new O_t({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:dD.of(t)}))}keydown(t){qBn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?qU:UU)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),vBe(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(dD)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(KI).top}}function vh(e,t){return e.state.phrase(t)}const ez=30,tz=/[\s\.,:;?!]/;function ZCe(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-ez),i=Math.min(s,n+ez),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<ez;c++)if(!tz.test(l[c+1])&&tz.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-ez;c--)if(!tz.test(l[c-1])&&tz.test(l[c])){l=l.slice(0,c);break}}return Rt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const kQn=Rt.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),OQn=[hS,lp.low(vQn),kQn];class yBe{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Kk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(fD).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new nd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let h,p;for(l.length?(h=c,p=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>h?f.from:1e8)):(h=f.from,p=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==h&&(v.to>v.from||v.to==h))l.push(v),d++,p=Math.min(v.to,p);else{p=Math.min(v.from,p);break}}let m=DQn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(h,h,jn.widget({widget:new RQn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(h,p,jn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>p)}))}c=p;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new Kk(u,n,kN(u))}}function kN(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new yBe(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new yBe(r.from,a,r.diagnostic)}}),r}function CQn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(fD).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(N_t))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function _Qn(e,t){return e.field(Fh,!1)?t:t.concat(pr.appendConfig.of(LQn))}const N_t=pr.define(),GCe=pr.define(),I_t=pr.define(),Fh=wl.define({create(){return new Kk(jn.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=kN(n,e.selected.diagnostic,a)||kN(n,null,a)}!n.size&&s&&t.state.facet(fD).autoPanel&&(s=null),e=new Kk(n,s,r)}for(let n of t.effects)if(n.is(N_t)){let r=t.state.facet(fD).autoPanel?n.value.length?hD.open:null:e.panel;e=Kk.init(n.value,r,t.state)}else n.is(GCe)?e=new Kk(e.diagnostics,n.value?hD.open:null,e.selected):n.is(I_t)&&(e=new Kk(e.diagnostics,e.panel,n.value));return e},provide:e=>[tD.from(e,t=>t.panel),Rt.decorations.from(e,t=>t.diagnostics)]}),EQn=jn.mark({class:"cm-lintRange cm-lintRange-active"});function TQn(e,t,n){let{diagnostics:r}=e.state.field(Fh),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(fD).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:jQn(e,s)}}}:null}function jQn(e,t){return pi("ul",{class:"cm-tooltip-lint"},t.map(n=>R_t(e,n,!1)))}const NQn=e=>{let t=e.state.field(Fh,!1);(!t||!t.panel)&&e.dispatch({effects:_Qn(e.state,[GCe.of(!0)])});let n=lCe(e,hD.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},bBe=e=>{let t=e.state.field(Fh,!1);return!t||!t.panel?!1:(e.dispatch({effects:GCe.of(!1)}),!0)},IQn=e=>{let t=e.state.field(Fh,!1);if(!t)return!1;let n=e.state.selection.main,r=t.diagnostics.iter(n.to+1);return!r.value&&(r=t.diagnostics.iter(0),!r.value||r.from==n.from&&r.to==n.to)?!1:(e.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},AQn=[{key:"Mod-Shift-m",run:NQn,preventDefault:!0},{key:"F8",run:IQn}],fD=On.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Jy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:xBe,tooltipFilter:xBe,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function xBe(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function A_t(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function R_t(e,t,n){var r;let s=n?A_t(t.actions):[];return pi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},pi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=p=>{if(p.preventDefault(),l)return;l=!0;let m=kN(e.state.field(Fh).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),pi("u",u.slice(d,d+1)),u.slice(d+1)],h=a.markClass?" "+a.markClass:"";return pi("button",{type:"button",class:"cm-diagnosticAction"+h,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&pi("div",{class:"cm-diagnosticSource"},t.source))}class RQn extends cp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return pi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class wBe{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=R_t(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class hD{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)bBe(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=A_t(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=kN(this.view.state.field(Fh).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=pi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=pi("div",{class:"cm-panel-lint"},this.list,pi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>bBe(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Fh).selected;if(!t)return-1;for(let n=0;n<this.items.length;n++)if(this.items[n].diagnostic==t.diagnostic)return n;return-1}update(){let{diagnostics:t,selected:n}=this.view.state.field(Fh),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,h;for(let p=r;p<this.items.length;p++)if(this.items[p].diagnostic==d){f=p;break}f<0?(h=new wBe(this.view,d),this.items.splice(r,0,h),s=!0):(h=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&h.diagnostic==n.diagnostic?h.dom.hasAttribute("aria-selected")||(h.dom.setAttribute("aria-selected","true"),a=h):h.dom.hasAttribute("aria-selected")&&h.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new wBe(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Fh),r=kN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:I_t.of(r)})}static open(t){return new hD(t)}}function PQn(e,t='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}function nz(e){return PQn(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const $Qn=Rt.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:nz("#d11")},".cm-lintRange-warning":{backgroundImage:nz("orange")},".cm-lintRange-info":{backgroundImage:nz("#999")},".cm-lintRange-hint":{backgroundImage:nz("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});function MQn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function DQn(e){let t="hint",n=1;for(let r of e){let s=MQn(r.severity);s>n&&(n=s,t=r.severity)}return t}const LQn=[Fh,Rt.decorations.compute([Fh],e=>{let{selected:t,panel:n}=e.field(Fh);return!t||!n||t.from==t.to?jn.none:jn.set([EQn.range(t.from,t.to)])}),IUn(TQn,{hideOn:CQn}),$Qn];var SBe=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(EVn)),t.defaultKeymap!==!1&&(a=a.concat(GGn)),t.searchKeymap!==!1&&(a=a.concat(wQn)),t.historyKeymap!==!1&&(a=a.concat(tGn)),t.foldKeymap!==!1&&(a=a.concat(fqn)),t.completionKeymap!==!1&&(a=a.concat(EOt)),t.lintKeymap!==!1&&(a=a.concat(AQn));var i=[];return t.lineNumbers!==!1&&i.push(Gkt()),t.highlightActiveLineGutter!==!1&&i.push(HUn()),t.highlightSpecialChars!==!1&&i.push(aUn()),t.history!==!1&&i.push(WZn()),t.foldGutter!==!1&&i.push(gqn()),t.drawSelection!==!1&&i.push(QBn()),t.dropCursor!==!1&&i.push(eUn()),t.allowMultipleSelections!==!1&&i.push(ps.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(sqn()),t.syntaxHighlighting!==!1&&i.push(T1(xqn,{fallback:!0})),t.bracketMatching!==!1&&i.push(Eqn()),t.closeBrackets!==!1&&i.push(kVn()),t.autocompletion!==!1&&i.push(_Ot()),t.rectangularSelection!==!1&&i.push(bUn()),s!==!1&&i.push(SUn()),t.highlightActiveLine!==!1&&i.push(dUn()),t.highlightSelectionMatches!==!1&&i.push(eQn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(ZI.of(" ".repeat(t.tabSize))),i.concat([WI.of(a.flat())]).filter(Boolean)};const FQn="#e5c07b",kBe="#e06c75",zQn="#56b6c2",BQn="#ffffff",D9="#abb2bf",zye="#7d8799",UQn="#61afef",qQn="#98c379",OBe="#d19a66",VQn="#c678dd",HQn="#21252b",CBe="#2c313a",_Be="#282c34",vne="#353a42",WQn="#3E4451",EBe="#528bff",ZQn=Rt.theme({"&":{color:D9,backgroundColor:_Be},".cm-content":{caretColor:EBe},".cm-cursor, .cm-dropCursor":{borderLeftColor:EBe},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:WQn},".cm-panels":{backgroundColor:HQn,color:D9},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:_Be,color:zye,border:"none"},".cm-activeLineGutter":{backgroundColor:CBe},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:vne},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:vne,borderBottomColor:vne},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:CBe,color:D9}}},{dark:!0}),GQn=rv.define([{tag:ue.keyword,color:VQn},{tag:[ue.name,ue.deleted,ue.character,ue.propertyName,ue.macroName],color:kBe},{tag:[ue.function(ue.variableName),ue.labelName],color:UQn},{tag:[ue.color,ue.constant(ue.name),ue.standard(ue.name)],color:OBe},{tag:[ue.definition(ue.name),ue.separator],color:D9},{tag:[ue.typeName,ue.className,ue.number,ue.changed,ue.annotation,ue.modifier,ue.self,ue.namespace],color:FQn},{tag:[ue.operator,ue.operatorKeyword,ue.url,ue.escape,ue.regexp,ue.link,ue.special(ue.string)],color:zQn},{tag:[ue.meta,ue.comment],color:zye},{tag:ue.strong,fontWeight:"bold"},{tag:ue.emphasis,fontStyle:"italic"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:ue.link,color:zye,textDecoration:"underline"},{tag:ue.heading,fontWeight:"bold",color:kBe},{tag:[ue.atom,ue.bool,ue.special(ue.variableName)],color:OBe},{tag:[ue.processingInstruction,ue.string,ue.inserted],color:qQn},{tag:ue.invalid,color:BQn}]),QQn=[ZQn,T1(GQn)];var YQn=Rt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),KQn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,h=f===void 0?"":f,p=n.basicSetup,m=p===void 0?!0:p,v=[];switch(s&&v.unshift(WI.of([QGn])),m&&(typeof m=="boolean"?v.unshift(SBe()):v.unshift(SBe(m))),h&&v.unshift(mUn(h)),d){case"light":v.push(YQn);break;case"dark":v.push(QQn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Rt.editable.of(!1)),c&&v.push(ps.readOnly.of(!0)),[...v]},XQn=e=>({line:e.state.doc.lineAt(e.state.selection.main.from),lineCount:e.state.doc.lines,lineBreak:e.state.lineBreak,length:e.state.doc.length,readOnly:e.state.readOnly,tabSize:e.state.tabSize,selection:e.state.selection,selectionAsSingle:e.state.selection.asSingle().main,ranges:e.state.selection.ranges,selectionCode:e.state.sliceDoc(e.state.selection.main.from,e.state.selection.main.to),selections:e.state.selection.ranges.map(t=>e.state.sliceDoc(t.from,t.to)),selectedText:e.state.selection.ranges.some(t=>!t.empty)});class JQn{constructor(t,n){this.timeLeftMS=void 0,this.timeoutMS=void 0,this.isCancelled=!1,this.isTimeExhausted=!1,this.callbacks=[],this.timeLeftMS=n,this.timeoutMS=n,this.callbacks.push(t)}tick(){if(!this.isCancelled&&!this.isTimeExhausted&&(this.timeLeftMS--,this.timeLeftMS<=0)){this.isTimeExhausted=!0;var t=this.callbacks.slice();this.callbacks.length=0,t.forEach(n=>{try{n()}catch(r){console.error("TimeoutLatch callback error:",r)}})}}cancel(){this.isCancelled=!0,this.callbacks.length=0}reset(){this.timeLeftMS=this.timeoutMS,this.isCancelled=!1,this.isTimeExhausted=!1}get isDone(){return this.isCancelled||this.isTimeExhausted}}class TBe{constructor(){this.interval=null,this.latches=new Set}add(t){this.latches.add(t),this.start()}remove(t){this.latches.delete(t),this.latches.size===0&&this.stop()}start(){this.interval===null&&(this.interval=setInterval(()=>{this.latches.forEach(t=>{t.tick(),t.isDone&&this.remove(t)})},1))}stop(){this.interval!==null&&(clearInterval(this.interval),this.interval=null)}}var yne=null,eYn=()=>typeof window>"u"?new TBe:(yne||(yne=new TBe),yne),tYn=Rt.theme({"& .cm-scroller":{height:"100% !important"}}),jBe=null,bne=null;function nYn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===jBe||(jBe=i,bne=Rt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),bne}var NBe=Xy.define(),rYn=200,sYn=[];function aYn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?sYn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,h=e.height,p=h===void 0?null:h,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,w=x===void 0?null:x,k=e.minWidth,O=k===void 0?null:k,_=e.maxWidth,T=_===void 0?null:_,E=e.placeholder,N=E===void 0?"":E,I=e.editable,A=I===void 0?!0:I,$=e.readOnly,z=$===void 0?!1:$,D=e.indentWithTab,q=D===void 0?!0:D,H=e.basicSetup,V=H===void 0?!0:H,B=e.root,W=e.initialState,L=g.useState(),G=L[0],M=L[1],R=g.useState(),F=R[0],U=R[1],Q=g.useState(),te=Q[0],J=Q[1],ee=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],ae=nYn(p,v,b,w,O,T),X=Rt.updateListener.of(ce=>{if(ce.docChanged&&typeof r=="function"&&!ce.transactions.some(ye=>ye.annotation(NBe))){ee.current?ee.current.reset():(ee.current=new JQn(()=>{if(re.current){var ye=re.current;re.current=null,ye()}ee.current=null},rYn),eYn().add(ee.current));var le=ce.state.doc,ve=le.toString();r(ve,ce)}s&&s(XQn(ce))}),ne=KQn({theme:f,editable:A,readOnly:z,placeholder:N,indentWithTab:q,basicSetup:V}),se=[X,...ae?[ae]:[],tYn,...ne];return i&&typeof i=="function"&&se.push(Rt.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!te){var ce={doc:t,selection:n,extensions:se},le=W?ps.fromJSON(W.json,ce,W.fields):ps.create(ce);if(J(le),!F){var ve=new Rt({state:le,parent:G,root:B});U(ve),a&&a(ve,le)}}return()=>{F&&(J(void 0),U(void 0))}},[G,te]),g.useEffect(()=>{e.container&&M(e.container)},[e.container]),g.useEffect(()=>()=>{F&&(F.destroy(),U(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[F]),g.useEffect(()=>{u&&F&&F.focus()},[u,F]),g.useEffect(()=>{F&&F.dispatch({effects:pr.reconfigure.of(se)})},[f,c,p,v,b,w,O,T,N,A,z,q,V,r,i]),g.useEffect(()=>{if(t!==void 0){var ce=F?F.state.doc.toString():"";if(F&&t!==ce){var le=ee.current&&!ee.current.isDone,ve=()=>{F&&t!==F.state.doc.toString()&&F.dispatch({changes:{from:0,to:F.state.doc.toString().length,insert:t||""},annotations:[NBe.of(!0)]})};le?re.current=ve:ve()}}},[t,F]),{state:te,setState:J,view:F,setView:U,container:G,setContainer:M}}var iYn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],rd=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,h=e.autoFocus,p=e.theme,m=p===void 0?"light":p,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,w=e.minWidth,k=e.maxWidth,O=e.basicSetup,_=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,$=BCt(e,iYn),z=g.useRef(null),D=aYn({root:I,value:s,autoFocus:h,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:O,placeholder:_,indentWithTab:T,editable:E,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),q=D.state,H=D.view,V=D.container,B=D.setContainer;g.useImperativeHandle(t,()=>({editor:z.current,state:q,view:H}),[z,V,q,H]);var W=g.useCallback(G=>{z.current=G,B(G)},[B]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var L=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",xC({ref:W,className:""+L+(n?" "+n:"")},$))});rd.displayName="CodeMirror";function oYn(e){return new gC(hCe.define(e))}const P_t=[vg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Va(()=>Promise.resolve().then(()=>XF),[],import.meta.url).then(e=>e.javascript())}}),vg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Va(()=>Promise.resolve().then(()=>Fqn),void 0,import.meta.url).then(e=>e.json())}}),vg.of({name:"JSX",extensions:["jsx"],load(){return Va(()=>Promise.resolve().then(()=>XF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),vg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Va(()=>Promise.resolve().then(()=>RZn),void 0,import.meta.url).then(e=>e.markdown())}}),vg.of({name:"TSX",extensions:["tsx"],load(){return Va(()=>Promise.resolve().then(()=>XF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),vg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Va(()=>Promise.resolve().then(()=>XF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),vg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Va(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>oYn(e.shell))}})];function lYn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function cYn(e){const t=lYn(e);return _Ot({override:[uYn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function uYn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,h)=>{const v=u.state.sliceDoc(h,h+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:h,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const dYn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,fYn=jn.mark({class:"cm-variable-highlight"}),IBe=new Fkt({regexp:dYn,decoration:()=>fYn}),hYn=_o.fromClass(class{decorations;constructor(e){this.decorations=IBe.createDeco(e)}update(e){this.decorations=IBe.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),pYn=hYn;function mYn(){const e=QI({settings:{fontFamily:"var(--font-mono)",fontSize:"var(--text-ui-smd)",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[ue.className,ue.propertyName],color:"var(--neutral6)"},{tag:ue.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.heading1,ue.heading2,ue.heading3,ue.heading4,ue.heading5,ue.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:ue.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:ue.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:ue.link,color:"var(--accent3)",textDecoration:"underline"},{tag:ue.url,color:"var(--accent3)"},{tag:ue.monospace,color:"var(--neutral6)"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:ue.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Rt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"var(--text-ui-sm)",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function gYn(){const e=Rt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"var(--text-ui-smd)"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"var(--text-ui-sm)",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=rv.define([{tag:[ue.comment,ue.bracket],color:"var(--neutral2)"},{tag:[ue.string,ue.meta,ue.regexp],color:"var(--accent1)"},{tag:[ue.atom,ue.bool,ue.special(ue.variableName)],color:"var(--accent6)"},{tag:[ue.keyword,ue.operator,ue.tagName],color:"var(--accent2)"},{tag:[ue.function(ue.propertyName),ue.propertyName],color:"var(--accent5)"},{tag:[ue.definition(ue.variableName),ue.function(ue.variableName),ue.className,ue.attributeName],color:"var(--accent3)"},{tag:[ue.variableName,ue.number],color:"var(--accent5)"},{tag:[ue.name,ue.quote],color:"var(--accent1)"},{tag:ue.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.heading1,ue.heading2,ue.heading3,ue.heading4,ue.heading5,ue.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[ue.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:ue.link,color:"var(--accent3)",textDecoration:"underline"},{tag:ue.url,color:"var(--accent3)"},{tag:ue.monospace,color:"var(--neutral6)"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:[ue.deleted],color:"var(--accent2)"},{tag:ue.invalid,color:"var(--error)"},{tag:[ue.standard(ue.tagName)],color:"var(--accent1)"}]);return[e,T1(t)]}const b0=()=>{const e=b_().resolvedTheme==="dark";return g.useMemo(()=>e?mYn():gYn(),[e])},vYn=xl(K("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),yYn=lp.highest(Rt.editorAttributes.of({style:"outline: none"})),bYn=lp.highest(Rt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),xYn=[yYn,bYn],Vr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:h,variant:p,...m},v)=>{const y=b0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const w=[...xYn];return f&&w.push(Rt.lineWrapping),a==="json"?w.push(Wh):a==="markdown"&&w.push(zCe({base:bC,codeLanguages:P_t})),i&&a==="markdown"&&w.push(pYn),c&&a==="markdown"&&w.push(cYn(c)),h===!1&&w.push(ps.readOnly.of(!0)),w},[a,i,c,h,f]);return o.jsxs("div",{className:K(vYn({variant:p}),s),...m,children:[r&&o.jsx(Pa,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(rd,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:h,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),$_t={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",diff:"diff",patch:"diff",css:"css",scss:"css",html:"html",htm:"html",xml:"xml",svg:"xml",sql:"sql"};let xne=null;function wYn(){return xne||(xne=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Va(()=>import("./core-C6NBy4h2.js"),__vite__mapDeps([0,1,2]),import.meta.url),Va(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Va(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Va(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Va(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Va(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Va(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Va(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Va(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Va(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Va(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Va(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Va(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Va(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Va(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Va(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Va(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Va(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),xne}async function SYn(e,t){const n=$_t[t?.toLowerCase()];if(!n)return null;const r=await wYn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function kYn(e){const t=e?.split(".").pop()?.toLowerCase();return t?$_t[t]:void 0}const OYn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},CYn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=b0(),{settings:r,setSettings:s}=PW(),a=r?.tracingOptions,i=g.useMemo(()=>OYn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=h=>{u.current=!0,c(h)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const h=JSON.parse(l);typeof h=="object"&&h!==null&&s({...r,tracingOptions:h})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ge,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(rd,{value:l,onChange:d,theme:n,extensions:[Wh],className:K("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(ie,{icon:o.jsx(Fn,{}),type:"button",onClick:f,children:"Save"})})]})},_Yn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(st,{children:o.jsx(Jwe,{})})})}),o.jsx(pn,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Run Options"}),o.jsx(Ms,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Mr,{children:o.jsx(CYn,{onSaved:()=>t(!1)})})]})})]})};function EYn({status:e}){switch(e){case"running":return o.jsx(Zt,{});case"failed":return o.jsx(qt,{className:"text-accent2"});case"canceled":return o.jsx(Os,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(xS,{className:"text-neutral3"});case"suspended":return o.jsx(yH,{className:"text-accent3"});case"success":return o.jsx(Fn,{className:"text-accent1"});default:return o.jsx(xS,{className:"text-neutral3"})}}function M_t({status:e}){return o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx(st,{"aria-label":e,className:"shrink-0",children:o.jsx(EYn,{status:e})})}),o.jsx(pn,{children:e})]})}var wne,ABe;function QCe(){if(ABe)return wne;ABe=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var h=arguments,p=this;return d.forEach(function(m){h.length>1?p.setNode(m,f):p.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var h=p=>f.removeEdge(f._edgeObjs[p]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(p){f.setParent(p)}),delete this._children[d]),Object.keys(this._in[d]).forEach(h),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(h),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var h=f;h!==void 0;h=this.parent(h))if(h===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const p=new Set(f);for(var h of this.successors(d))p.add(h);return Array.from(p.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var h=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,h.edge(v))});var p={};function m(v){var y=h.parent(v);return y===void 0||f.hasNode(y)?(p[v]=y,y):y in p?p[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var h=this,p=arguments;return d.reduce(function(m,v){return p.length>1?h.setEdge(m,v,f):h.setEdge(m,v),v}),this}setEdge(){var d,f,h,p,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,h=v.name,arguments.length===2&&(p=arguments[1],m=!0)):(d=v,f=arguments[1],h=arguments[3],arguments.length>2&&(p=arguments[2],m=!0)),d=""+d,f=""+f,h!==void 0&&(h=""+h);var y=i(this._isDirected,d,f,h);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=p),this;if(h!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?p:this._defaultEdgeLabelFn(d,f,h);var b=l(this._isDirected,d,f,h);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h);return this._edgeLabels[p]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h);return Object.hasOwn(this._edgeLabels,p)}removeEdge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h),m=this._edgeObjs[p];return m&&(d=m.v,f=m.w,delete this._edgeLabels[p],delete this._edgeObjs[p],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][p],delete this._out[d][p],this._edgeCount--),this}inEdges(d,f){var h=this._in[d];if(h){var p=Object.values(h);return f?p.filter(m=>m.v===f):p}}outEdges(d,f){var h=this._out[d];if(h){var p=Object.values(h);return f?p.filter(m=>m.w===f):p}}nodeEdges(d,f){var h=this.inEdges(d,f);if(h)return h.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,h){var p=""+d,m=""+f;if(!u&&p>m){var v=p;p=m,m=v}return p+n+m+n+(h===void 0?e:h)}function l(u,d,f,h){var p=""+d,m=""+f;if(!u&&p>m){var v=p;p=m,m=v}var y={v:p,w:m};return h&&(y.name=h),y}function c(u,d){return i(u,d.v,d.w,d.name)}return wne=r,wne}var Sne,RBe;function TYn(){return RBe||(RBe=1,Sne="2.2.4"),Sne}var kne,PBe;function jYn(){return PBe||(PBe=1,kne={Graph:QCe(),version:TYn()}),kne}var One,$Be;function NYn(){if($Be)return One;$Be=1;var e=QCe();One={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return One}var Cne,MBe;function IYn(){if(MBe)return Cne;MBe=1,Cne=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return Cne}var _ne,DBe;function D_t(){if(DBe)return _ne;DBe=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return _ne=e,_ne}var Ene,LBe;function L_t(){if(LBe)return Ene;LBe=1;var e=D_t();Ene=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,h=function(p){var m=p.v!==d?p.v:p.w,v=c[m],y=i(p),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+p+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(p){var m=p===a?0:Number.POSITIVE_INFINITY;c[p]={distance:m},u.add(p,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(h);return c}return Ene}var Tne,FBe;function AYn(){if(FBe)return Tne;FBe=1;var e=L_t();Tne=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Tne}var jne,zBe;function F_t(){if(zBe)return jne;zBe=1,jne=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return jne}var Nne,BBe;function RYn(){if(BBe)return Nne;BBe=1;var e=F_t();Nne=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Nne}var Ine,UBe;function PYn(){if(UBe)return Ine;UBe=1,Ine=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(h){var p=f[c],m=u[h],v=f[h],y=p.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return Ine}var Ane,qBe;function z_t(){if(qBe)return Ane;qBe=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return Ane=e,e.CycleException=t,Ane}var Rne,VBe;function $Yn(){if(VBe)return Rne;VBe=1;var e=z_t();Rne=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return Rne}var Pne,HBe;function B_t(){if(HBe)return Pne;HBe=1,Pne=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return Pne}var $ne,WBe;function MYn(){if(WBe)return $ne;WBe=1;var e=B_t();$ne=t;function t(n,r){return e(n,r,"post")}return $ne}var Mne,ZBe;function DYn(){if(ZBe)return Mne;ZBe=1;var e=B_t();Mne=t;function t(n,r){return e(n,r,"pre")}return Mne}var Dne,GBe;function LYn(){if(GBe)return Dne;GBe=1;var e=QCe(),t=D_t();Dne=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var h=f.v===c?f.w:f.v,p=l.priority(h);if(p!==void 0){var m=s(f);m<p&&(i[h]=c,l.decrease(h,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return Dne}var Lne,QBe;function FYn(){return QBe||(QBe=1,Lne={components:IYn(),dijkstra:L_t(),dijkstraAll:AYn(),findCycles:RYn(),floydWarshall:PYn(),isAcyclic:$Yn(),postorder:MYn(),preorder:DYn(),prim:LYn(),tarjan:F_t(),topsort:z_t()}),Lne}var Fne,YBe;function Gg(){if(YBe)return Fne;YBe=1;var e=jYn();return Fne={Graph:e.Graph,json:NYn(),alg:FYn(),version:e.version},Fne}var zne,KBe;function zYn(){if(KBe)return zne;KBe=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return zne=e,zne}var Bne,XBe;function BYn(){if(XBe)return Bne;XBe=1;let e=Gg().Graph,t=zYn();Bne=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(p=>u.outEdges(p.v,p.w))}function s(u,d,f){let h=[],p=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=p.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){h=h.concat(a(u,d,f,v,!0));break}}}return h}function a(u,d,f,h,p){let m=p?[]:void 0;return u.inEdges(h.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);p&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(h.v).forEach(v=>{let y=u.edge(v),b=v.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(h.v),m}function i(u,d){let f=new e,h=0,p=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,x=d(y),w=b+x;f.setEdge(y.v,y.w,w),p=Math.max(p,f.node(y.v).out+=x),h=Math.max(h,f.node(y.w).in+=x)});let m=c(p+h+3).map(()=>new t),v=h+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return Bne}var Une,JBe;function Dl(){if(JBe)return Une;JBe=1;let e=Gg().Graph;Une={addBorderNode:d,addDummyNode:t,applyWithChunking:p,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:_,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:O,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:w,zipObject:T};function t(E,N,I,A){for(var $=A;E.hasNode($);)$=w(A);return I.dummy=N,E.setNode($,I),$}function n(E){let N=new e().setGraph(E.graph());return E.nodes().forEach(I=>N.setNode(I,E.node(I))),E.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},$=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+$.weight,minlen:Math.max(A.minlen,$.minlen)})}),N}function r(E){let N=new e({multigraph:E.isMultigraph()}).setGraph(E.graph());return E.nodes().forEach(I=>{E.children(I).length||N.setNode(I,E.node(I))}),E.edges().forEach(I=>{N.setEdge(I,E.edge(I))}),N}function s(E){let N=E.nodes().map(I=>{let A={};return E.outEdges(I).forEach($=>{A[$.w]=(A[$.w]||0)+E.edge($).weight}),A});return T(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach($=>{A[$.v]=(A[$.v]||0)+E.edge($).weight}),A});return T(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,$=N.x-I,z=N.y-A,D=E.width/2,q=E.height/2;if(!$&&!z)throw new Error("Not possible to find intersection inside of the rectangle");let H,V;return Math.abs(z)*D>Math.abs($)*q?(z<0&&(q=-q),H=q*$/z,V=q):($<0&&(D=-D),H=D,V=D*z/$),{x:I+H,y:A+V}}function l(E){let N=k(m(E)+1).map(()=>[]);return E.nodes().forEach(I=>{let A=E.node(I),$=A.rank;$!==void 0&&(N[$][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let $=E.node(A).rank;return $===void 0?Number.MAX_VALUE:$}),I=p(Math.min,N);E.nodes().forEach(A=>{let $=E.node(A);Object.hasOwn($,"rank")&&($.rank-=I)})}function u(E){let N=E.nodes().map(D=>E.node(D).rank),I=p(Math.min,N),A=[];E.nodes().forEach(D=>{let q=E.node(D).rank-I;A[q]||(A[q]=[]),A[q].push(D)});let $=0,z=E.graph().nodeRankFactor;Array.from(A).forEach((D,q)=>{D===void 0&&q%z!==0?--$:D!==void 0&&$&&D.forEach(H=>E.node(H).rank+=$)})}function d(E,N,I,A){let $={width:0,height:0};return arguments.length>=4&&($.rank=I,$.order=A),t(E,"border",$,N)}function f(E,N=h){const I=[];for(let A=0;A<E.length;A+=N){const $=E.slice(A,A+N);I.push($)}return I}const h=65535;function p(E,N){if(N.length>h){const I=f(N);return E.apply(null,I.map(A=>E.apply(null,A)))}else return E.apply(null,N)}function m(E){const I=E.nodes().map(A=>{let $=E.node(A).rank;return $===void 0?Number.MIN_VALUE:$});return p(Math.max,I)}function v(E,N){let I={lhs:[],rhs:[]};return E.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(E,N){let I=Date.now();try{return N()}finally{console.log(E+" time: "+(Date.now()-I)+"ms")}}function b(E,N){return N()}let x=0;function w(E){var N=++x;return E+(""+N)}function k(E,N,I=1){N==null&&(N=E,E=0);let A=z=>z<N;I<0&&(A=z=>N<z);const $=[];for(let z=E;A(z);z+=I)$.push(z);return $}function O(E,N){const I={};for(const A of N)E[A]!==void 0&&(I[A]=E[A]);return I}function _(E,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(E).reduce((A,[$,z])=>(A[$]=I(z,$),A),{})}function T(E,N){return E.reduce((I,A,$)=>(I[A]=N[$],I),{})}return Une}var qne,eUe;function UYn(){if(eUe)return qne;eUe=1;let e=BYn(),t=Dl().uniqueId;qne={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return qne}var Vne,tUe;function qYn(){if(tUe)return Vne;tUe=1;let e=Dl();Vne={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),h=f.labelRank;if(u===l+1)return;s.removeEdge(a);let p,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},p=e.addDummyNode(s,"edge",m,"_d"),l===h&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,p,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(p),i=p;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return Vne}var Hne,nUe;function VU(){if(nUe)return Hne;nUe=1;const{applyWithChunking:e}=Dl();Hne={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return Hne}var Wne,rUe;function U_t(){if(rUe)return Wne;rUe=1;var e=Gg().Graph,t=VU().slack;Wne=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,h=u===f?d.w:f;!i.hasNode(h)&&!t(l,d)&&(i.setNode(h,{}),i.setEdge(u,h,{}),c(h))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return Wne}var Zne,sUe;function VYn(){if(sUe)return Zne;sUe=1;var e=U_t(),t=VU().slack,n=VU().longestPath,r=Gg().alg.preorder,s=Gg().alg.postorder,a=Dl().simplify;Zne=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=h,i.enterEdge=p,i.exchangeEdges=m;function i(x){x=a(x),n(x);var w=e(x);d(w),l(w,x);for(var k,O;k=h(w);)O=p(w,x,k),m(w,x,k,O)}function l(x,w){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(O=>c(x,w,O))}function c(x,w,k){var O=x.node(k),_=O.parent;x.edge(k,_).cutvalue=u(x,w,k)}function u(x,w,k){var O=x.node(k),_=O.parent,T=!0,E=w.edge(k,_),N=0;return E||(T=!1,E=w.edge(_,k)),N=E.weight,w.nodeEdges(k).forEach(I=>{var A=I.v===k,$=A?I.w:I.v;if($!==_){var z=A===T,D=w.edge(I).weight;if(N+=z?D:-D,y(x,k,$)){var q=x.edge(k,$).cutvalue;N+=z?-q:q}}}),N}function d(x,w){arguments.length<2&&(w=x.nodes()[0]),f(x,{},1,w)}function f(x,w,k,O,_){var T=k,E=x.node(O);return w[O]=!0,x.neighbors(O).forEach(N=>{Object.hasOwn(w,N)||(k=f(x,w,k,N,O))}),E.low=T,E.lim=k++,_?E.parent=_:delete E.parent,k}function h(x){return x.edges().find(w=>x.edge(w).cutvalue<0)}function p(x,w,k){var O=k.v,_=k.w;w.hasEdge(O,_)||(O=k.w,_=k.v);var T=x.node(O),E=x.node(_),N=T,I=!1;T.lim>E.lim&&(N=E,I=!0);var A=w.edges().filter($=>I===b(x,x.node($.v),N)&&I!==b(x,x.node($.w),N));return A.reduce(($,z)=>t(w,z)<t(w,$)?z:$)}function m(x,w,k,O){var _=k.v,T=k.w;x.removeEdge(_,T),x.setEdge(O.v,O.w,{}),d(x),l(x,w),v(x,w)}function v(x,w){var k=x.nodes().find(_=>!w.node(_).parent),O=r(x,k);O=O.slice(1),O.forEach(_=>{var T=x.node(_).parent,E=w.edge(_,T),N=!1;E||(E=w.edge(T,_),N=!0),w.node(_).rank=w.node(T).rank+(N?E.minlen:-E.minlen)})}function y(x,w,k){return x.hasEdge(w,k)}function b(x,w,k){return k.low<=w.lim&&w.lim<=k.lim}return Zne}var Gne,aUe;function HYn(){if(aUe)return Gne;aUe=1;var e=VU(),t=e.longestPath,n=U_t(),r=VYn();Gne=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return Gne}var Qne,iUe;function WYn(){if(iUe)return Qne;iUe=1,Qne=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,h=u[f],p=!0;for(;a!==l.w;){if(i=r.node(a),p){for(;(h=u[f])!==d&&r.node(h).maxRank<i.rank;)f++;h===d&&(p=!1)}if(!p){for(;f<u.length-1&&r.node(h=u[f+1]).minRank<=i.rank;)f++;h=u[f]}r.setParent(a,h),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,h;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(h=f,f=i;(f=r.parent(f))!==h;)c.push(f);return{path:l.concat(c.reverse()),lca:h}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return Qne}var Yne,oUe;function ZYn(){if(oUe)return Yne;oUe=1;let e=Dl();Yne={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(p=>i.edge(p).minlen*=f);let h=s(i)+1;i.children().forEach(p=>n(i,l,f,h,d,c,p)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,h){let p=i.children(h);if(!p.length){h!==l&&i.setEdge(l,h,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(h);i.setParent(m,h),y.borderTop=m,i.setParent(v,h),y.borderBottom=v,p.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),w=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,O=x.borderTop?u:2*u,_=w!==k?1:d-f[h]+1;i.setEdge(m,w,{weight:O,minlen:_,nestingEdge:!0}),i.setEdge(k,v,{weight:O,minlen:_,nestingEdge:!0})}),i.parent(h)||i.setEdge(l,m,{weight:0,minlen:d+f[h]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(h=>c(h,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return Yne}var Kne,lUe;function GYn(){if(lUe)return Kne;lUe=1;let e=Dl();Kne=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return Kne}var Xne,cUe;function QYn(){if(cUe)return Xne;cUe=1,Xne={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return Xne}var Jne,uUe;function YYn(){if(uUe)return Jne;uUe=1;let e=Dl();Jne=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return Jne}var ere,dUe;function KYn(){if(dUe)return ere;dUe=1;let e=Dl().zipObject;ere=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((h,p)=>p)),l=s.flatMap(h=>r.outEdges(h).map(p=>({pos:i[p.w],weight:r.edge(p).weight})).sort((p,m)=>p.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(h=>{let p=h.pos+c;d[p]+=h.weight;let m=0;for(;p>0;)p%2&&(m+=d[p+1]),p=p-1>>1,d[p]+=h.weight;f+=h.weight*m}),f}return ere}var tre,fUe;function XYn(){if(fUe)return tre;fUe=1,tre=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return tre}var nre,hUe;function JYn(){if(hUe)return nre;hUe=1;let e=Dl();nre=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return nre}var rre,pUe;function eKn(){if(pUe)return rre;pUe=1;let e=Dl();rre=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,h=0;l.sort(r(!!a)),h=n(u,c,h),l.forEach(m=>{h+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,h=n(u,c,h)});let p={vs:u.flat(!0)};return f&&(p.barycenter=d/f,p.weight=f),p}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return rre}var sre,mUe;function tKn(){if(mUe)return sre;mUe=1;let e=XYn(),t=JYn(),n=eKn();sre=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),h=f?f.borderLeft:void 0,p=f?f.borderRight:void 0,m={};h&&(d=d.filter(x=>x!==h&&x!==p));let v=e(i,d);v.forEach(x=>{if(i.children(x.v).length){let w=r(i,x.v,c,u);m[x.v]=w,Object.hasOwn(w,"barycenter")&&a(x,w)}});let y=t(v,c);s(y,m);let b=n(y,u);if(h&&(b.vs=[h,b.vs,p].flat(!0),i.predecessors(h).length)){let x=i.node(i.predecessors(h)[0]),w=i.node(i.predecessors(p)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+w.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return sre}var are,gUe;function nKn(){if(gUe)return are;gUe=1;let e=Gg().Graph,t=Dl();are=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),h=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,h||c),s[i](d).forEach(p=>{let m=p.v===d?p.w:p.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(p).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return are}var ire,vUe;function rKn(){if(vUe)return ire;vUe=1,ire=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return ire}var ore,yUe;function sKn(){if(yUe)return ore;yUe=1;let e=YYn(),t=KYn(),n=tKn(),r=nKn(),s=rKn(),a=Gg().Graph,i=Dl();ore=l;function l(f,h){if(h&&typeof h.customOrder=="function"){h.customOrder(f,l);return}let p=i.maxRank(f),m=c(f,i.range(1,p+1),"inEdges"),v=c(f,i.range(p-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),h&&h.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let w=0,k=0;k<4;++w,++k){u(w%2?m:v,w%4>=2),y=i.buildLayerMatrix(f);let O=t(f,y);O<b&&(k=0,x=Object.assign({},y),b=O)}d(f,x)}function c(f,h,p){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return h.map(function(y){return r(f,y,p,m.get(y)||[])})}function u(f,h){let p=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,p,h);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,p,y.vs)})}function d(f,h){Object.values(h).forEach(p=>p.forEach((m,v)=>f.node(m).order=v))}return ore}var lre,bUe;function aKn(){if(bUe)return lre;bUe=1;let e=Gg().Graph,t=Dl();lre={positionX:p,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:h};function n(y,b){let x={};function w(k,O){let _=0,T=0,E=k.length,N=O[O.length-1];return O.forEach((I,A)=>{let $=s(y,I),z=$?y.node($).order:E;($||I===N)&&(O.slice(T,A+1).forEach(D=>{y.predecessors(D).forEach(q=>{let H=y.node(q),V=H.order;(V<_||z<V)&&!(H.dummy&&y.node(D).dummy)&&a(x,q,D)})}),T=A+1,_=z)}),O}return b.length&&b.reduce(w),x}function r(y,b){let x={};function w(O,_,T,E,N){let I;t.range(_,T).forEach(A=>{I=O[A],y.node(I).dummy&&y.predecessors(I).forEach($=>{let z=y.node($);z.dummy&&(z.order<E||z.order>N)&&a(x,$,I)})})}function k(O,_){let T=-1,E,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let $=y.predecessors(I);$.length&&(E=y.node($[0]).order,w(_,N,A,T,E),N=A,T=E)}w(_,N,_.length,E,O.length)}),_}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let w=y[b];w||(y[b]=w={}),w[x]=!0}function i(y,b,x){if(b>x){let w=b;b=x,x=w}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,w){let k={},O={},_={};return b.forEach(T=>{T.forEach((E,N)=>{k[E]=E,O[E]=E,_[E]=N})}),b.forEach(T=>{let E=-1;T.forEach(N=>{let I=w(N);if(I.length){I=I.sort(($,z)=>_[$]-_[z]);let A=(I.length-1)/2;for(let $=Math.floor(A),z=Math.ceil(A);$<=z;++$){let D=I[$];O[N]===N&&E<_[D]&&!i(x,N,D)&&(O[D]=N,O[N]=k[N]=k[D],E=_[D])}}})}),{root:k,align:O}}function c(y,b,x,w,k){let O={},_=u(y,b,x,k),T=k?"borderLeft":"borderRight";function E(A,$){let z=_.nodes(),D=z.pop(),q={};for(;D;)q[D]?A(D):(q[D]=!0,z.push(D),z=z.concat($(D))),D=z.pop()}function N(A){O[A]=_.inEdges(A).reduce(($,z)=>Math.max($,O[z.v]+_.edge(z)),0)}function I(A){let $=_.outEdges(A).reduce((D,q)=>Math.min(D,O[q.w]-_.edge(q)),Number.POSITIVE_INFINITY),z=y.node(A);$!==Number.POSITIVE_INFINITY&&z.borderType!==T&&(O[A]=Math.max(O[A],$))}return E(N,_.predecessors.bind(_)),E(I,_.successors.bind(_)),Object.keys(w).forEach(A=>O[A]=O[x[A]]),O}function u(y,b,x,w){let k=new e,O=y.graph(),_=m(O.nodesep,O.edgesep,w);return b.forEach(T=>{let E;T.forEach(N=>{let I=x[N];if(k.setNode(I),E){var A=x[E],$=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,E),$||0))}E=N})}),k}function d(y,b){return Object.values(b).reduce((x,w)=>{let k=Number.NEGATIVE_INFINITY,O=Number.POSITIVE_INFINITY;Object.entries(w).forEach(([T,E])=>{let N=v(y,T)/2;k=Math.max(E+N,k),O=Math.min(E-N,O)});const _=k-O;return _<x[0]&&(x=[_,w]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),w=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(O=>{["l","r"].forEach(_=>{let T=O+_,E=y[T];if(E===b)return;let N=Object.values(E),I=w-t.applyWithChunking(Math.min,N);_!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[T]=t.mapValues(E,A=>A+I))})})}function h(y,b){return t.mapValues(y.ul,(x,w)=>{if(b)return y[b.toLowerCase()][w];{let k=Object.values(y).map(O=>O[w]).sort((O,_)=>O-_);return(k[1]+k[2])/2}})}function p(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),w={},k;["u","d"].forEach(_=>{k=_==="u"?b:Object.values(b).reverse(),["l","r"].forEach(T=>{T==="r"&&(k=k.map(A=>Object.values(A).reverse()));let E=(_==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,E),I=c(y,k,N.root,N.align,T==="r");T==="r"&&(I=t.mapValues(I,A=>-A)),w[_+T]=I})});let O=d(y,w);return f(w,O),h(w,y.graph().align)}function m(y,b,x){return(w,k,O)=>{let _=w.node(k),T=w.node(O),E=0,N;if(E+=_.width/2,Object.hasOwn(_,"labelpos"))switch(_.labelpos.toLowerCase()){case"l":N=-_.width/2;break;case"r":N=_.width/2;break}if(N&&(E+=x?N:-N),N=0,E+=(_.dummy?b:y)/2,E+=(T.dummy?b:y)/2,E+=T.width/2,Object.hasOwn(T,"labelpos"))switch(T.labelpos.toLowerCase()){case"l":N=T.width/2;break;case"r":N=-T.width/2;break}return N&&(E+=x?N:-N),N=0,E}}function v(y,b){return y.node(b).width}return lre}var cre,xUe;function iKn(){if(xUe)return cre;xUe=1;let e=Dl(),t=aKn().positionX;cre=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const h=s.node(f).height;return d>h?d:h},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return cre}var ure,wUe;function oKn(){if(wUe)return ure;wUe=1;let e=UYn(),t=qYn(),n=HYn(),r=Dl().normalizeRanks,s=WYn(),a=Dl().removeEmptyRanks,i=ZYn(),l=GYn(),c=QYn(),u=sKn(),d=iKn(),f=Dl(),h=Gg().Graph;ure=p;function p(R,F){let U=F&&F.debugTiming?f.time:f.notime;U("layout",()=>{let Q=U(" buildLayoutGraph",()=>E(R));U(" runLayout",()=>m(Q,U,F)),U(" updateInputGraph",()=>v(R,Q))})}function m(R,F,U){F(" makeSpaceForEdgeLabels",()=>N(R)),F(" removeSelfEdges",()=>B(R)),F(" acyclic",()=>e.run(R)),F(" nestingGraph.run",()=>i.run(R)),F(" rank",()=>n(f.asNonCompoundGraph(R))),F(" injectEdgeLabelProxies",()=>I(R)),F(" removeEmptyRanks",()=>a(R)),F(" nestingGraph.cleanup",()=>i.cleanup(R)),F(" normalizeRanks",()=>r(R)),F(" assignRankMinMax",()=>A(R)),F(" removeEdgeLabelProxies",()=>$(R)),F(" normalize.run",()=>t.run(R)),F(" parentDummyChains",()=>s(R)),F(" addBorderSegments",()=>l(R)),F(" order",()=>u(R,U)),F(" insertSelfEdges",()=>W(R)),F(" adjustCoordinateSystem",()=>c.adjust(R)),F(" position",()=>d(R)),F(" positionSelfEdges",()=>L(R)),F(" removeBorderNodes",()=>V(R)),F(" normalize.undo",()=>t.undo(R)),F(" fixupEdgeLabelCoords",()=>q(R)),F(" undoCoordinateSystem",()=>c.undo(R)),F(" translateGraph",()=>z(R)),F(" assignNodeIntersects",()=>D(R)),F(" reversePoints",()=>H(R)),F(" acyclic.undo",()=>e.undo(R))}function v(R,F){R.nodes().forEach(U=>{let Q=R.node(U),te=F.node(U);Q&&(Q.x=te.x,Q.y=te.y,Q.rank=te.rank,F.children(U).length&&(Q.width=te.width,Q.height=te.height))}),R.edges().forEach(U=>{let Q=R.edge(U),te=F.edge(U);Q.points=te.points,Object.hasOwn(te,"x")&&(Q.x=te.x,Q.y=te.y)}),R.graph().width=F.graph().width,R.graph().height=F.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],w=["width","height","rank"],k={width:0,height:0},O=["minlen","weight","width","height","labeloffset"],_={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},T=["labelpos"];function E(R){let F=new h({multigraph:!0,compound:!0}),U=M(R.graph());return F.setGraph(Object.assign({},b,G(U,y),f.pick(U,x))),R.nodes().forEach(Q=>{let te=M(R.node(Q));const J=G(te,w);Object.keys(k).forEach(ee=>{J[ee]===void 0&&(J[ee]=k[ee])}),F.setNode(Q,J),F.setParent(Q,R.parent(Q))}),R.edges().forEach(Q=>{let te=M(R.edge(Q));F.setEdge(Q,Object.assign({},_,G(te,O),f.pick(te,T)))}),F}function N(R){let F=R.graph();F.ranksep/=2,R.edges().forEach(U=>{let Q=R.edge(U);Q.minlen*=2,Q.labelpos.toLowerCase()!=="c"&&(F.rankdir==="TB"||F.rankdir==="BT"?Q.width+=Q.labeloffset:Q.height+=Q.labeloffset)})}function I(R){R.edges().forEach(F=>{let U=R.edge(F);if(U.width&&U.height){let Q=R.node(F.v),J={rank:(R.node(F.w).rank-Q.rank)/2+Q.rank,e:F};f.addDummyNode(R,"edge-proxy",J,"_ep")}})}function A(R){let F=0;R.nodes().forEach(U=>{let Q=R.node(U);Q.borderTop&&(Q.minRank=R.node(Q.borderTop).rank,Q.maxRank=R.node(Q.borderBottom).rank,F=Math.max(F,Q.maxRank))}),R.graph().maxRank=F}function $(R){R.nodes().forEach(F=>{let U=R.node(F);U.dummy==="edge-proxy"&&(R.edge(U.e).labelRank=U.rank,R.removeNode(F))})}function z(R){let F=Number.POSITIVE_INFINITY,U=0,Q=Number.POSITIVE_INFINITY,te=0,J=R.graph(),ee=J.marginx||0,re=J.marginy||0;function ae(X){let ne=X.x,se=X.y,ce=X.width,le=X.height;F=Math.min(F,ne-ce/2),U=Math.max(U,ne+ce/2),Q=Math.min(Q,se-le/2),te=Math.max(te,se+le/2)}R.nodes().forEach(X=>ae(R.node(X))),R.edges().forEach(X=>{let ne=R.edge(X);Object.hasOwn(ne,"x")&&ae(ne)}),F-=ee,Q-=re,R.nodes().forEach(X=>{let ne=R.node(X);ne.x-=F,ne.y-=Q}),R.edges().forEach(X=>{let ne=R.edge(X);ne.points.forEach(se=>{se.x-=F,se.y-=Q}),Object.hasOwn(ne,"x")&&(ne.x-=F),Object.hasOwn(ne,"y")&&(ne.y-=Q)}),J.width=U-F+ee,J.height=te-Q+re}function D(R){R.edges().forEach(F=>{let U=R.edge(F),Q=R.node(F.v),te=R.node(F.w),J,ee;U.points?(J=U.points[0],ee=U.points[U.points.length-1]):(U.points=[],J=te,ee=Q),U.points.unshift(f.intersectRect(Q,J)),U.points.push(f.intersectRect(te,ee))})}function q(R){R.edges().forEach(F=>{let U=R.edge(F);if(Object.hasOwn(U,"x"))switch((U.labelpos==="l"||U.labelpos==="r")&&(U.width-=U.labeloffset),U.labelpos){case"l":U.x-=U.width/2+U.labeloffset;break;case"r":U.x+=U.width/2+U.labeloffset;break}})}function H(R){R.edges().forEach(F=>{let U=R.edge(F);U.reversed&&U.points.reverse()})}function V(R){R.nodes().forEach(F=>{if(R.children(F).length){let U=R.node(F),Q=R.node(U.borderTop),te=R.node(U.borderBottom),J=R.node(U.borderLeft[U.borderLeft.length-1]),ee=R.node(U.borderRight[U.borderRight.length-1]);U.width=Math.abs(ee.x-J.x),U.height=Math.abs(te.y-Q.y),U.x=J.x+U.width/2,U.y=Q.y+U.height/2}}),R.nodes().forEach(F=>{R.node(F).dummy==="border"&&R.removeNode(F)})}function B(R){R.edges().forEach(F=>{if(F.v===F.w){var U=R.node(F.v);U.selfEdges||(U.selfEdges=[]),U.selfEdges.push({e:F,label:R.edge(F)}),R.removeEdge(F)}})}function W(R){var F=f.buildLayerMatrix(R);F.forEach(U=>{var Q=0;U.forEach((te,J)=>{var ee=R.node(te);ee.order=J+Q,(ee.selfEdges||[]).forEach(re=>{f.addDummyNode(R,"selfedge",{width:re.label.width,height:re.label.height,rank:ee.rank,order:J+ ++Q,e:re.e,label:re.label},"_se")}),delete ee.selfEdges})})}function L(R){R.nodes().forEach(F=>{var U=R.node(F);if(U.dummy==="selfedge"){var Q=R.node(U.e.v),te=Q.x+Q.width/2,J=Q.y,ee=U.x-te,re=Q.height/2;R.setEdge(U.e,U.label),R.removeNode(F),U.label.points=[{x:te+2*ee/3,y:J-re},{x:te+5*ee/6,y:J-re},{x:te+ee,y:J},{x:te+5*ee/6,y:J+re},{x:te+2*ee/3,y:J+re}],U.label.x=U.x,U.label.y=U.y}})}function G(R,F){return f.mapValues(f.pick(R,F),Number)}function M(R){var F={};return R&&Object.entries(R).forEach(([U,Q])=>{typeof U=="string"&&(U=U.toLowerCase()),F[U]=Q}),F}return ure}var dre,SUe;function lKn(){if(SUe)return dre;SUe=1;let e=Dl(),t=Gg().Graph;dre={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return dre}var fre,kUe;function cKn(){return kUe||(kUe=1,fre="1.1.8"),fre}var hre,OUe;function uKn(){return OUe||(OUe=1,hre={graphlib:Gg(),layout:oKn(),debug:lKn(),util:{time:Dl().time,notime:Dl().notime},version:cKn()}),hre}var dKn=uKn();const CUe=Hl(dKn);function Gl(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=Gl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var fKn={value:()=>{}};function cZ(){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 L9(n)}function L9(e){this._=e}function hKn(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}L9.prototype=cZ.prototype={constructor:L9,on:function(e,t){var n=this._,r=hKn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=pKn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=_Ue(n[s],e.name,t);else if(t==null)for(s in n)n[s]=_Ue(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new L9(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++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],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function pKn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function _Ue(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=fKn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Bye="http://www.w3.org/1999/xhtml";const EUe={svg:"http://www.w3.org/2000/svg",xhtml:Bye,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function uZ(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),EUe.hasOwnProperty(t)?{space:EUe[t],local:e}:e}function mKn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Bye&&t.documentElement.namespaceURI===Bye?t.createElement(e):t.createElementNS(n,e)}}function gKn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function q_t(e){var t=uZ(e);return(t.local?gKn:mKn)(t)}function vKn(){}function YCe(e){return e==null?vKn:function(){return this.querySelector(e)}}function yKn(e){typeof e!="function"&&(e=YCe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new np(r,this._parents)}function bKn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function xKn(){return[]}function V_t(e){return e==null?xKn:function(){return this.querySelectorAll(e)}}function wKn(e){return function(){return bKn(e.apply(this,arguments))}}function SKn(e){typeof e=="function"?e=wKn(e):e=V_t(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new np(r,s)}function H_t(e){return function(){return this.matches(e)}}function W_t(e){return function(t){return t.matches(e)}}var kKn=Array.prototype.find;function OKn(e){return function(){return kKn.call(this.children,e)}}function CKn(){return this.firstElementChild}function _Kn(e){return this.select(e==null?CKn:OKn(typeof e=="function"?e:W_t(e)))}var EKn=Array.prototype.filter;function TKn(){return Array.from(this.children)}function jKn(e){return function(){return EKn.call(this.children,e)}}function NKn(e){return this.selectAll(e==null?TKn:jKn(typeof e=="function"?e:W_t(e)))}function IKn(e){typeof e!="function"&&(e=H_t(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new np(r,this._parents)}function Z_t(e){return new Array(e.length)}function AKn(){return new np(this._enter||this._groups.map(Z_t),this._parents)}function HU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}HU.prototype={constructor:HU,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 RKn(e){return function(){return e}}function PKn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new HU(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function $Kn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,h=new Array(d),p;for(l=0;l<d;++l)(c=t[l])&&(h[l]=p=i.call(c,c.__data__,l,t)+"",u.has(p)?s[l]=c:u.set(p,c));for(l=0;l<f;++l)p=i.call(e,a[l],l,a)+"",(c=u.get(p))?(r[l]=c,c.__data__=a[l],u.delete(p)):n[l]=new HU(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(h[l])===c&&(s[l]=c)}function MKn(e){return e.__data__}function DKn(e,t){if(!arguments.length)return Array.from(this,MKn);var n=t?$Kn:PKn,r=this._parents,s=this._groups;typeof e!="function"&&(e=RKn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],h=f.length,p=LKn(e.call(d,d&&d.__data__,u,r)),m=p.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(h);n(d,f,v,y,b,p,t);for(var x=0,w=0,k,O;x<m;++x)if(k=v[x]){for(x>=w&&(w=x+1);!(O=y[w])&&++w<m;);k._next=O||null}}return i=new np(i,r),i._enter=l,i._exit=c,i}function LKn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function FKn(){return new np(this._exit||this._groups.map(Z_t),this._parents)}function zKn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function BKn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,h=l[c]=new Array(f),p,m=0;m<f;++m)(p=u[m]||d[m])&&(h[m]=p);for(;c<s;++c)l[c]=n[c];return new np(l,this._parents)}function UKn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function qKn(e){e||(e=VKn);function t(f,h){return f&&h?e(f.__data__,h.__data__):!f-!h}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new np(s,this._parents).order()}function VKn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function HKn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function WKn(){return Array.from(this)}function ZKn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function GKn(){let e=0;for(const t of this)++e;return e}function QKn(){return!this.node()}function YKn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function KKn(e){return function(){this.removeAttribute(e)}}function XKn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function JKn(e,t){return function(){this.setAttribute(e,t)}}function eXn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function tXn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function nXn(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 rXn(e,t){var n=uZ(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?XKn:KKn:typeof t=="function"?n.local?nXn:tXn:n.local?eXn:JKn)(n,t))}function G_t(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function sXn(e){return function(){this.style.removeProperty(e)}}function aXn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function iXn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function oXn(e,t,n){return arguments.length>1?this.each((t==null?sXn:typeof t=="function"?iXn:aXn)(e,t,n??"")):ON(this.node(),e)}function ON(e,t){return e.style.getPropertyValue(t)||G_t(e).getComputedStyle(e,null).getPropertyValue(t)}function lXn(e){return function(){delete this[e]}}function cXn(e,t){return function(){this[e]=t}}function uXn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function dXn(e,t){return arguments.length>1?this.each((t==null?lXn:typeof t=="function"?uXn:cXn)(e,t)):this.node()[e]}function Q_t(e){return e.trim().split(/^|\s+/)}function KCe(e){return e.classList||new Y_t(e)}function Y_t(e){this._node=e,this._names=Q_t(e.getAttribute("class")||"")}Y_t.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 K_t(e,t){for(var n=KCe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function X_t(e,t){for(var n=KCe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function fXn(e){return function(){K_t(this,e)}}function hXn(e){return function(){X_t(this,e)}}function pXn(e,t){return function(){(t.apply(this,arguments)?K_t:X_t)(this,e)}}function mXn(e,t){var n=Q_t(e+"");if(arguments.length<2){for(var r=KCe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?pXn:t?fXn:hXn)(n,t))}function gXn(){this.textContent=""}function vXn(e){return function(){this.textContent=e}}function yXn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function bXn(e){return arguments.length?this.each(e==null?gXn:(typeof e=="function"?yXn:vXn)(e)):this.node().textContent}function xXn(){this.innerHTML=""}function wXn(e){return function(){this.innerHTML=e}}function SXn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function kXn(e){return arguments.length?this.each(e==null?xXn:(typeof e=="function"?SXn:wXn)(e)):this.node().innerHTML}function OXn(){this.nextSibling&&this.parentNode.appendChild(this)}function CXn(){return this.each(OXn)}function _Xn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function EXn(){return this.each(_Xn)}function TXn(e){var t=typeof e=="function"?e:q_t(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function jXn(){return null}function NXn(e,t){var n=typeof e=="function"?e:q_t(e),r=t==null?jXn:typeof t=="function"?t:YCe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function IXn(){var e=this.parentNode;e&&e.removeChild(this)}function AXn(){return this.each(IXn)}function RXn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function PXn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function $Xn(e){return this.select(e?PXn:RXn)}function MXn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function DXn(e){return function(t){e.call(this,t,this.__data__)}}function LXn(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 FXn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++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 zXn(e,t,n){return function(){var r=this.__on,s,a=DXn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function BXn(e,t,n){var r=LXn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?zXn:FXn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function J_t(e,t,n){var r=G_t(e),s=r.CustomEvent;typeof s=="function"?s=new s(t,n):(s=r.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function UXn(e,t){return function(){return J_t(this,e,t)}}function qXn(e,t){return function(){return J_t(this,e,t.apply(this,arguments))}}function VXn(e,t){return this.each((typeof t=="function"?qXn:UXn)(e,t))}function*HXn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var eEt=[null];function np(e,t){this._groups=e,this._parents=t}function PL(){return new np([[document.documentElement]],eEt)}function WXn(){return this}np.prototype=PL.prototype={constructor:np,select:yKn,selectAll:SKn,selectChild:_Kn,selectChildren:NKn,filter:IKn,data:DKn,enter:AKn,exit:FKn,join:zKn,merge:BKn,selection:WXn,order:UKn,sort:qKn,call:HKn,nodes:WKn,node:ZKn,size:GKn,empty:QKn,each:YKn,attr:rXn,style:oXn,property:dXn,classed:mXn,text:bXn,html:kXn,raise:CXn,lower:EXn,append:TXn,insert:NXn,remove:AXn,clone:$Xn,datum:MXn,on:BXn,dispatch:VXn,[Symbol.iterator]:HXn};function Ah(e){return typeof e=="string"?new np([[document.querySelector(e)]],[document.documentElement]):new np([[e]],eEt)}function ZXn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function yg(e,t){if(e=ZXn(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 s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const GXn={passive:!1},pD={capture:!0,passive:!1};function pre(e){e.stopImmediatePropagation()}function Aj(e){e.preventDefault(),e.stopImmediatePropagation()}function tEt(e){var t=e.document.documentElement,n=Ah(e).on("dragstart.drag",Aj,pD);"onselectstart"in t?n.on("selectstart.drag",Aj,pD):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function nEt(e,t){var n=e.document.documentElement,r=Ah(e).on("dragstart.drag",null);t&&(r.on("click.drag",Aj,pD),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 rz=e=>()=>e;function Uye(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,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:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}Uye.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function QXn(e){return!e.ctrlKey&&!e.button}function YXn(){return this.parentNode}function KXn(e,t){return t??{x:e.x,y:e.y}}function XXn(){return navigator.maxTouchPoints||"ontouchstart"in this}function rEt(){var e=QXn,t=YXn,n=KXn,r=XXn,s={},a=cZ("start","drag","end"),i=0,l,c,u,d,f=0;function h(k){k.on("mousedown.drag",p).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,GXn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(k,O){if(!(d||!e.call(this,k,O))){var _=w(this,t.call(this,k,O),k,O,"mouse");_&&(Ah(k.view).on("mousemove.drag",m,pD).on("mouseup.drag",v,pD),tEt(k.view),pre(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(Aj(k),!u){var O=k.clientX-l,_=k.clientY-c;u=O*O+_*_>f}s.mouse("drag",k)}function v(k){Ah(k.view).on("mousemove.drag mouseup.drag",null),nEt(k.view,u),Aj(k),s.mouse("end",k)}function y(k,O){if(e.call(this,k,O)){var _=k.changedTouches,T=t.call(this,k,O),E=_.length,N,I;for(N=0;N<E;++N)(I=w(this,T,k,O,_[N].identifier,_[N]))&&(pre(k),I("start",k,_[N]))}}function b(k){var O=k.changedTouches,_=O.length,T,E;for(T=0;T<_;++T)(E=s[O[T].identifier])&&(Aj(k),E("drag",k,O[T]))}function x(k){var O=k.changedTouches,_=O.length,T,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),T=0;T<_;++T)(E=s[O[T].identifier])&&(pre(k),E("end",k,O[T]))}function w(k,O,_,T,E,N){var I=a.copy(),A=yg(N||_,O),$,z,D;if((D=n.call(k,new Uye("beforestart",{sourceEvent:_,target:h,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return $=D.x-A[0]||0,z=D.y-A[1]||0,function q(H,V,B){var W=A,L;switch(H){case"start":s[E]=q,L=i++;break;case"end":delete s[E],--i;case"drag":A=yg(B||V,O),L=i;break}I.call(H,k,new Uye(H,{sourceEvent:V,subject:D,target:h,identifier:E,active:L,x:A[0]+$,y:A[1]+z,dx:A[0]-W[0],dy:A[1]-W[1],dispatch:I}),T)}}return h.filter=function(k){return arguments.length?(e=typeof k=="function"?k:rz(!!k),h):e},h.container=function(k){return arguments.length?(t=typeof k=="function"?k:rz(k),h):t},h.subject=function(k){return arguments.length?(n=typeof k=="function"?k:rz(k),h):n},h.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:rz(!!k),h):r},h.on=function(){var k=a.on.apply(a,arguments);return k===a?h:k},h.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,h):Math.sqrt(f)},h}function XCe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function sEt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function $L(){}var mD=.7,WU=1/mD,Rj="\\s*([+-]?\\d+)\\s*",gD="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ky="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",JXn=/^#([0-9a-f]{3,8})$/,eJn=new RegExp(`^rgb\\(${Rj},${Rj},${Rj}\\)$`),tJn=new RegExp(`^rgb\\(${ky},${ky},${ky}\\)$`),nJn=new RegExp(`^rgba\\(${Rj},${Rj},${Rj},${gD}\\)$`),rJn=new RegExp(`^rgba\\(${ky},${ky},${ky},${gD}\\)$`),sJn=new RegExp(`^hsl\\(${gD},${ky},${ky}\\)$`),aJn=new RegExp(`^hsla\\(${gD},${ky},${ky},${gD}\\)$`),TUe={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};XCe($L,wC,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:jUe,formatHex:jUe,formatHex8:iJn,formatHsl:oJn,formatRgb:NUe,toString:NUe});function jUe(){return this.rgb().formatHex()}function iJn(){return this.rgb().formatHex8()}function oJn(){return aEt(this).formatHsl()}function NUe(){return this.rgb().formatRgb()}function wC(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=JXn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?IUe(t):n===3?new Nf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?sz(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?sz(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=eJn.exec(e))?new Nf(t[1],t[2],t[3],1):(t=tJn.exec(e))?new Nf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=nJn.exec(e))?sz(t[1],t[2],t[3],t[4]):(t=rJn.exec(e))?sz(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=sJn.exec(e))?PUe(t[1],t[2]/100,t[3]/100,1):(t=aJn.exec(e))?PUe(t[1],t[2]/100,t[3]/100,t[4]):TUe.hasOwnProperty(e)?IUe(TUe[e]):e==="transparent"?new Nf(NaN,NaN,NaN,0):null}function IUe(e){return new Nf(e>>16&255,e>>8&255,e&255,1)}function sz(e,t,n,r){return r<=0&&(e=t=n=NaN),new Nf(e,t,n,r)}function lJn(e){return e instanceof $L||(e=wC(e)),e?(e=e.rgb(),new Nf(e.r,e.g,e.b,e.opacity)):new Nf}function qye(e,t,n,r){return arguments.length===1?lJn(e):new Nf(e,t,n,r??1)}function Nf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}XCe(Nf,qye,sEt($L,{brighter(e){return e=e==null?WU:Math.pow(WU,e),new Nf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?mD:Math.pow(mD,e),new Nf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Nf(EO(this.r),EO(this.g),EO(this.b),ZU(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:AUe,formatHex:AUe,formatHex8:cJn,formatRgb:RUe,toString:RUe}));function AUe(){return`#${oO(this.r)}${oO(this.g)}${oO(this.b)}`}function cJn(){return`#${oO(this.r)}${oO(this.g)}${oO(this.b)}${oO((isNaN(this.opacity)?1:this.opacity)*255)}`}function RUe(){const e=ZU(this.opacity);return`${e===1?"rgb(":"rgba("}${EO(this.r)}, ${EO(this.g)}, ${EO(this.b)}${e===1?")":`, ${e})`}`}function ZU(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function EO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function oO(e){return e=EO(e),(e<16?"0":"")+e.toString(16)}function PUe(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Cg(e,t,n,r)}function aEt(e){if(e instanceof Cg)return new Cg(e.h,e.s,e.l,e.opacity);if(e instanceof $L||(e=wC(e)),!e)return new Cg;if(e instanceof Cg)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new Cg(i,l,c,e.opacity)}function uJn(e,t,n,r){return arguments.length===1?aEt(e):new Cg(e,t,n,r??1)}function Cg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}XCe(Cg,uJn,sEt($L,{brighter(e){return e=e==null?WU:Math.pow(WU,e),new Cg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?mD:Math.pow(mD,e),new Cg(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new Nf(mre(e>=240?e-240:e+120,s,r),mre(e,s,r),mre(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new Cg($Ue(this.h),az(this.s),az(this.l),ZU(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=ZU(this.opacity);return`${e===1?"hsl(":"hsla("}${$Ue(this.h)}, ${az(this.s)*100}%, ${az(this.l)*100}%${e===1?")":`, ${e})`}`}}));function $Ue(e){return e=(e||0)%360,e<0?e+360:e}function az(e){return Math.max(0,Math.min(1,e||0))}function mre(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const JCe=e=>()=>e;function dJn(e,t){return function(n){return e+n*t}}function fJn(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function hJn(e){return(e=+e)==1?iEt:function(t,n){return n-t?fJn(t,n,e):JCe(isNaN(t)?n:t)}}function iEt(e,t){var n=t-e;return n?dJn(e,n):JCe(isNaN(e)?t:e)}const GU=(function e(t){var n=hJn(t);function r(s,a){var i=n((s=qye(s)).r,(a=qye(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=iEt(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function pJn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function mJn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function gJn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=Cx(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function vJn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function xg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function yJn(e,t){var n={},r={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=Cx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Vye=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,gre=new RegExp(Vye.source,"g");function bJn(e){return function(){return e}}function xJn(e){return function(t){return e(t)+""}}function oEt(e,t){var n=Vye.lastIndex=gre.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Vye.exec(e))&&(s=gre.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:xg(r,s)})),n=gre.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?xJn(c[0].x):bJn(t):(t=c.length,function(u){for(var d=0,f;d<t;++d)l[(f=c[d]).i]=f.x(u);return l.join("")})}function Cx(e,t){var n=typeof t,r;return t==null||n==="boolean"?JCe(t):(n==="number"?xg:n==="string"?(r=wC(t))?(t=r,GU):oEt:t instanceof wC?GU:t instanceof Date?vJn:mJn(t)?pJn:Array.isArray(t)?gJn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?yJn:xg)(e,t)}function e_e(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var MUe=180/Math.PI,Hye={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function lEt(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*MUe,skewX:Math.atan(c)*MUe,scaleX:i,scaleY:l}}var iz;function wJn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Hye:lEt(t.a,t.b,t.c,t.d,t.e,t.f)}function SJn(e){return e==null||(iz||(iz=document.createElementNS("http://www.w3.org/2000/svg","g")),iz.setAttribute("transform",e),!(e=iz.transform.baseVal.consolidate()))?Hye:(e=e.matrix,lEt(e.a,e.b,e.c,e.d,e.e,e.f))}function cEt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push("translate(",null,t,null,n);m.push({i:v-4,x:xg(u,f)},{i:v-2,x:xg(d,h)})}else(f||h)&&p.push("translate("+f+t+h+n)}function i(u,d,f,h){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),h.push({i:f.push(s(f)+"rotate(",null,r)-2,x:xg(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,h){u!==d?h.push({i:f.push(s(f)+"skewX(",null,r)-2,x:xg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push(s(p)+"scale(",null,",",null,")");m.push({i:v-4,x:xg(u,f)},{i:v-2,x:xg(d,h)})}else(f!==1||h!==1)&&p.push(s(p)+"scale("+f+","+h+")")}return function(u,d){var f=[],h=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,h),i(u.rotate,d.rotate,f,h),l(u.skewX,d.skewX,f,h),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,h),u=d=null,function(p){for(var m=-1,v=h.length,y;++m<v;)f[(y=h[m]).i]=y.x(p);return f.join("")}}}var kJn=cEt(wJn,"px, ","px)","deg)"),OJn=cEt(SJn,", ",")",")"),CJn=1e-12;function DUe(e){return((e=Math.exp(e))+1/e)/2}function _Jn(e){return((e=Math.exp(e))-1/e)/2}function EJn(e){return((e=Math.exp(2*e))-1)/(e+1)}const F9=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],h=i[2],p=d-l,m=f-c,v=p*p+m*m,y,b;if(v<CJn)b=Math.log(h/u)/t,y=function(T){return[l+T*p,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(v),w=(h*h-u*u+r*v)/(2*u*n*x),k=(h*h-u*u-r*v)/(2*h*n*x),O=Math.log(Math.sqrt(w*w+1)-w),_=Math.log(Math.sqrt(k*k+1)-k);b=(_-O)/t,y=function(T){var E=T*b,N=DUe(O),I=u/(n*x)*(N*EJn(t*E+O)-_Jn(O));return[l+I*p,c+I*m,u*N/DUe(t*E+O)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function TJn(e,t){t===void 0&&(t=e,e=Cx);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var CN=0,T$=0,hP=0,uEt=1e3,QU,j$,YU=0,SC=0,dZ=0,vD=typeof performance=="object"&&performance.now?performance:Date,dEt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function t_e(){return SC||(dEt(jJn),SC=vD.now()+dZ)}function jJn(){SC=0}function KU(){this._call=this._time=this._next=null}KU.prototype=fEt.prototype={constructor:KU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?t_e():+n)+(t==null?0:+t),!this._next&&j$!==this&&(j$?j$._next=this:QU=this,j$=this),this._call=e,this._time=n,Wye()},stop:function(){this._call&&(this._call=null,this._time=1/0,Wye())}};function fEt(e,t,n){var r=new KU;return r.restart(e,t,n),r}function NJn(){t_e(),++CN;for(var e=QU,t;e;)(t=SC-e._time)>=0&&e._call.call(void 0,t),e=e._next;--CN}function LUe(){SC=(YU=vD.now())+dZ,CN=T$=0;try{NJn()}finally{CN=0,AJn(),SC=0}}function IJn(){var e=vD.now(),t=e-YU;t>uEt&&(dZ-=t,YU=e)}function AJn(){for(var e,t=QU,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:QU=n);j$=e,Wye(r)}function Wye(e){if(!CN){T$&&(T$=clearTimeout(T$));var t=e-SC;t>24?(e<1/0&&(T$=setTimeout(LUe,e-vD.now()-dZ)),hP&&(hP=clearInterval(hP))):(hP||(YU=vD.now(),hP=setInterval(IJn,uEt)),CN=1,dEt(LUe))}}function FUe(e,t,n){var r=new KU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var RJn=cZ("start","end","cancel","interrupt"),PJn=[],hEt=0,zUe=1,Zye=2,z9=3,BUe=4,Gye=5,B9=6;function fZ(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;$Jn(e,n,{name:t,index:r,group:s,on:RJn,tween:PJn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:hEt})}function n_e(e,t){var n=iv(e,t);if(n.state>hEt)throw new Error("too late; already scheduled");return n}function eb(e,t){var n=iv(e,t);if(n.state>z9)throw new Error("too late; already running");return n}function iv(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function $Jn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=fEt(a,0,n.time);function a(u){n.state=zUe,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,h,p;if(n.state!==zUe)return c();for(d in r)if(p=r[d],p.name===n.name){if(p.state===z9)return FUe(i);p.state===BUe?(p.state=B9,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[d]):+d<t&&(p.state=B9,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[d])}if(FUe(function(){n.state===z9&&(n.state=BUe,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Zye,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Zye){for(n.state=z9,s=new Array(h=n.tween.length),d=0,f=-1;d<h;++d)(p=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=p);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=Gye,1),f=-1,h=s.length;++f<h;)s[f].call(e,d);n.state===Gye&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=B9,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function U9(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Zye&&r.state<Gye,r.state=B9,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function MJn(e){return this.each(function(){U9(this,e)})}function DJn(e,t){var n,r;return function(){var s=eb(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function LJn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=eb(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function FJn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=iv(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?DJn:LJn)(n,e,t))}function r_e(e,t,n){var r=e._id;return e.each(function(){var s=eb(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return iv(s,r).value[t]}}function pEt(e,t){var n;return(typeof t=="number"?xg:t instanceof wC?GU:(n=wC(t))?(t=n,GU):oEt)(e,t)}function zJn(e){return function(){this.removeAttribute(e)}}function BJn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function UJn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function qJn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function VJn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function HJn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function WJn(e,t){var n=uZ(e),r=n==="transform"?OJn:pEt;return this.attrTween(e,typeof t=="function"?(n.local?HJn:VJn)(n,r,r_e(this,"attr."+e,t)):t==null?(n.local?BJn:zJn)(n):(n.local?qJn:UJn)(n,r,t))}function ZJn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function GJn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function QJn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&GJn(e,a)),n}return s._value=t,s}function YJn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&ZJn(e,a)),n}return s._value=t,s}function KJn(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=uZ(e);return this.tween(n,(r.local?QJn:YJn)(r,t))}function XJn(e,t){return function(){n_e(this,e).delay=+t.apply(this,arguments)}}function JJn(e,t){return t=+t,function(){n_e(this,e).delay=t}}function eer(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?XJn:JJn)(t,e)):iv(this.node(),t).delay}function ter(e,t){return function(){eb(this,e).duration=+t.apply(this,arguments)}}function ner(e,t){return t=+t,function(){eb(this,e).duration=t}}function rer(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?ter:ner)(t,e)):iv(this.node(),t).duration}function ser(e,t){if(typeof t!="function")throw new Error;return function(){eb(this,e).ease=t}}function aer(e){var t=this._id;return arguments.length?this.each(ser(t,e)):iv(this.node(),t).ease}function ier(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;eb(this,e).ease=n}}function oer(e){if(typeof e!="function")throw new Error;return this.each(ier(this._id,e))}function ler(e){typeof e!="function"&&(e=H_t(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Gx(r,this._parents,this._name,this._id)}function cer(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),h,p=0;p<d;++p)(h=c[p]||u[p])&&(f[p]=h);for(;l<r;++l)i[l]=t[l];return new Gx(i,this._parents,this._name,this._id)}function uer(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 der(e,t,n){var r,s,a=uer(t)?n_e:eb;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function fer(e,t){var n=this._id;return arguments.length<2?iv(this.node(),n).on.on(e):this.each(der(n,e,t))}function her(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function per(){return this.on("end.remove",her(this._id))}function mer(e){var t=this._name,n=this._id;typeof e!="function"&&(e=YCe(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,h=0;h<c;++h)(d=l[h])&&(f=e.call(d,d.__data__,h,l))&&("__data__"in d&&(f.__data__=d.__data__),u[h]=f,fZ(u[h],t,n,h,u,iv(d,n)));return new Gx(a,this._parents,t,n)}function ger(e){var t=this._name,n=this._id;typeof e!="function"&&(e=V_t(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var h=e.call(d,d.__data__,f,c),p,m=iv(d,n),v=0,y=h.length;v<y;++v)(p=h[v])&&fZ(p,t,n,v,h,m);a.push(h),i.push(d)}return new Gx(a,i,t,n)}var ver=PL.prototype.constructor;function yer(){return new ver(this._groups,this._parents)}function ber(e,t){var n,r,s;return function(){var a=ON(this,e),i=(this.style.removeProperty(e),ON(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function mEt(e){return function(){this.style.removeProperty(e)}}function xer(e,t,n){var r,s=n+"",a;return function(){var i=ON(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function wer(e,t,n){var r,s,a;return function(){var i=ON(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),ON(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function Ser(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=eb(this,e),u=c.on,d=c.value[a]==null?l||(l=mEt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function ker(e,t,n){var r=(e+="")=="transform"?kJn:pEt;return t==null?this.styleTween(e,ber(e,r)).on("end.style."+e,mEt(e)):typeof t=="function"?this.styleTween(e,wer(e,r,r_e(this,"style."+e,t))).each(Ser(this._id,e)):this.styleTween(e,xer(e,r,t),n).on("end.style."+e,null)}function Oer(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function Cer(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&Oer(e,i,n)),r}return a._value=t,a}function _er(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,Cer(e,t,n??""))}function Eer(e){return function(){this.textContent=e}}function Ter(e){return function(){var t=e(this);this.textContent=t??""}}function jer(e){return this.tween("text",typeof e=="function"?Ter(r_e(this,"text",e)):Eer(e==null?"":e+""))}function Ner(e){return function(t){this.textContent=e.call(this,t)}}function Ier(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&Ner(s)),t}return r._value=e,r}function Aer(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,Ier(e))}function Rer(){for(var e=this._name,t=this._id,n=gEt(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=iv(c,t);fZ(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Gx(r,this._parents,e,n)}function Per(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=eb(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var $er=0;function Gx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function gEt(){return++$er}var $b=PL.prototype;Gx.prototype={constructor:Gx,select:mer,selectAll:ger,selectChild:$b.selectChild,selectChildren:$b.selectChildren,filter:ler,merge:cer,selection:yer,transition:Rer,call:$b.call,nodes:$b.nodes,node:$b.node,size:$b.size,empty:$b.empty,each:$b.each,on:fer,attr:WJn,attrTween:KJn,style:ker,styleTween:_er,text:jer,textTween:Aer,remove:per,tween:FJn,delay:eer,duration:rer,ease:aer,easeVarying:oer,end:Per,[Symbol.iterator]:$b[Symbol.iterator]};function Mer(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var Der={time:null,delay:0,duration:250,ease:Mer};function Ler(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 Fer(e){var t,n;e instanceof Gx?(t=e._id,e=e._name):(t=gEt(),(n=Der).time=t_e(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&fZ(c,e,t,u,i,n||Ler(c,t));return new Gx(r,this._parents,e,t)}PL.prototype.interrupt=MJn;PL.prototype.transition=Fer;const oz=e=>()=>e;function zer(e,{sourceEvent:t,target:n,transform:r,dispatch:s}){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:s}})}function dx(e,t,n){this.k=e,this.x=t,this.y=n}dx.prototype={constructor:dx,scale:function(e){return e===1?this:new dx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new dx(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 hZ=new dx(1,0,0);vEt.prototype=dx.prototype;function vEt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return hZ;return e.__zoom}function vre(e){e.stopImmediatePropagation()}function pP(e){e.preventDefault(),e.stopImmediatePropagation()}function Ber(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function Uer(){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 UUe(){return this.__zoom||hZ}function qer(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Ver(){return navigator.maxTouchPoints||"ontouchstart"in this}function Her(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function yEt(){var e=Ber,t=Uer,n=Her,r=qer,s=Ver,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=F9,u=cZ("start","zoom","end"),d,f,h,p=500,m=150,v=0,y=10;function b(D){D.property("__zoom",UUe).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",$).on("touchend.zoom touchcancel.zoom",z).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,q,H,V){var B=D.selection?D.selection():D;B.property("__zoom",UUe),D!==B?O(D,q,H,V):B.interrupt().each(function(){_(this,arguments).event(V).start().zoom(null,typeof q=="function"?q.apply(this,arguments):q).end()})},b.scaleBy=function(D,q,H,V){b.scaleTo(D,function(){var B=this.__zoom.k,W=typeof q=="function"?q.apply(this,arguments):q;return B*W},H,V)},b.scaleTo=function(D,q,H,V){b.transform(D,function(){var B=t.apply(this,arguments),W=this.__zoom,L=H==null?k(B):typeof H=="function"?H.apply(this,arguments):H,G=W.invert(L),M=typeof q=="function"?q.apply(this,arguments):q;return n(w(x(W,M),L,G),B,i)},H,V)},b.translateBy=function(D,q,H,V){b.transform(D,function(){return n(this.__zoom.translate(typeof q=="function"?q.apply(this,arguments):q,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,V)},b.translateTo=function(D,q,H,V,B){b.transform(D,function(){var W=t.apply(this,arguments),L=this.__zoom,G=V==null?k(W):typeof V=="function"?V.apply(this,arguments):V;return n(hZ.translate(G[0],G[1]).scale(L.k).translate(typeof q=="function"?-q.apply(this,arguments):-q,typeof H=="function"?-H.apply(this,arguments):-H),W,i)},V,B)};function x(D,q){return q=Math.max(a[0],Math.min(a[1],q)),q===D.k?D:new dx(q,D.x,D.y)}function w(D,q,H){var V=q[0]-H[0]*D.k,B=q[1]-H[1]*D.k;return V===D.x&&B===D.y?D:new dx(D.k,V,B)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function O(D,q,H,V){D.on("start.zoom",function(){_(this,arguments).event(V).start()}).on("interrupt.zoom end.zoom",function(){_(this,arguments).event(V).end()}).tween("zoom",function(){var B=this,W=arguments,L=_(B,W).event(V),G=t.apply(B,W),M=H==null?k(G):typeof H=="function"?H.apply(B,W):H,R=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),F=B.__zoom,U=typeof q=="function"?q.apply(B,W):q,Q=c(F.invert(M).concat(R/F.k),U.invert(M).concat(R/U.k));return function(te){if(te===1)te=U;else{var J=Q(te),ee=R/J[2];te=new dx(ee,M[0]-J[0]*ee,M[1]-J[1]*ee)}L.zoom(null,te)}})}function _(D,q,H){return!H&&D.__zooming||new T(D,q)}function T(D,q){this.that=D,this.args=q,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,q),this.taps=0}T.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,q){return this.mouse&&D!=="mouse"&&(this.mouse[1]=q.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=q.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=q.invert(this.touch1[0])),this.that.__zoom=q,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var q=Ah(this.that).datum();u.call(D,this.that,new zer(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),q)}};function E(D,...q){if(!e.apply(this,arguments))return;var H=_(this,q).event(D),V=this.__zoom,B=Math.max(a[0],Math.min(a[1],V.k*Math.pow(2,r.apply(this,arguments)))),W=yg(D);if(H.wheel)(H.mouse[0][0]!==W[0]||H.mouse[0][1]!==W[1])&&(H.mouse[1]=V.invert(H.mouse[0]=W)),clearTimeout(H.wheel);else{if(V.k===B)return;H.mouse=[W,V.invert(W)],U9(this),H.start()}pP(D),H.wheel=setTimeout(L,m),H.zoom("mouse",n(w(x(V,B),H.mouse[0],H.mouse[1]),H.extent,i));function L(){H.wheel=null,H.end()}}function N(D,...q){if(h||!e.apply(this,arguments))return;var H=D.currentTarget,V=_(this,q,!0).event(D),B=Ah(D.view).on("mousemove.zoom",M,!0).on("mouseup.zoom",R,!0),W=yg(D,H),L=D.clientX,G=D.clientY;tEt(D.view),vre(D),V.mouse=[W,this.__zoom.invert(W)],U9(this),V.start();function M(F){if(pP(F),!V.moved){var U=F.clientX-L,Q=F.clientY-G;V.moved=U*U+Q*Q>v}V.event(F).zoom("mouse",n(w(V.that.__zoom,V.mouse[0]=yg(F,H),V.mouse[1]),V.extent,i))}function R(F){B.on("mousemove.zoom mouseup.zoom",null),nEt(F.view,V.moved),pP(F),V.event(F).end()}}function I(D,...q){if(e.apply(this,arguments)){var H=this.__zoom,V=yg(D.changedTouches?D.changedTouches[0]:D,this),B=H.invert(V),W=H.k*(D.shiftKey?.5:2),L=n(w(x(H,W),V,B),t.apply(this,q),i);pP(D),l>0?Ah(this).transition().duration(l).call(O,L,V,D):Ah(this).call(b.transform,L,V,D)}}function A(D,...q){if(e.apply(this,arguments)){var H=D.touches,V=H.length,B=_(this,q,D.changedTouches.length===V).event(D),W,L,G,M;for(vre(D),L=0;L<V;++L)G=H[L],M=yg(G,this),M=[M,this.__zoom.invert(M),G.identifier],B.touch0?!B.touch1&&B.touch0[2]!==M[2]&&(B.touch1=M,B.taps=0):(B.touch0=M,W=!0,B.taps=1+!!d);d&&(d=clearTimeout(d)),W&&(B.taps<2&&(f=M[0],d=setTimeout(function(){d=null},p)),U9(this),B.start())}}function $(D,...q){if(this.__zooming){var H=_(this,q).event(D),V=D.changedTouches,B=V.length,W,L,G,M;for(pP(D),W=0;W<B;++W)L=V[W],G=yg(L,this),H.touch0&&H.touch0[2]===L.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===L.identifier&&(H.touch1[0]=G);if(L=H.that.__zoom,H.touch1){var R=H.touch0[0],F=H.touch0[1],U=H.touch1[0],Q=H.touch1[1],te=(te=U[0]-R[0])*te+(te=U[1]-R[1])*te,J=(J=Q[0]-F[0])*J+(J=Q[1]-F[1])*J;L=x(L,Math.sqrt(te/J)),G=[(R[0]+U[0])/2,(R[1]+U[1])/2],M=[(F[0]+Q[0])/2,(F[1]+Q[1])/2]}else if(H.touch0)G=H.touch0[0],M=H.touch0[1];else return;H.zoom("touch",n(w(L,G,M),H.extent,i))}}function z(D,...q){if(this.__zooming){var H=_(this,q).event(D),V=D.changedTouches,B=V.length,W,L;for(vre(D),h&&clearTimeout(h),h=setTimeout(function(){h=null},p),W=0;W<B;++W)L=V[W],H.touch0&&H.touch0[2]===L.identifier?delete H.touch0:H.touch1&&H.touch1[2]===L.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(L=yg(L,this),Math.hypot(f[0]-L[0],f[1]-L[1])<y)){var G=Ah(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:oz(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:oz(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:oz(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:oz([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const $y={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."},yD=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],bEt=["Enter"," ","Escape"],xEt={"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 _N;(function(e){e.Strict="strict",e.Loose="loose"})(_N||(_N={}));var TO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(TO||(TO={}));var bD;(function(e){e.Partial="partial",e.Full="full"})(bD||(bD={}));const wEt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Uw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Uw||(Uw={}));var xD;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(xD||(xD={}));var ar;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(ar||(ar={}));const qUe={[ar.Left]:ar.Right,[ar.Right]:ar.Left,[ar.Top]:ar.Bottom,[ar.Bottom]:ar.Top};function SEt(e){return e===null?null:e?"valid":"invalid"}const kEt=e=>"id"in e&&"source"in e&&"target"in e,Wer=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),s_e=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),ML=(e,t=[0,0])=>{const{width:n,height:r}=x0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},Zer=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):s_e(s)?s:t.nodeLookup.get(s.id));const l=i?XU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return pZ(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return mZ(n)},DL=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=pZ(n,XU(s)),r=!0)}),r?mZ(n):{x:0,y:0,width:0,height:0}},a_e=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...FL(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:h=!1}=u;if(i&&!f||h)continue;const p=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=wD(l,TN(u)),y=(p??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},Ger=(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 Qer(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&(t?.includeHiddenNodes||!s.hidden)&&(!r||r.has(s.id))&&n.set(s.id,s)}),n}async function Yer({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=Qer(e,i),c=DL(l),u=i_e(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function OEt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",$y.error005());else{const p=l.measured.width,m=l.measured.height;p&&m&&(f=[[c,u],[c+p,u+m]])}else l&&jN(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const h=jN(f)?kC(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",$y.error015()),{position:{x:h.x-c+(i.measured.width??0)*d[0],y:h.y-u+(i.measured.height??0)*d[1]},positionAbsolute:h}}async function Ker({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(h=>h.id)),i=[];for(const h of n){if(h.deletable===!1)continue;const p=a.has(h.id),m=!p&&h.parentId&&i.find(v=>v.id===h.parentId);(p||m)&&i.push(h)}const l=new Set(t.map(h=>h.id)),c=r.filter(h=>h.deletable!==!1),d=Ger(i,c);for(const h of c)l.has(h.id)&&!d.find(m=>m.id===h.id)&&d.push(h);if(!s)return{edges:d,nodes:i};const f=await s({nodes:i,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:i}:{edges:[],nodes:[]}:f}const EN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),kC=(e={x:0,y:0},t,n)=>({x:EN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:EN(e.y,t[0][1],t[1][1]-(n?.height??0))});function CEt(e,t,n){const{width:r,height:s}=x0(n),{x:a,y:i}=n.internals.positionAbsolute;return kC(e,[[a,i],[a+r,i+s]],t)}const VUe=(e,t,n)=>e<t?EN(Math.abs(e-t),1,t)/t:e>n?-EN(Math.abs(e-n),1,t)/t:0,_Et=(e,t,n=15,r=40)=>{const s=VUe(e.x,r,t.width-r)*n,a=VUe(e.y,r,t.height-r)*n;return[s,a]},pZ=(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)}),Qye=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),mZ=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),TN=(e,t=[0,0])=>{const{x:n,y:r}=s_e(e)?e.internals.positionAbsolute:ML(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}},XU=(e,t=[0,0])=>{const{x:n,y:r}=s_e(e)?e.internals.positionAbsolute:ML(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)}},EEt=(e,t)=>mZ(pZ(Qye(e),Qye(t))),wD=(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)},HUe=e=>Ng(e.width)&&Ng(e.height)&&Ng(e.x)&&Ng(e.y),Ng=e=>!isNaN(e)&&isFinite(e),Xer=(e,t)=>{},LL=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),FL=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?LL(l,i):l},JU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function FE(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 Jer(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=FE(e,n),s=FE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=FE(e.top??e.y??0,n),s=FE(e.bottom??e.y??0,n),a=FE(e.left??e.x??0,t),i=FE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function etr(e,t,n,r,s,a){const{x:i,y:l}=JU(e,[t,n,r]),{x:c,y:u}=JU({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const i_e=(e,t,n,r,s,a)=>{const i=Jer(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=EN(u,r,s),f=e.x+e.width/2,h=e.y+e.height/2,p=t/2-f*d,m=n/2-h*d,v=etr(e,p,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:p-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},SD=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function jN(e){return e!=null&&e!=="parent"}function x0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function TEt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function jEt(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function WUe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function ttr(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function ntr(e){return{...xEt,...e||{}}}function gM(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Ig(e),l=FL({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?LL(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const o_e=e=>({width:e.offsetWidth,height:e.offsetHeight}),NEt=e=>e?.getRootNode?.()||window?.document,rtr=["INPUT","SELECT","TEXTAREA"];function IEt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:rtr.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const AEt=e=>"clientX"in e,Ig=(e,t)=>{const n=AEt(e),r=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:s-(t?.top??0)}},ZUe=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...o_e(i)}})};function REt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function lz(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function GUe({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case ar.Left:return[t-lz(t-r,a),n];case ar.Right:return[t+lz(r-t,a),n];case ar.Top:return[t,n-lz(n-s,a)];case ar.Bottom:return[t,n+lz(s-n,a)]}}function l_e({sourceX:e,sourceY:t,sourcePosition:n=ar.Bottom,targetX:r,targetY:s,targetPosition:a=ar.Top,curvature:i=.25}){const[l,c]=GUe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=GUe({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,h,p,m]=REt({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,h,p,m]}function PEt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function str({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function atr({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=pZ(XU(e),XU(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return wD(i,mZ(a))>0}const itr=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,otr=(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)),ltr=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||itr;let s;return kEt(e)?s={...e}:s={...e,id:r(e)},otr(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function $Et({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=PEt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const QUe={[ar.Left]:{x:-1,y:0},[ar.Right]:{x:1,y:0},[ar.Top]:{x:0,y:-1},[ar.Bottom]:{x:0,y:1}},ctr=({source:e,sourcePosition:t=ar.Bottom,target:n})=>t===ar.Left||t===ar.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},YUe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function utr({source:e,sourcePosition:t=ar.Bottom,target:n,targetPosition:r=ar.Top,center:s,offset:a,stepPosition:i}){const l=QUe[t],c=QUe[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=ctr({source:u,sourcePosition:t,target:d}),h=f.x!==0?"x":"y",p=f[h];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,w,k]=PEt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[h]*c[h]===-1){h==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[h]===p?m=h==="x"?E:N:m=h==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(h==="x"?m=l.x===p?N:E:m=l.y===p?E:N,t===r){const D=Math.abs(e[h]-n[h]);if(D<=a){const q=Math.min(a-1,a-D);l[h]===p?b[h]=(u[h]>e[h]?-1:1)*q:x[h]=(d[h]>n[h]?-1:1)*q}}if(t!==r){const D=h==="x"?"y":"x",q=l[h]===c[D],H=u[D]>d[D],V=u[D]<d[D];(l[h]===1&&(!q&&H||q&&V)||l[h]!==1&&(!q&&V||q&&H))&&(m=h==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},$=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),z=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));$>=z?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const O={x:u.x+b.x,y:u.y+b.y},_={x:d.x+x.x,y:d.y+x.y};return[[e,...O.x!==m[0].x||O.y!==m[0].y?[O]:[],...m,..._.x!==m[m.length-1].x||_.y!==m[m.length-1].y?[_]:[],n],v,y,w,k]}function dtr(e,t,n,r){const s=Math.min(YUe(e,t)/2,YUe(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function Yye({sourceX:e,sourceY:t,sourcePosition:n=ar.Bottom,targetX:r,targetY:s,targetPosition:a=ar.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,h,p,m,v]=utr({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=dtr(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,h,p,m,v]}function KUe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function ftr(e){const{sourceNode:t,targetNode:n}=e;if(!KUe(t)||!KUe(n))return null;const r=t.internals.handleBounds||XUe(t.handles),s=n.internals.handleBounds||XUe(n.handles),a=JUe(r?.source??[],e.sourceHandle),i=JUe(e.connectionMode===_N.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",$y.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||ar.Bottom,c=i?.position||ar.Top,u=OC(t,a,l),d=OC(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function XUe(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 OC(e,t,n=ar.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??x0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case ar.Top:return{x:s+i/2,y:a};case ar.Right:return{x:s+i,y:a+l/2};case ar.Bottom:return{x:s+i/2,y:a+l};case ar.Left:return{x:s,y:a+l/2}}}function JUe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Kye(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function htr(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=Kye(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const MEt=1e3,ptr=10,c_e={nodeOrigin:[0,0],nodeExtent:yD,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},mtr={...c_e,checkEquality:!0};function u_e(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function gtr(e,t,n){const r=u_e(c_e,n);for(const s of e.values())if(s.parentId)f_e(s,e,t,r);else{const a=ML(s,r.nodeOrigin),i=jN(s.extent)?s.extent:r.nodeExtent,l=kC(a,i,x0(s));s.internals.positionAbsolute=l}}function vtr(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function d_e(e){return e==="manual"}function Xye(e,t,n,r={}){const s=u_e(mtr,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!d_e(s.zIndexMode)?MEt:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const h=ML(d,s.nodeOrigin),p=jN(d.extent)?d.extent:s.nodeExtent,m=kC(h,p,x0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:vtr(d,f),z:DEt(d,l,s.zIndexMode),userNode:d}},t.set(d.id,f)}(f.measured===void 0||f.measured.width===void 0||f.measured.height===void 0)&&!f.hidden&&(c=!1),d.parentId&&f_e(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function ytr(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 f_e(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=u_e(c_e,r),u=e.parentId,d=t.get(u);if(!d){console.warn(`Parent node ${u} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}ytr(e,n),s&&!d.parentId&&d.internals.rootParentIndex===void 0&&c==="auto"&&(d.internals.rootParentIndex=++s.i,d.internals.z=d.internals.z+s.i*ptr),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!d_e(c)?MEt:0,{x:h,y:p,z:m}=btr(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=h!==v.x||p!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:h,y:p}:v,z:m}})}function DEt(e,t,n){const r=Ng(e.zIndex)?e.zIndex:0;return d_e(n)?r:r+(e.selected?t:0)}function btr(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=x0(e),u=ML(e,n),d=jN(e.extent)?kC(u,e.extent,c):u;let f=kC({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=CEt(f,c,t));const h=DEt(e,s,a),p=t.internals.z??0;return{x:f.x,y:f.y,z:p>=h?p+1:h}}function h_e(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??TN(l),u=EEt(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=x0(l),f=l.origin??r,h=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,p=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(h>0||p>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-h+y,y:l.position.y-p+b}}),n.get(c)?.forEach(x=>{e.some(w=>w.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+h,y:x.position.y+p}})})),(d.width<i.width||d.height<i.height||h||p)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(h?f[0]*h-y:0),height:v+(p?f[1]*p-b:0)}})}),s}function xtr(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),h=[];for(const p of e.values()){const m=t.get(p.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=o_e(p.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||p.force))){const x=p.nodeElement.getBoundingClientRect(),w=jN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=CEt(k,v,t.get(m.parentId)):w&&(k=kC(k,w,v));const O={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:ZUe("source",p.nodeElement,x,f,m.id),target:ZUe("target",p.nodeElement,x,f,m.id)}}};t.set(m.id,O),m.parentId&&f_e(O,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&h.push({id:m.id,parentId:m.parentId,rect:TN(O,s)}))}}if(h.length>0){const p=h_e(h,t,n,s);u.push(...p)}return{changes:u,updatedInternals:c}}async function wtr({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function eqe(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function LEt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;eqe("source",c,d,e,s,i),eqe("target",c,u,e,a,l),t.set(r.id,r)}}function FEt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:FEt(n,t):!1}function tqe(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 Str(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!FEt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function yre({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function ktr({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=LL(a,t);return{x:i.x-a.x,y:i.y-a.y}}function Otr({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,h=null,p=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:w,domNode:k,isSelectable:O,nodeId:_,nodeClickDistance:T=0}){h=Ah(k);function E({x:$,y:z}){const{nodeLookup:D,nodeExtent:q,snapGrid:H,snapToGrid:V,nodeOrigin:B,onNodeDrag:W,onSelectionDrag:L,onError:G,updateNodePositions:M}=t();a={x:$,y:z};let R=!1;const F=l.size>1,U=F&&q?Qye(DL(l)):null,Q=F&&V?ktr({dragItems:l,snapGrid:H,x:$,y:z}):null;for(const[te,J]of l){if(!D.has(te))continue;let ee={x:$-J.distance.x,y:z-J.distance.y};V&&(ee=Q?{x:Math.round(ee.x+Q.x),y:Math.round(ee.y+Q.y)}:LL(ee,H));let re=null;if(F&&q&&!J.extent&&U){const{positionAbsolute:ne}=J.internals,se=ne.x-U.x+q[0][0],ce=ne.x+J.measured.width-U.x2+q[1][0],le=ne.y-U.y+q[0][1],ve=ne.y+J.measured.height-U.y2+q[1][1];re=[[se,le],[ce,ve]]}const{position:ae,positionAbsolute:X}=OEt({nodeId:te,nextPosition:ee,nodeLookup:D,nodeExtent:re||q,nodeOrigin:B,onError:G});R=R||J.position.x!==ae.x||J.position.y!==ae.y,J.position=ae,J.internals.positionAbsolute=X}if(m=m||R,!!R&&(M(l,!0),v&&(r||W||!_&&L))){const[te,J]=yre({nodeId:_,dragItems:l,nodeLookup:D});r?.(v,l,te,J),W?.(v,te,J),_||L?.(v,J)}}async function N(){if(!d)return;const{transform:$,panBy:z,autoPanSpeed:D,autoPanOnNodeDrag:q}=t();if(!q){c=!1,cancelAnimationFrame(i);return}const[H,V]=_Et(u,d,D);(H!==0||V!==0)&&(a.x=(a.x??0)-H/$[2],a.y=(a.y??0)-V/$[2],await z({x:H,y:V})&&E(a)),i=requestAnimationFrame(N)}function I($){const{nodeLookup:z,multiSelectionActive:D,nodesDraggable:q,transform:H,snapGrid:V,snapToGrid:B,selectNodesOnDrag:W,onNodeDragStart:L,onSelectionDragStart:G,unselectNodesAndEdges:M}=t();f=!0,(!W||!O)&&!D&&_&&(z.get(_)?.selected||M()),O&&W&&_&&e?.(_);const R=gM($.sourceEvent,{transform:H,snapGrid:V,snapToGrid:B,containerBounds:d});if(a=R,l=Str(z,q,R,_),l.size>0&&(n||L||!_&&G)){const[F,U]=yre({nodeId:_,dragItems:l,nodeLookup:z});n?.($.sourceEvent,l,F,U),L?.($.sourceEvent,F,U),_||G?.($.sourceEvent,U)}}const A=rEt().clickDistance(T).on("start",$=>{const{domNode:z,nodeDragThreshold:D,transform:q,snapGrid:H,snapToGrid:V}=t();d=z?.getBoundingClientRect()||null,p=!1,m=!1,v=$.sourceEvent,D===0&&I($),a=gM($.sourceEvent,{transform:q,snapGrid:H,snapToGrid:V,containerBounds:d}),u=Ig($.sourceEvent,d)}).on("drag",$=>{const{autoPanOnNodeDrag:z,transform:D,snapGrid:q,snapToGrid:H,nodeDragThreshold:V,nodeLookup:B}=t(),W=gM($.sourceEvent,{transform:D,snapGrid:q,snapToGrid:H,containerBounds:d});if(v=$.sourceEvent,($.sourceEvent.type==="touchmove"&&$.sourceEvent.touches.length>1||_&&!B.has(_))&&(p=!0),!p){if(!c&&z&&f&&(c=!0,N()),!f){const L=Ig($.sourceEvent,d),G=L.x-u.x,M=L.y-u.y;Math.sqrt(G*G+M*M)>V&&I($)}(a.x!==W.xSnapped||a.y!==W.ySnapped)&&l&&f&&(u=Ig($.sourceEvent,d),E(W))}}).on("end",$=>{if(!(!f||p)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:z,updateNodePositions:D,onNodeDragStop:q,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||q||!_&&H){const[V,B]=yre({nodeId:_,dragItems:l,nodeLookup:z,dragging:!1});s?.($.sourceEvent,l,V,B),q?.($.sourceEvent,V,B),_||H?.($.sourceEvent,B)}}}).filter($=>{const z=$.target;return!$.button&&(!x||!tqe(z,`.${x}`,k))&&(!w||tqe(z,w,k))});h.call(A)}function b(){h?.on(".drag",null)}return{update:y,destroy:b}}function Ctr(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())wD(s,TN(a))>0&&r.push(a);return r}const _tr=250;function Etr(e,t,n,r){let s=[],a=1/0;const i=Ctr(e,n,t+_tr);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=OC(l,u,u.position,!0),h=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));h>t||(h<a?(s=[{...u,x:d,y:f}],a=h):h===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function zEt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...OC(i,c,c.position,!0)}:c}function BEt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function Ttr(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const UEt=()=>!0;function jtr(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:h,cancelConnection:p,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=UEt,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:O,autoPanSpeed:_,dragThreshold:T=1,handleDomNode:E}){const N=NEt(e.target);let I=0,A;const{x:$,y:z}=Ig(e),D=BEt(a,E),q=l?.getBoundingClientRect();let H=!1;if(!q||!D)return;const V=zEt(s,D,r,c,t);if(!V)return;let B=Ig(e,q),W=!1,L=null,G=!1,M=null;function R(){if(!d||!q)return;const[ae,X]=_Et(B,q,_);h({x:ae,y:X}),I=requestAnimationFrame(R)}const F={...V,nodeId:s,type:D,position:V.position},U=c.get(s);let te={inProgress:!0,isValid:null,from:OC(U,F,ar.Left,!0),fromHandle:F,fromPosition:F.position,fromNode:U,to:B,toHandle:null,toPosition:qUe[F.position],toNode:null,pointer:B};function J(){H=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}T===0&&J();function ee(ae){if(!H){const{x:ve,y:ye}=Ig(ae),Te=ve-$,Me=ye-z;if(!(Te*Te+Me*Me>T*T))return;J()}if(!O()||!F){re(ae);return}const X=k();B=Ig(ae,q),A=Etr(FL(B,X,!1,[1,1]),n,c,F),W||(R(),W=!0);const ne=qEt(ae,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});M=ne.handleDomNode,L=ne.connection,G=Ttr(!!A,ne.isValid);const se=c.get(s),ce=se?OC(se,F,ar.Left,!0):te.from,le={...te,from:ce,isValid:G,to:ne.toHandle&&G?JU({x:ne.toHandle.x,y:ne.toHandle.y},X):B,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:qUe[F.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:B};w(le),te=le}function re(ae){if(!("touches"in ae&&ae.touches.length>0)){if(H){(A||M)&&L&&G&&v?.(L);const{inProgress:X,...ne}=te,se={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(ae,se),a&&x?.(ae,se)}p(),cancelAnimationFrame(I),W=!1,G=!1,L=null,M=null,N.removeEventListener("mousemove",ee),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",ee),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",ee),N.addEventListener("mouseup",re),N.addEventListener("touchmove",ee),N.addEventListener("touchend",re)}function qEt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=UEt,nodeLookup:d}){const f=a==="target",h=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:p,y:m}=Ig(e),v=i.elementFromPoint(p,m),y=v?.classList.contains(`${l}-flow__handle`)?v:h,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=BEt(void 0,y),w=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),O=y.classList.contains("connectable"),_=y.classList.contains("connectableend");if(!w||!x)return b;const T={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=T;const N=O&&_&&(n===_N.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=N&&u(T),b.toHandle=zEt(w,x,k,d,n,!0)}return b}const Jye={onPointerDown:jtr,isValid:qEt};function Ntr({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Ah(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:h=!0,inversePan:p=!1}){const m=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const k=n(),O=w.sourceEvent.ctrlKey&&SD()?10:1,_=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,_*O);t.scaleTo(T)};let v=[0,0];const y=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])},b=w=>{const k=n();if(w.sourceEvent.type!=="mousemove"&&w.sourceEvent.type!=="touchmove"||!t)return;const O=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],_=[O[0]-v[0],O[1]-v[1]];v=O;const T=r()*Math.max(k[2],Math.log(k[2]))*(p?-1:1),E={x:k[0]-_[0]*T,y:k[1]-_[1]*T},N=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},N,l)},x=yEt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",h?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:yg}}const gZ=e=>({x:e.x,y:e.y,zoom:e.k}),bre=({x:e,y:t,zoom:n})=>hZ.translate(e,t).scale(n),WT=(e,t)=>e.target.closest(`.${t}`),VEt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Itr=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,xre=(e,t=0,n=Itr,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},HEt=e=>{const t=e.ctrlKey&&SD()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function Atr({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(WT(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=yg(d),b=HEt(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const h=d.deltaMode===1?20:1;let p=s===TO.Vertical?0:d.deltaX*h,m=s===TO.Horizontal?0:d.deltaY*h;!SD()&&d.shiftKey&&s!==TO.Vertical&&(p=d.deltaY*h,m=0),r.translateBy(n,-(p/f)*a,-(m/f)*a,{internal:!0});const v=gZ(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function Rtr({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=WT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function Ptr({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=gZ(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,r.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(r.sourceEvent,s)}}function $tr({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&VEt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,gZ(a.transform))}}function Mtr({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&VEt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=gZ(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function Dtr({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const h=e||t,p=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(WT(f,`${u}-flow__node`)||WT(f,`${u}-flow__edge`)))return!0;if(!r&&!h&&!s&&!a&&!n||i||d&&!m||WT(f,l)&&m||WT(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!h&&!s&&!p&&m||!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||m)&&v}}function Ltr({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=yEt().scaleExtent([t,n]).translateExtent(r),h=Ah(e).call(f);x({x:s.x,y:s.y,zoom:EN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const p=h.on("wheel.zoom"),m=h.on("dblclick.zoom");f.wheelDelta(HEt);function v(A,$){return h?new Promise(z=>{f?.interpolate($?.interpolate==="linear"?Cx:F9).transform(xre(h,$?.duration,$?.ease,()=>z(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:$,onPaneContextMenu:z,userSelectionActive:D,panOnScroll:q,panOnDrag:H,panOnScrollMode:V,panOnScrollSpeed:B,preventScrolling:W,zoomOnPinch:L,zoomOnScroll:G,zoomOnDoubleClick:M,zoomActivationKeyPressed:R,lib:F,onTransformChange:U,connectionInProgress:Q,paneClickDistance:te,selectionOnDrag:J}){D&&!u.isZoomingOrPanning&&b();const ee=q&&!R&&!D;f.clickDistance(J?1/0:!Ng(te)||te<0?0:te);const re=ee?Atr({zoomPanValues:u,noWheelClassName:A,d3Selection:h,d3Zoom:f,panOnScrollMode:V,panOnScrollSpeed:B,zoomOnPinch:L,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):Rtr({noWheelClassName:A,preventScrolling:W,d3ZoomHandler:p});if(h.on("wheel.zoom",re,{passive:!1}),!D){const X=Ptr({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const ne=$tr({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!z,onPanZoom:a,onTransformChange:U});f.on("zoom",ne);const se=Mtr({zoomPanValues:u,panOnDrag:H,panOnScroll:q,onPaneContextMenu:z,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const ae=Dtr({zoomActivationKeyPressed:R,panOnDrag:H,zoomOnScroll:G,panOnScroll:q,zoomOnDoubleClick:M,zoomOnPinch:L,userSelectionActive:D,noPanClassName:$,noWheelClassName:A,lib:F,connectionInProgress:Q});f.filter(ae),M?h.on("dblclick.zoom",m):h.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,$,z){const D=bre(A),q=f?.constrain()(D,$,z);return q&&await v(q),new Promise(H=>H(q))}async function w(A,$){const z=bre(A);return await v(z,$),new Promise(D=>D(z))}function k(A){if(h){const $=bre(A),z=h.property("__zoom");(z.k!==A.zoom||z.x!==A.x||z.y!==A.y)&&f?.transform(h,$,null,{sync:!0})}}function O(){const A=h?vEt(h.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,$){return h?new Promise(z=>{f?.interpolate($?.interpolate==="linear"?Cx:F9).scaleTo(xre(h,$?.duration,$?.ease,()=>z(!0)),A)}):Promise.resolve(!1)}function T(A,$){return h?new Promise(z=>{f?.interpolate($?.interpolate==="linear"?Cx:F9).scaleBy(xre(h,$?.duration,$?.ease,()=>z(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const $=!Ng(A)||A<0?0:A;f?.clickDistance($)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:O,scaleTo:_,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var NN;(function(e){e.Line="line",e.Handle="handle"})(NN||(NN={}));function Ftr({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function nqe(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function vw(e,t){return Math.max(0,t-e)}function yw(e,t){return Math.max(0,e-t)}function cz(e,t,n){return Math.max(0,t-e,e-n)}function rqe(e,t){return e?!t:t}function ztr(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,h=d&&f,{xSnapped:p,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:w,y:k,width:O,height:_,aspectRatio:T}=e;let E=Math.floor(d?p-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=O+(c?-E:E),A=_+(u?-N:N),$=-a[0]*O,z=-a[1]*_;let D=cz(I,v,y),q=cz(A,b,x);if(i){let B=0,W=0;c&&E<0?B=vw(w+E+$,i[0][0]):!c&&E>0&&(B=yw(w+I+$,i[1][0])),u&&N<0?W=vw(k+N+z,i[0][1]):!u&&N>0&&(W=yw(k+A+z,i[1][1])),D=Math.max(D,B),q=Math.max(q,W)}if(l){let B=0,W=0;c&&E>0?B=yw(w+E,l[0][0]):!c&&E<0&&(B=vw(w+I,l[1][0])),u&&N>0?W=yw(k+N,l[0][1]):!u&&N<0&&(W=vw(k+A,l[1][1])),D=Math.max(D,B),q=Math.max(q,W)}if(s){if(d){const B=cz(I/T,b,x)*T;if(D=Math.max(D,B),i){let W=0;!c&&!u||c&&!u&&h?W=yw(k+z+I/T,i[1][1])*T:W=vw(k+z+(c?E:-E)/T,i[0][1])*T,D=Math.max(D,W)}if(l){let W=0;!c&&!u||c&&!u&&h?W=vw(k+I/T,l[1][1])*T:W=yw(k+(c?E:-E)/T,l[0][1])*T,D=Math.max(D,W)}}if(f){const B=cz(A*T,v,y)/T;if(q=Math.max(q,B),i){let W=0;!c&&!u||u&&!c&&h?W=yw(w+A*T+$,i[1][0])/T:W=vw(w+(u?N:-N)*T+$,i[0][0])/T,q=Math.max(q,W)}if(l){let W=0;!c&&!u||u&&!c&&h?W=vw(w+A*T,l[1][0])/T:W=yw(w+(u?N:-N)*T,l[0][0])/T,q=Math.max(q,W)}}}N=N+(N<0?q:-q),E=E+(E<0?D:-D),s&&(h?I>A*T?N=(rqe(c,u)?-E:E)/T:E=(rqe(c,u)?-N:N)*T:d?(N=E/T,u=c):(E=N*T,c=u));const H=c?w+E:w,V=u?k+N:k;return{width:O+(c?-E:E),height:_+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+V}}const WEt={width:0,height:0,x:0,y:0},Btr={...WEt,pointerX:0,pointerY:0,aspectRatio:1};function Utr(e){return[[0,0],[e.measured.width,e.measured.height]]}function qtr(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function Vtr({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Ah(e);let i={controlDirection:nqe("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:h,onResizeStart:p,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...WEt},x={...Btr};i={boundaries:d,resizeDirection:h,keepAspectRatio:f,controlDirection:nqe(u)};let w,k=null,O=[],_,T,E,N=!1;const I=rEt().on("start",A=>{const{nodeLookup:$,transform:z,snapGrid:D,snapToGrid:q,nodeOrigin:H,paneDomNode:V}=n();if(w=$.get(t),!w)return;k=V?.getBoundingClientRect()??null;const{xSnapped:B,ySnapped:W}=gM(A.sourceEvent,{transform:z,snapGrid:D,snapToGrid:q,containerBounds:k});b={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},x={...b,pointerX:B,pointerY:W,aspectRatio:b.width/b.height},_=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(_=$.get(w.parentId),T=_&&w.extent==="parent"?Utr(_):void 0),O=[],E=void 0;for(const[L,G]of $)if(G.parentId===t&&(O.push({id:L,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const M=qtr(G,w,G.origin??H);E?E=[[Math.min(M[0][0],E[0][0]),Math.min(M[0][1],E[0][1])],[Math.max(M[1][0],E[1][0]),Math.max(M[1][1],E[1][1])]]:E=M}p?.(A,{...b})}).on("drag",A=>{const{transform:$,snapGrid:z,snapToGrid:D,nodeOrigin:q}=n(),H=gM(A.sourceEvent,{transform:$,snapGrid:z,snapToGrid:D,containerBounds:k}),V=[];if(!w)return;const{x:B,y:W,width:L,height:G}=b,M={},R=w.origin??q,{width:F,height:U,x:Q,y:te}=ztr(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,R,T,E),J=F!==L,ee=U!==G,re=Q!==B&&J,ae=te!==W&ⅇif(!re&&!ae&&!J&&!ee)return;if((re||ae||R[0]===1||R[1]===1)&&(M.x=re?Q:b.x,M.y=ae?te:b.y,b.x=M.x,b.y=M.y,O.length>0)){const ce=Q-B,le=te-W;for(const ve of O)ve.position={x:ve.position.x-ce+R[0]*(F-L),y:ve.position.y-le+R[1]*(U-G)},V.push(ve)}if((J||ee)&&(M.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?F:b.width,M.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?U:b.height,b.width=M.width,b.height=M.height),_&&w.expandParent){const ce=R[0]*(M.width??0);M.x&&M.x<ce&&(b.x=ce,x.x=x.x-(M.x-ce));const le=R[1]*(M.height??0);M.y&&M.y<le&&(b.y=le,x.y=x.y-(M.y-le))}const X=Ftr({width:b.width,prevWidth:L,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ne={...b,direction:X};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(M,V))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const Htr={},sqe=e=>{let t;const n=new Set,r=(d,f)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=f??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(m=>m(t,p))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(Htr?"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()}},u=t=e(r,s,c);return c},Wtr=e=>e?sqe(e):sqe,{useDebugValue:Ztr}=ze,{useSyncExternalStoreWithSelector:Gtr}=qRn,Qtr=e=>e;function ZEt(e,t=Qtr,n){const r=Gtr(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Ztr(r),r}const aqe=(e,t)=>{const n=Wtr(e),r=(s,a=t)=>ZEt(n,s,a);return Object.assign(r,n),r},Ytr=(e,t)=>e?aqe(e,t):aqe;function io(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,s]of e)if(!Object.is(s,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 vZ=g.createContext(null),Ktr=vZ.Provider,GEt=$y.error001();function Zs(e,t){const n=g.useContext(vZ);if(n===null)throw new Error(GEt);return ZEt(n,e,t)}function To(){const e=g.useContext(vZ);if(e===null)throw new Error(GEt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const iqe={display:"none"},Xtr={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},QEt="react-flow__node-desc",YEt="react-flow__edge-desc",Jtr="react-flow__aria-live",enr=e=>e.ariaLiveMessage,tnr=e=>e.ariaLabelConfig;function nnr({rfId:e}){const t=Zs(enr);return o.jsx("div",{id:`${Jtr}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:Xtr,children:t})}function rnr({rfId:e,disableKeyboardA11y:t}){const n=Zs(tnr);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${QEt}-${e}`,style:iqe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${YEt}-${e}`,style:iqe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(nnr,{rfId:e})]})}const zL=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Gl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});zL.displayName="Panel";function snr({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(zL,{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:o.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const anr=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}},uz=e=>e.id;function inr(e,t){return io(e.selectedNodes.map(uz),t.selectedNodes.map(uz))&&io(e.selectedEdges.map(uz),t.selectedEdges.map(uz))}function onr({onSelectionChange:e}){const t=To(),{selectedNodes:n,selectedEdges:r}=Zs(anr,inr);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const lnr=e=>!!e.onSelectionChangeHandlers;function cnr({onSelectionChange:e}){const t=Zs(lnr);return e||t?o.jsx(onr,{onSelectionChange:e}):null}const ebe=typeof window<"u"?g.useLayoutEffect:g.useEffect,KEt=[0,0],unr={x:0,y:0,zoom:1},dnr=["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"],oqe=[...dnr,"rfId"],fnr=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}),lqe={translateExtent:yD,nodeOrigin:KEt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function hnr(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Zs(fnr,io),u=To();ebe(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=lqe,l()}),[]);const d=g.useRef(lqe);return ebe(()=>{for(const f of oqe){const h=e[f],p=d.current[f];h!==p&&(typeof e[f]>"u"||(f==="nodes"?t(h):f==="edges"?n(h):f==="minZoom"?r(h):f==="maxZoom"?s(h):f==="translateExtent"?a(h):f==="nodeExtent"?i(h):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:ntr(h)}):f==="fitView"?u.setState({fitViewQueued:h}):f==="fitViewOptions"?u.setState({fitViewOptions:h}):u.setState({[f]:h})))}d.current=e},oqe.map(f=>e[f])),null}function cqe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function pnr(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=cqe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:cqe()?.matches?"dark":"light"}const uqe=typeof document<"u"?document:null;function kD(e=null,t={target:uqe,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
|
|
234
|
+
`:r=="r"?"\r":r=="t"?" ":"\\")}eq(t){return this.search==t.search&&this.replace==t.replace&&this.caseSensitive==t.caseSensitive&&this.regexp==t.regexp&&this.wholeWord==t.wholeWord&&this.test==t.test}create(){return this.regexp?new pQn(this):new dQn(this)}getCursor(t,n=0,r){let s=t.doc?t:ps.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?kT(this,s,n,r):ST(this,s,n,r)}}class C_t{constructor(t){this.spec=t}}function cQn(e,t,n){return(r,s,a,i)=>{if(n&&!n(r,s,a,i))return!1;let l=r>=i&&s<=i+a.length?a.slice(r-i,s-i):t.doc.sliceString(r,s);return e(l,t,r,s)}}function ST(e,t,n,r){let s;return e.wholeWord&&(s=uQn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=cQn(e.test,t,s)),new Zx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function uQn(e,t){return(n,r,s,a)=>((a>n||a+s.length<r)&&(a=Math.max(0,n-2),s=e.sliceString(a,Math.min(e.length,r+2))),(t(zU(s,n-a))!=wo.Word||t(BU(s,n-a))!=wo.Word)&&(t(BU(s,r-a))!=wo.Word||t(zU(s,r-a))!=wo.Word))}class dQn extends C_t{constructor(t){super(t)}nextMatch(t,n,r){let s=ST(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=ST(this.spec,t,0,a).nextOverlapping()}return s.done||s.value.from==n&&s.value.to==r?null:s.value}prevMatchInRange(t,n,r){for(let s=r;;){let a=Math.max(n,s-1e4-this.spec.unquoted.length),i=ST(this.spec,t,a,s),l=null;for(;!i.nextOverlapping().done;)l=i.value;if(l)return l;if(a==n)return null;s-=1e4}}prevMatch(t,n,r){let s=this.prevMatchInRange(t,0,n);return s||(s=this.prevMatchInRange(t,Math.max(0,r-this.spec.unquoted.length),t.doc.length)),s&&(s.from!=n||s.to!=r)?s:null}getReplacement(t){return this.spec.unquote(this.spec.replace)}matchAll(t,n){let r=ST(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=ST(this.spec,t,Math.max(0,n-this.spec.unquoted.length),Math.min(r+this.spec.unquoted.length,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}function fQn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function kT(e,t,n,r){let s;return e.wholeWord&&(s=hQn(t.charCategorizer(t.selection.main.head))),e.test&&(s=fQn(e.test,t,s)),new S_t(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function zU(e,t){return e.slice(Nc(e,t,!1),t)}function BU(e,t){return e.slice(t,Nc(e,t))}function hQn(e){return(t,n,r)=>!r[0].length||(e(zU(r.input,r.index))!=wo.Word||e(BU(r.input,r.index))!=wo.Word)&&(e(BU(r.input,r.index+r[0].length))!=wo.Word||e(zU(r.input,r.index+r[0].length))!=wo.Word)}class pQn extends C_t{nextMatch(t,n,r){let s=kT(this.spec,t,r,t.doc.length).next();return s.done&&(s=kT(this.spec,t,0,n).next()),s.done?null:s.value}prevMatchInRange(t,n,r){for(let s=1;;s++){let a=Math.max(n,r-s*1e4),i=kT(this.spec,t,a,r),l=null;for(;!i.next().done;)l=i.value;if(l&&(a==n||l.from>a+10))return l;if(a==n)return null}}prevMatch(t,n,r){return this.prevMatchInRange(t,0,n)||this.prevMatchInRange(t,r,t.doc.length)}getReplacement(t){return this.spec.unquote(this.spec.replace).replace(/\$([$&]|\d+)/g,(n,r)=>{if(r=="&")return t.match[0];if(r=="$")return"$";for(let s=r.length;s>0;s--){let a=+r.slice(0,s);if(a>0&&a<t.match.length)return t.match[a]+r.slice(s)}return n})}matchAll(t,n){let r=kT(this.spec,t,0,t.doc.length),s=[];for(;!r.next().done;){if(s.length>=n)return null;s.push(r.value)}return s}highlight(t,n,r,s){let a=kT(this.spec,t,Math.max(0,n-250),Math.min(r+250,t.doc.length));for(;!a.next().done;)s(a.value.from,a.value.to)}}const dD=pr.define(),HCe=pr.define(),hS=wl.define({create(e){return new gne(Fye(e).create(),null)},update(e,t){for(let n of t.effects)n.is(dD)?e=new gne(n.value.create(),e.panel):n.is(HCe)&&(e=new gne(e.query,n.value?WCe:null));return e},provide:e=>tD.from(e,t=>t.panel)});class gne{constructor(t,n){this.query=t,this.panel=n}}const mQn=jn.mark({class:"cm-searchMatch"}),gQn=jn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),vQn=_o.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(hS))}update(e){let t=e.state.field(hS);(t!=e.startState.field(hS)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return jn.none;let{view:n}=this,r=new nd;for(let s=0,a=n.visibleRanges,i=a.length;s<i;s++){let{from:l,to:c}=a[s];for(;s<i-1&&c>a[s+1].from-500;)c=a[++s].to;e.highlight(n.state,l,c,(u,d)=>{let f=n.state.selection.ranges.some(h=>h.from==u&&h.to==d);r.add(u,d,f?gQn:mQn)})}return r.finish()}},{decorations:e=>e.decorations});function RL(e){return t=>{let n=t.state.field(hS,!1);return n&&n.query.spec.valid?e(t,n):T_t(t)}}const UU=RL((e,{query:t})=>{let{to:n}=e.state.selection.main,r=t.nextMatch(e.state,n,n);if(!r)return!1;let s=St.single(r.from,r.to),a=e.state.facet(KI);return e.dispatch({selection:s,effects:[ZCe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),E_t(e),!0}),qU=RL((e,{query:t})=>{let{state:n}=e,{from:r}=n.selection.main,s=t.prevMatch(n,r,r);if(!s)return!1;let a=St.single(s.from,s.to),i=e.state.facet(KI);return e.dispatch({selection:a,effects:[ZCe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),E_t(e),!0}),yQn=RL((e,{query:t})=>{let n=t.matchAll(e.state,1e3);return!n||!n.length?!1:(e.dispatch({selection:St.create(n.map(r=>St.range(r.from,r.to))),userEvent:"select.search.matches"}),!0)}),bQn=({state:e,dispatch:t})=>{let n=e.selection;if(n.ranges.length>1||n.main.empty)return!1;let{from:r,to:s}=n.main,a=[],i=0;for(let l=new Zx(e.doc,e.sliceDoc(r,s));!l.next().done;){if(a.length>1e3)return!1;l.value.from==r&&(i=a.length),a.push(St.range(l.value.from,l.value.to))}return t(e.update({selection:St.create(a,i),userEvent:"select.search.matches"})),!0},vBe=RL((e,{query:t})=>{let{state:n}=e,{from:r,to:s}=n.selection.main;if(n.readOnly)return!1;let a=t.nextMatch(n,r,r);if(!a)return!1;let i=a,l=[],c,u,d=[];i.precise?i.from==r&&i.to==s&&(u=n.toText(t.getReplacement(i)),l.push({from:i.from,to:i.to,insert:u}),i=t.nextMatch(n,i.from,i.to),d.push(Rt.announce.of(n.phrase("replaced match on line $",n.doc.lineAt(r).number)+"."))):i=t.nextMatch(n,i.from,i.to);let f=e.state.changes(l);return i&&(c=St.single(i.from,i.to).map(f),d.push(ZCe(e,i)),d.push(n.facet(KI).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),xQn=RL((e,{query:t})=>{if(e.state.readOnly)return!1;let n=[];for(let s of t.matchAll(e.state,1e9)){let{from:a,to:i,precise:l}=s;l&&n.push({from:a,to:i,insert:t.getReplacement(s)})}if(!n.length)return!1;let r=e.state.phrase("replaced $ matches",n.length)+".";return e.dispatch({changes:n,effects:Rt.announce.of(r),userEvent:"input.replace.all"}),!0});function WCe(e){return e.state.facet(KI).createPanel(e)}function Fye(e,t){var n,r,s,a,i;let l=e.selection.main,c=l.empty||l.to>l.from+100?"":e.sliceDoc(l.from,l.to);if(t&&!c)return t;let u=e.facet(KI);return new O_t({search:((n=t?.literal)!==null&&n!==void 0?n:u.literal)?c:c.replace(/\n/g,"\\n"),caseSensitive:(r=t?.caseSensitive)!==null&&r!==void 0?r:u.caseSensitive,literal:(s=t?.literal)!==null&&s!==void 0?s:u.literal,regexp:(a=t?.regexp)!==null&&a!==void 0?a:u.regexp,wholeWord:(i=t?.wholeWord)!==null&&i!==void 0?i:u.wholeWord})}function __t(e){let t=lCe(e,WCe);return t&&t.dom.querySelector("[main-field]")}function E_t(e){let t=__t(e);t&&t==e.root.activeElement&&t.select()}const T_t=e=>{let t=e.state.field(hS,!1);if(t&&t.panel){let n=__t(e);if(n&&n!=e.root.activeElement){let r=Fye(e.state,t.query.spec);r.valid&&e.dispatch({effects:dD.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[HCe.of(!0),t?dD.of(Fye(e.state,t.query.spec)):pr.appendConfig.of(OQn)]});return!0},j_t=e=>{let t=e.state.field(hS,!1);if(!t||!t.panel)return!1;let n=lCe(e,WCe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:HCe.of(!1)}),!0},wQn=[{key:"Mod-f",run:T_t,scope:"editor search-panel"},{key:"F3",run:UU,shift:qU,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:UU,shift:qU,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:j_t,scope:"editor search-panel"},{key:"Mod-Shift-l",run:bQn},{key:"Mod-Alt-g",run:KGn},{key:"Mod-d",run:lQn,preventDefault:!0}];class SQn{constructor(t){this.view=t;let n=this.query=t.state.field(hS).query.spec;this.commit=this.commit.bind(this),this.searchField=pi("input",{value:n.search,placeholder:vh(t,"Find"),"aria-label":vh(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=pi("input",{value:n.replace,placeholder:vh(t,"Replace"),"aria-label":vh(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=pi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=pi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=pi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return pi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=pi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>UU(t),[vh(t,"next")]),r("prev",()=>qU(t),[vh(t,"previous")]),r("select",()=>yQn(t),[vh(t,"all")]),pi("label",null,[this.caseField,vh(t,"match case")]),pi("label",null,[this.reField,vh(t,"regexp")]),pi("label",null,[this.wordField,vh(t,"by word")]),...t.state.readOnly?[]:[pi("br"),this.replaceField,r("replace",()=>vBe(t),[vh(t,"replace")]),r("replaceAll",()=>xQn(t),[vh(t,"replace all")])],pi("button",{name:"close",onclick:()=>j_t(t),"aria-label":vh(t,"close"),type:"button"},["×"])])}commit(){let t=new O_t({search:this.searchField.value,caseSensitive:this.caseField.checked,regexp:this.reField.checked,wholeWord:this.wordField.checked,replace:this.replaceField.value});t.eq(this.query)||(this.query=t,this.view.dispatch({effects:dD.of(t)}))}keydown(t){qBn(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?qU:UU)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),vBe(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(dD)&&!r.value.eq(this.query)&&this.setQuery(r.value)}setQuery(t){this.query=t,this.searchField.value=t.search,this.replaceField.value=t.replace,this.caseField.checked=t.caseSensitive,this.reField.checked=t.regexp,this.wordField.checked=t.wholeWord}mount(){this.searchField.select()}get pos(){return 80}get top(){return this.view.state.facet(KI).top}}function vh(e,t){return e.state.phrase(t)}const ez=30,tz=/[\s\.,:;?!]/;function ZCe(e,{from:t,to:n}){let r=e.state.doc.lineAt(t),s=e.state.doc.lineAt(n).to,a=Math.max(r.from,t-ez),i=Math.min(s,n+ez),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<ez;c++)if(!tz.test(l[c+1])&&tz.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-ez;c--)if(!tz.test(l[c-1])&&tz.test(l[c])){l=l.slice(0,c);break}}return Rt.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const kQn=Rt.baseTheme({".cm-panel.cm-search":{padding:"2px 6px 4px",position:"relative","& [name=close]":{position:"absolute",top:"0",right:"4px",backgroundColor:"inherit",border:"none",font:"inherit",padding:0,margin:0},"& input, & button, & label":{margin:".2em .6em .2em 0"},"& input[type=checkbox]":{marginRight:".2em"},"& label":{fontSize:"80%",whiteSpace:"pre"}},"&light .cm-searchMatch":{backgroundColor:"#ffff0054"},"&dark .cm-searchMatch":{backgroundColor:"#00ffff8a"},"&light .cm-searchMatch-selected":{backgroundColor:"#ff6a0054"},"&dark .cm-searchMatch-selected":{backgroundColor:"#ff00ff8a"}}),OQn=[hS,lp.low(vQn),kQn];class yBe{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Kk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(fD).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new nd,l=[],c=0;for(let d=0;;){let f=d==a.length?null:a[d];if(!f&&!l.length)break;let h,p;for(l.length?(h=c,p=l.reduce((v,y)=>Math.min(v,y.to),f&&f.from>h?f.from:1e8)):(h=f.from,p=f.to,l.push(f),d++);d<a.length;){let v=a[d];if(v.from==h&&(v.to>v.from||v.to==h))l.push(v),d++,p=Math.min(v.to,p);else{p=Math.min(v.from,p);break}}let m=DQn(l);if(l.some(v=>v.from==v.to||v.from==v.to-1&&r.doc.lineAt(v.from).to==v.from))i.add(h,h,jn.widget({widget:new RQn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(h,p,jn.mark({class:"cm-lintRange cm-lintRange-"+m+v,diagnostics:l.slice(),inclusiveEnd:l.some(y=>y.to>p)}))}c=p;for(let v=0;v<l.length;v++)l[v].to<=c&&l.splice(v--,1)}let u=i.finish();return new Kk(u,n,kN(u))}}function kN(e,t=null,n=0){let r=null;return e.between(n,1e9,(s,a,{spec:i})=>{if(!(t&&i.diagnostics.indexOf(t)<0))if(!r)r=new yBe(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new yBe(r.from,a,r.diagnostic)}}),r}function CQn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(fD).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(N_t))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function _Qn(e,t){return e.field(Fh,!1)?t:t.concat(pr.appendConfig.of(LQn))}const N_t=pr.define(),GCe=pr.define(),I_t=pr.define(),Fh=wl.define({create(){return new Kk(jn.none,null,null)},update(e,t){if(t.docChanged&&e.diagnostics.size){let n=e.diagnostics.map(t.changes),r=null,s=e.panel;if(e.selected){let a=t.changes.mapPos(e.selected.from,1);r=kN(n,e.selected.diagnostic,a)||kN(n,null,a)}!n.size&&s&&t.state.facet(fD).autoPanel&&(s=null),e=new Kk(n,s,r)}for(let n of t.effects)if(n.is(N_t)){let r=t.state.facet(fD).autoPanel?n.value.length?hD.open:null:e.panel;e=Kk.init(n.value,r,t.state)}else n.is(GCe)?e=new Kk(e.diagnostics,n.value?hD.open:null,e.selected):n.is(I_t)&&(e=new Kk(e.diagnostics,e.panel,n.value));return e},provide:e=>[tD.from(e,t=>t.panel),Rt.decorations.from(e,t=>t.diagnostics)]}),EQn=jn.mark({class:"cm-lintRange cm-lintRange-active"});function TQn(e,t,n){let{diagnostics:r}=e.state.field(Fh),s,a=-1,i=-1;r.between(t-(n<0?1:0),t+(n>0?1:0),(c,u,{spec:d})=>{if(t>=c&&t<=u&&(c==u||(t>c||n>0)&&(t<u||n<0)))return s=d.diagnostics,a=c,i=u,!1});let l=e.state.facet(fD).tooltipFilter;return s&&l&&(s=l(s,e.state)),s?{pos:a,end:i,above:e.state.doc.lineAt(a).to<i,create(){return{dom:jQn(e,s)}}}:null}function jQn(e,t){return pi("ul",{class:"cm-tooltip-lint"},t.map(n=>R_t(e,n,!1)))}const NQn=e=>{let t=e.state.field(Fh,!1);(!t||!t.panel)&&e.dispatch({effects:_Qn(e.state,[GCe.of(!0)])});let n=lCe(e,hD.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},bBe=e=>{let t=e.state.field(Fh,!1);return!t||!t.panel?!1:(e.dispatch({effects:GCe.of(!1)}),!0)},IQn=e=>{let t=e.state.field(Fh,!1);if(!t)return!1;let n=e.state.selection.main,r=t.diagnostics.iter(n.to+1);return!r.value&&(r=t.diagnostics.iter(0),!r.value||r.from==n.from&&r.to==n.to)?!1:(e.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0}),!0)},AQn=[{key:"Mod-Shift-m",run:NQn,preventDefault:!0},{key:"F8",run:IQn}],fD=On.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...Jy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:xBe,tooltipFilter:xBe,needsRefresh:(t,n)=>t?n?r=>t(r)||n(r):t:n,hideOn:(t,n)=>t?n?(r,s,a)=>t(r,s,a)||n(r,s,a):t:n,autoPanel:(t,n)=>t||n})}}});function xBe(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function A_t(e){let t=[];if(e)e:for(let{name:n}of e){for(let r=0;r<n.length;r++){let s=n[r];if(/[a-zA-Z]/.test(s)&&!t.some(a=>a.toLowerCase()==s.toLowerCase())){t.push(s);continue e}}t.push("")}return t}function R_t(e,t,n){var r;let s=n?A_t(t.actions):[];return pi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},pi("span",{class:"cm-diagnosticText"},t.renderMessage?t.renderMessage(e):t.message),(r=t.actions)===null||r===void 0?void 0:r.map((a,i)=>{let l=!1,c=p=>{if(p.preventDefault(),l)return;l=!0;let m=kN(e.state.field(Fh).diagnostics,t);m&&a.apply(e,m.from,m.to)},{name:u}=a,d=s[i]?u.indexOf(s[i]):-1,f=d<0?u:[u.slice(0,d),pi("u",u.slice(d,d+1)),u.slice(d+1)],h=a.markClass?" "+a.markClass:"";return pi("button",{type:"button",class:"cm-diagnosticAction"+h,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&pi("div",{class:"cm-diagnosticSource"},t.source))}class RQn extends cp{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return pi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class wBe{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=R_t(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class hD{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)bBe(this.view),this.view.focus();else if(s.keyCode==38||s.keyCode==33)this.moveSelection((this.selectedIndex-1+this.items.length)%this.items.length);else if(s.keyCode==40||s.keyCode==34)this.moveSelection((this.selectedIndex+1)%this.items.length);else if(s.keyCode==36)this.moveSelection(0);else if(s.keyCode==35)this.moveSelection(this.items.length-1);else if(s.keyCode==13)this.view.focus();else if(s.keyCode>=65&&s.keyCode<=90&&this.selectedIndex>=0){let{diagnostic:a}=this.items[this.selectedIndex],i=A_t(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=kN(this.view.state.field(Fh).diagnostics,a);c&&a.actions[l].apply(t,c.from,c.to)}}else return;s.preventDefault()},r=s=>{for(let a=0;a<this.items.length;a++)this.items[a].dom.contains(s.target)&&this.moveSelection(a)};this.list=pi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=pi("div",{class:"cm-panel-lint"},this.list,pi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>bBe(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Fh).selected;if(!t)return-1;for(let n=0;n<this.items.length;n++)if(this.items[n].diagnostic==t.diagnostic)return n;return-1}update(){let{diagnostics:t,selected:n}=this.view.state.field(Fh),r=0,s=!1,a=null,i=new Set;for(t.between(0,this.view.state.doc.length,(l,c,{spec:u})=>{for(let d of u.diagnostics){if(i.has(d))continue;i.add(d);let f=-1,h;for(let p=r;p<this.items.length;p++)if(this.items[p].diagnostic==d){f=p;break}f<0?(h=new wBe(this.view,d),this.items.splice(r,0,h),s=!0):(h=this.items[f],f>r&&(this.items.splice(r,f-r),s=!0)),n&&h.diagnostic==n.diagnostic?h.dom.hasAttribute("aria-selected")||(h.dom.setAttribute("aria-selected","true"),a=h):h.dom.hasAttribute("aria-selected")&&h.dom.removeAttribute("aria-selected"),r++}});r<this.items.length&&!(this.items.length==1&&this.items[0].diagnostic.from<0);)s=!0,this.items.pop();this.items.length==0&&(this.items.push(new wBe(this.view,{from:-1,to:-1,severity:"info",message:this.view.state.phrase("No diagnostics")})),s=!0),a?(this.list.setAttribute("aria-activedescendant",a.id),this.view.requestMeasure({key:this,read:()=>({sel:a.dom.getBoundingClientRect(),panel:this.list.getBoundingClientRect()}),write:({sel:l,panel:c})=>{let u=c.height/this.list.offsetHeight;l.top<c.top?this.list.scrollTop-=(c.top-l.top)/u:l.bottom>c.bottom&&(this.list.scrollTop+=(l.bottom-c.bottom)/u)}})):this.selectedIndex<0&&this.list.removeAttribute("aria-activedescendant"),s&&this.sync()}sync(){let t=this.list.firstChild;function n(){let r=t;t=r.nextSibling,r.remove()}for(let r of this.items)if(r.dom.parentNode==this.list){for(;t!=r.dom;)n();t=r.dom.nextSibling}else this.list.insertBefore(r.dom,t);for(;t;)n()}moveSelection(t){if(this.selectedIndex<0)return;let n=this.view.state.field(Fh),r=kN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:I_t.of(r)})}static open(t){return new hD(t)}}function PQn(e,t='viewBox="0 0 40 40"'){return`url('data:image/svg+xml,<svg xmlns="http://www.w3.org/2000/svg" ${t}>${encodeURIComponent(e)}</svg>')`}function nz(e){return PQn(`<path d="m0 2.5 l2 -1.5 l1 0 l2 1.5 l1 0" stroke="${e}" fill="none" stroke-width=".7"/>`,'width="6" height="3"')}const $Qn=Rt.baseTheme({".cm-diagnostic":{padding:"3px 6px 3px 8px",marginLeft:"-1px",display:"block",whiteSpace:"pre-wrap"},".cm-diagnostic-error":{borderLeft:"5px solid #d11"},".cm-diagnostic-warning":{borderLeft:"5px solid orange"},".cm-diagnostic-info":{borderLeft:"5px solid #999"},".cm-diagnostic-hint":{borderLeft:"5px solid #66d"},".cm-diagnosticAction":{font:"inherit",border:"none",padding:"2px 4px",backgroundColor:"#444",color:"white",borderRadius:"3px",marginLeft:"8px",cursor:"pointer"},".cm-diagnosticSource":{fontSize:"70%",opacity:.7},".cm-lintRange":{backgroundPosition:"left bottom",backgroundRepeat:"repeat-x",paddingBottom:"0.7px"},".cm-lintRange-error":{backgroundImage:nz("#d11")},".cm-lintRange-warning":{backgroundImage:nz("orange")},".cm-lintRange-info":{backgroundImage:nz("#999")},".cm-lintRange-hint":{backgroundImage:nz("#66d")},".cm-lintRange-active":{backgroundColor:"#ffdd9980"},".cm-tooltip-lint":{padding:0,margin:0},".cm-lintPoint":{position:"relative","&:after":{content:'""',position:"absolute",bottom:0,left:"-2px",borderLeft:"3px solid transparent",borderRight:"3px solid transparent",borderBottom:"4px solid #d11"}},".cm-lintPoint-warning":{"&:after":{borderBottomColor:"orange"}},".cm-lintPoint-info":{"&:after":{borderBottomColor:"#999"}},".cm-lintPoint-hint":{"&:after":{borderBottomColor:"#66d"}},".cm-panel.cm-panel-lint":{position:"relative","& ul":{maxHeight:"100px",overflowY:"auto","& [aria-selected]":{backgroundColor:"#ddd","& u":{textDecoration:"underline"}},"&:focus [aria-selected]":{background_fallback:"#bdf",backgroundColor:"Highlight",color_fallback:"white",color:"HighlightText"},"& u":{textDecoration:"none"},padding:0,margin:0},"& [name=close]":{position:"absolute",top:"0",right:"2px",background:"inherit",border:"none",font:"inherit",padding:0,margin:0}}});function MQn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function DQn(e){let t="hint",n=1;for(let r of e){let s=MQn(r.severity);s>n&&(n=s,t=r.severity)}return t}const LQn=[Fh,Rt.decorations.compute([Fh],e=>{let{selected:t,panel:n}=e.field(Fh);return!t||!n||t.from==t.to?jn.none:jn.set([EQn.range(t.from,t.to)])}),IUn(TQn,{hideOn:CQn}),$Qn];var SBe=function(t){t===void 0&&(t={});var n=t,r=n.crosshairCursor,s=r===void 0?!1:r,a=[];t.closeBracketsKeymap!==!1&&(a=a.concat(EVn)),t.defaultKeymap!==!1&&(a=a.concat(GGn)),t.searchKeymap!==!1&&(a=a.concat(wQn)),t.historyKeymap!==!1&&(a=a.concat(tGn)),t.foldKeymap!==!1&&(a=a.concat(fqn)),t.completionKeymap!==!1&&(a=a.concat(EOt)),t.lintKeymap!==!1&&(a=a.concat(AQn));var i=[];return t.lineNumbers!==!1&&i.push(Gkt()),t.highlightActiveLineGutter!==!1&&i.push(HUn()),t.highlightSpecialChars!==!1&&i.push(aUn()),t.history!==!1&&i.push(WZn()),t.foldGutter!==!1&&i.push(gqn()),t.drawSelection!==!1&&i.push(QBn()),t.dropCursor!==!1&&i.push(eUn()),t.allowMultipleSelections!==!1&&i.push(ps.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(sqn()),t.syntaxHighlighting!==!1&&i.push(T1(xqn,{fallback:!0})),t.bracketMatching!==!1&&i.push(Eqn()),t.closeBrackets!==!1&&i.push(kVn()),t.autocompletion!==!1&&i.push(_Ot()),t.rectangularSelection!==!1&&i.push(bUn()),s!==!1&&i.push(SUn()),t.highlightActiveLine!==!1&&i.push(dUn()),t.highlightSelectionMatches!==!1&&i.push(eQn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(ZI.of(" ".repeat(t.tabSize))),i.concat([WI.of(a.flat())]).filter(Boolean)};const FQn="#e5c07b",kBe="#e06c75",zQn="#56b6c2",BQn="#ffffff",D9="#abb2bf",zye="#7d8799",UQn="#61afef",qQn="#98c379",OBe="#d19a66",VQn="#c678dd",HQn="#21252b",CBe="#2c313a",_Be="#282c34",vne="#353a42",WQn="#3E4451",EBe="#528bff",ZQn=Rt.theme({"&":{color:D9,backgroundColor:_Be},".cm-content":{caretColor:EBe},".cm-cursor, .cm-dropCursor":{borderLeftColor:EBe},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:WQn},".cm-panels":{backgroundColor:HQn,color:D9},".cm-panels.cm-panels-top":{borderBottom:"2px solid black"},".cm-panels.cm-panels-bottom":{borderTop:"2px solid black"},".cm-searchMatch":{backgroundColor:"#72a1ff59",outline:"1px solid #457dff"},".cm-searchMatch.cm-searchMatch-selected":{backgroundColor:"#6199ff2f"},".cm-activeLine":{backgroundColor:"#6699ff0b"},".cm-selectionMatch":{backgroundColor:"#aafe661a"},"&.cm-focused .cm-matchingBracket, &.cm-focused .cm-nonmatchingBracket":{backgroundColor:"#bad0f847"},".cm-gutters":{backgroundColor:_Be,color:zye,border:"none"},".cm-activeLineGutter":{backgroundColor:CBe},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:vne},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:vne,borderBottomColor:vne},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:CBe,color:D9}}},{dark:!0}),GQn=rv.define([{tag:ue.keyword,color:VQn},{tag:[ue.name,ue.deleted,ue.character,ue.propertyName,ue.macroName],color:kBe},{tag:[ue.function(ue.variableName),ue.labelName],color:UQn},{tag:[ue.color,ue.constant(ue.name),ue.standard(ue.name)],color:OBe},{tag:[ue.definition(ue.name),ue.separator],color:D9},{tag:[ue.typeName,ue.className,ue.number,ue.changed,ue.annotation,ue.modifier,ue.self,ue.namespace],color:FQn},{tag:[ue.operator,ue.operatorKeyword,ue.url,ue.escape,ue.regexp,ue.link,ue.special(ue.string)],color:zQn},{tag:[ue.meta,ue.comment],color:zye},{tag:ue.strong,fontWeight:"bold"},{tag:ue.emphasis,fontStyle:"italic"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:ue.link,color:zye,textDecoration:"underline"},{tag:ue.heading,fontWeight:"bold",color:kBe},{tag:[ue.atom,ue.bool,ue.special(ue.variableName)],color:OBe},{tag:[ue.processingInstruction,ue.string,ue.inserted],color:qQn},{tag:ue.invalid,color:BQn}]),QQn=[ZQn,T1(GQn)];var YQn=Rt.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),KQn=function(t){t===void 0&&(t={});var n=t,r=n.indentWithTab,s=r===void 0?!0:r,a=n.editable,i=a===void 0?!0:a,l=n.readOnly,c=l===void 0?!1:l,u=n.theme,d=u===void 0?"light":u,f=n.placeholder,h=f===void 0?"":f,p=n.basicSetup,m=p===void 0?!0:p,v=[];switch(s&&v.unshift(WI.of([QGn])),m&&(typeof m=="boolean"?v.unshift(SBe()):v.unshift(SBe(m))),h&&v.unshift(mUn(h)),d){case"light":v.push(YQn);break;case"dark":v.push(QQn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(Rt.editable.of(!1)),c&&v.push(ps.readOnly.of(!0)),[...v]},XQn=e=>({line:e.state.doc.lineAt(e.state.selection.main.from),lineCount:e.state.doc.lines,lineBreak:e.state.lineBreak,length:e.state.doc.length,readOnly:e.state.readOnly,tabSize:e.state.tabSize,selection:e.state.selection,selectionAsSingle:e.state.selection.asSingle().main,ranges:e.state.selection.ranges,selectionCode:e.state.sliceDoc(e.state.selection.main.from,e.state.selection.main.to),selections:e.state.selection.ranges.map(t=>e.state.sliceDoc(t.from,t.to)),selectedText:e.state.selection.ranges.some(t=>!t.empty)});class JQn{constructor(t,n){this.timeLeftMS=void 0,this.timeoutMS=void 0,this.isCancelled=!1,this.isTimeExhausted=!1,this.callbacks=[],this.timeLeftMS=n,this.timeoutMS=n,this.callbacks.push(t)}tick(){if(!this.isCancelled&&!this.isTimeExhausted&&(this.timeLeftMS--,this.timeLeftMS<=0)){this.isTimeExhausted=!0;var t=this.callbacks.slice();this.callbacks.length=0,t.forEach(n=>{try{n()}catch(r){console.error("TimeoutLatch callback error:",r)}})}}cancel(){this.isCancelled=!0,this.callbacks.length=0}reset(){this.timeLeftMS=this.timeoutMS,this.isCancelled=!1,this.isTimeExhausted=!1}get isDone(){return this.isCancelled||this.isTimeExhausted}}class TBe{constructor(){this.interval=null,this.latches=new Set}add(t){this.latches.add(t),this.start()}remove(t){this.latches.delete(t),this.latches.size===0&&this.stop()}start(){this.interval===null&&(this.interval=setInterval(()=>{this.latches.forEach(t=>{t.tick(),t.isDone&&this.remove(t)})},1))}stop(){this.interval!==null&&(clearInterval(this.interval),this.interval=null)}}var yne=null,eYn=()=>typeof window>"u"?new TBe:(yne||(yne=new TBe),yne),tYn=Rt.theme({"& .cm-scroller":{height:"100% !important"}}),jBe=null,bne=null;function nYn(e,t,n,r,s,a){if(!e&&!t&&!n&&!r&&!s&&!a)return null;var i=JSON.stringify({height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a});return i===jBe||(jBe=i,bne=Rt.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),bne}var NBe=Xy.define(),rYn=200,sYn=[];function aYn(e){var t=e.value,n=e.selection,r=e.onChange,s=e.onStatistics,a=e.onCreateEditor,i=e.onUpdate,l=e.extensions,c=l===void 0?sYn:l,u=e.autoFocus,d=e.theme,f=d===void 0?"light":d,h=e.height,p=h===void 0?null:h,m=e.minHeight,v=m===void 0?null:m,y=e.maxHeight,b=y===void 0?null:y,x=e.width,w=x===void 0?null:x,k=e.minWidth,O=k===void 0?null:k,_=e.maxWidth,T=_===void 0?null:_,E=e.placeholder,N=E===void 0?"":E,I=e.editable,A=I===void 0?!0:I,$=e.readOnly,z=$===void 0?!1:$,D=e.indentWithTab,q=D===void 0?!0:D,H=e.basicSetup,V=H===void 0?!0:H,B=e.root,W=e.initialState,L=g.useState(),G=L[0],M=L[1],R=g.useState(),F=R[0],U=R[1],Q=g.useState(),te=Q[0],J=Q[1],ee=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],ae=nYn(p,v,b,w,O,T),X=Rt.updateListener.of(ce=>{if(ce.docChanged&&typeof r=="function"&&!ce.transactions.some(ye=>ye.annotation(NBe))){ee.current?ee.current.reset():(ee.current=new JQn(()=>{if(re.current){var ye=re.current;re.current=null,ye()}ee.current=null},rYn),eYn().add(ee.current));var le=ce.state.doc,ve=le.toString();r(ve,ce)}s&&s(XQn(ce))}),ne=KQn({theme:f,editable:A,readOnly:z,placeholder:N,indentWithTab:q,basicSetup:V}),se=[X,...ae?[ae]:[],tYn,...ne];return i&&typeof i=="function"&&se.push(Rt.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!te){var ce={doc:t,selection:n,extensions:se},le=W?ps.fromJSON(W.json,ce,W.fields):ps.create(ce);if(J(le),!F){var ve=new Rt({state:le,parent:G,root:B});U(ve),a&&a(ve,le)}}return()=>{F&&(J(void 0),U(void 0))}},[G,te]),g.useEffect(()=>{e.container&&M(e.container)},[e.container]),g.useEffect(()=>()=>{F&&(F.destroy(),U(void 0)),ee.current&&(ee.current.cancel(),ee.current=null)},[F]),g.useEffect(()=>{u&&F&&F.focus()},[u,F]),g.useEffect(()=>{F&&F.dispatch({effects:pr.reconfigure.of(se)})},[f,c,p,v,b,w,O,T,N,A,z,q,V,r,i]),g.useEffect(()=>{if(t!==void 0){var ce=F?F.state.doc.toString():"";if(F&&t!==ce){var le=ee.current&&!ee.current.isDone,ve=()=>{F&&t!==F.state.doc.toString()&&F.dispatch({changes:{from:0,to:F.state.doc.toString().length,insert:t||""},annotations:[NBe.of(!0)]})};le?re.current=ve:ve()}}},[t,F]),{state:te,setState:J,view:F,setView:U,container:G,setContainer:M}}var iYn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],rd=g.forwardRef((e,t)=>{var n=e.className,r=e.value,s=r===void 0?"":r,a=e.selection,i=e.extensions,l=i===void 0?[]:i,c=e.onChange,u=e.onStatistics,d=e.onCreateEditor,f=e.onUpdate,h=e.autoFocus,p=e.theme,m=p===void 0?"light":p,v=e.height,y=e.minHeight,b=e.maxHeight,x=e.width,w=e.minWidth,k=e.maxWidth,O=e.basicSetup,_=e.placeholder,T=e.indentWithTab,E=e.editable,N=e.readOnly,I=e.root,A=e.initialState,$=BCt(e,iYn),z=g.useRef(null),D=aYn({root:I,value:s,autoFocus:h,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:O,placeholder:_,indentWithTab:T,editable:E,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),q=D.state,H=D.view,V=D.container,B=D.setContainer;g.useImperativeHandle(t,()=>({editor:z.current,state:q,view:H}),[z,V,q,H]);var W=g.useCallback(G=>{z.current=G,B(G)},[B]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var L=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",xC({ref:W,className:""+L+(n?" "+n:"")},$))});rd.displayName="CodeMirror";function oYn(e){return new gC(hCe.define(e))}const P_t=[vg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return Va(()=>Promise.resolve().then(()=>XF),[],import.meta.url).then(e=>e.javascript())}}),vg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return Va(()=>Promise.resolve().then(()=>Fqn),void 0,import.meta.url).then(e=>e.json())}}),vg.of({name:"JSX",extensions:["jsx"],load(){return Va(()=>Promise.resolve().then(()=>XF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),vg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return Va(()=>Promise.resolve().then(()=>RZn),void 0,import.meta.url).then(e=>e.markdown())}}),vg.of({name:"TSX",extensions:["tsx"],load(){return Va(()=>Promise.resolve().then(()=>XF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),vg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return Va(()=>Promise.resolve().then(()=>XF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),vg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return Va(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>oYn(e.shell))}})];function lYn(e,t=5){if(!e?.properties)return[];const n=[];function r(s,a,i){if(i>t)return;const l=Array.isArray(s.type)?s.type.join(" | "):s.type;if(n.push({path:a,label:a,description:s.description??s.title,type:l}),s.properties)for(const[c,u]of Object.entries(s.properties))r(u,`${a}.${c}`,i+1);if(s.items?.properties)for(const[c,u]of Object.entries(s.items.properties))r(u,`${a}[].${c}`,i+1)}for(const[s,a]of Object.entries(e.properties))r(a,s,1);return n}function cYn(e){const t=lYn(e);return _Ot({override:[uYn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function uYn(e){return t=>{const r=t.state.sliceDoc(Math.max(0,t.pos-50),t.pos).match(/\{\{([a-zA-Z0-9_.\[\]]*)?$/);if(!r)return null;const s=r[1]??"",a=t.pos-s.length,i=s?e.filter(c=>c.path.toLowerCase().startsWith(s.toLowerCase())):e;if(i.length===0)return null;const l=i.map(c=>({label:c.path,displayLabel:c.path,detail:c.type,info:c.description,apply:(u,d,f,h)=>{const v=u.state.sliceDoc(h,h+2)==="}}"?d.label:`${d.label}}}`;u.dispatch({changes:{from:f,to:h,insert:v},selection:{anchor:f+v.length}})}}));return{from:a,options:l,validFor:/^[a-zA-Z0-9_.\[\]]*$/}}}const dYn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,fYn=jn.mark({class:"cm-variable-highlight"}),IBe=new Fkt({regexp:dYn,decoration:()=>fYn}),hYn=_o.fromClass(class{decorations;constructor(e){this.decorations=IBe.createDeco(e)}update(e){this.decorations=IBe.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),pYn=hYn;function mYn(){const e=QI({settings:{fontFamily:"var(--font-mono)",fontSize:"var(--text-ui-smd)",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[ue.className,ue.propertyName],color:"var(--neutral6)"},{tag:ue.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.heading1,ue.heading2,ue.heading3,ue.heading4,ue.heading5,ue.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:ue.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:ue.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:ue.link,color:"var(--accent3)",textDecoration:"underline"},{tag:ue.url,color:"var(--accent3)"},{tag:ue.monospace,color:"var(--neutral6)"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:ue.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=Rt.theme({".cm-editor":{backgroundColor:"transparent"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{color:"var(--neutral3)"},".cm-cursor":{borderLeftColor:"var(--neutral6)"},".cm-selectionBackground, .cm-content ::selection":{backgroundColor:"color-mix(in srgb, var(--accent3) 22%, transparent)"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"var(--text-ui-sm)",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}});return[e,t]}function gYn(){const e=Rt.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"var(--text-ui-smd)"},"&.cm-editor .cm-scroller":{fontFamily:"var(--font-mono)"},".cm-gutters":{backgroundColor:"transparent",color:"var(--neutral2)",borderRight:"none"},".cm-content":{color:"var(--neutral6)",caretColor:"var(--neutral6)"},".cm-activeLine":{backgroundColor:"transparent"},".cm-lineNumbers .cm-gutterElement":{color:"var(--neutral2)"},".cm-activeLineGutter":{backgroundColor:"transparent",color:"var(--neutral3)"},".cm-cursor, .cm-dropCursor":{borderLeftColor:"var(--neutral6)"},"&.cm-focused .cm-selectionBackground, & .cm-line::selection, & .cm-selectionLayer .cm-selectionBackground, .cm-content ::selection":{background:"color-mix(in srgb, var(--accent3) 22%, transparent) !important"},".cm-tooltip-autocomplete":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",borderRadius:"6px",boxShadow:"0 8px 16px rgba(0, 0, 0, 0.2)"},".cm-tooltip-autocomplete > ul":{fontFamily:"var(--font-mono)"},".cm-completionLabel":{color:"var(--neutral6)"},".cm-completionDetail":{color:"var(--neutral3)",fontSize:"var(--text-ui-sm)",marginLeft:"auto",paddingLeft:"12px"},".cm-completionInfo":{backgroundColor:"var(--surface2)",border:"1px solid var(--border1)",color:"var(--neutral3)",padding:"8px 12px"},".cm-completionIcon":{display:"none"},"ul.cm-completionList li[aria-selected]":{backgroundColor:"var(--surface4)",color:"var(--neutral6)"},".cm-line .cm-variable-highlight":{color:"var(--accent6) !important",fontWeight:"500"}}),t=rv.define([{tag:[ue.comment,ue.bracket],color:"var(--neutral2)"},{tag:[ue.string,ue.meta,ue.regexp],color:"var(--accent1)"},{tag:[ue.atom,ue.bool,ue.special(ue.variableName)],color:"var(--accent6)"},{tag:[ue.keyword,ue.operator,ue.tagName],color:"var(--accent2)"},{tag:[ue.function(ue.propertyName),ue.propertyName],color:"var(--accent5)"},{tag:[ue.definition(ue.variableName),ue.function(ue.variableName),ue.className,ue.attributeName],color:"var(--accent3)"},{tag:[ue.variableName,ue.number],color:"var(--accent5)"},{tag:[ue.name,ue.quote],color:"var(--accent1)"},{tag:ue.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.heading1,ue.heading2,ue.heading3,ue.heading4,ue.heading5,ue.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[ue.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[ue.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:ue.link,color:"var(--accent3)",textDecoration:"underline"},{tag:ue.url,color:"var(--accent3)"},{tag:ue.monospace,color:"var(--neutral6)"},{tag:ue.strikethrough,textDecoration:"line-through"},{tag:[ue.deleted],color:"var(--accent2)"},{tag:ue.invalid,color:"var(--error)"},{tag:[ue.standard(ue.tagName)],color:"var(--accent1)"}]);return[e,T1(t)]}const b0=()=>{const e=b_().resolvedTheme==="dark";return g.useMemo(()=>e?mYn():gYn(),[e])},vYn=xl(K("relative overflow-hidden font-mono outline-hidden focus-within:outline-hidden focus:outline-hidden","duration-normal transition-colors ease-out-custom"),{variants:{variant:{default:"rounded-md border border-border1 bg-surface3 p-1 focus-within:border-neutral6/20",embedded:"rounded-none border-none bg-transparent p-0"}},defaultVariants:{variant:"default"}}),yYn=lp.highest(Rt.editorAttributes.of({style:"outline: none"})),bYn=lp.highest(Rt.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),xYn=[yYn,bYn],Vr=g.forwardRef(({data:e,value:t,onChange:n,showCopyButton:r=!0,className:s,language:a="json",highlightVariables:i=!1,placeholder:l,schema:c,autoFocus:u,lineNumbers:d=!0,lineWrapping:f=!0,editable:h,variant:p,...m},v)=>{const y=b0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const w=[...xYn];return f&&w.push(Rt.lineWrapping),a==="json"?w.push(Wh):a==="markdown"&&w.push(zCe({base:bC,codeLanguages:P_t})),i&&a==="markdown"&&w.push(pYn),c&&a==="markdown"&&w.push(cYn(c)),h===!1&&w.push(ps.readOnly.of(!0)),w},[a,i,c,h,f]);return o.jsxs("div",{className:K(vYn({variant:p}),s),...m,children:[r&&o.jsx(Pa,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(rd,{ref:v,value:b,theme:y,extensions:x,onChange:n,editable:h,"aria-label":"Code editor",placeholder:l,height:"100%",style:{height:"100%"},autoFocus:u,basicSetup:{lineNumbers:d}})]})}),$_t={js:"javascript",javascript:"javascript",mjs:"javascript",cjs:"javascript",node:"javascript",ts:"typescript",typescript:"typescript",mts:"typescript",cts:"typescript",tsx:"tsx",jsx:"jsx",json:"json",json5:"json",md:"markdown",markdown:"markdown",py:"python",python:"python",sh:"bash",bash:"bash",shell:"bash",zsh:"bash",yml:"yaml",yaml:"yaml",diff:"diff",patch:"diff",css:"css",scss:"css",html:"html",htm:"html",xml:"xml",svg:"xml",sql:"sql"};let xne=null;function wYn(){return xne||(xne=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([Va(()=>import("./core-BMRp5Zv-.js"),__vite__mapDeps([0,1,2]),import.meta.url),Va(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[Va(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),Va(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[Va(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),Va(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),Va(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),Va(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),Va(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),Va(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),Va(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),Va(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),Va(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),Va(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),Va(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),Va(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),Va(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),Va(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),xne}async function SYn(e,t){const n=$_t[t?.toLowerCase()];if(!n)return null;const r=await wYn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function kYn(e){const t=e?.split(".").pop()?.toLowerCase();return t?$_t[t]:void 0}const OYn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},CYn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=b0(),{settings:r,setSettings:s}=PW(),a=r?.tracingOptions,i=g.useMemo(()=>OYn(a),[a]),[l,c]=g.useState(()=>i),u=g.useRef(!1);g.useEffect(()=>{u.current||c(i)},[i]);const d=h=>{u.current=!0,c(h)},f=()=>{if(!l){s({...r,tracingOptions:void 0}),t?.();return}try{const h=JSON.parse(l);typeof h=="object"&&h!==null&&s({...r,tracingOptions:h})}catch{return}t?.()};return o.jsxs("div",{className:"space-y-2 px-5 py-2",children:[o.jsx(ge,{as:"h3",variant:"ui-md",className:"text-neutral3",children:"Tracing Options"}),o.jsx(rd,{value:l,onChange:d,theme:n,extensions:[Wh],className:K("overflow-y-scroll bg-surface3 rounded-lg overflow-hidden p-3",e)}),o.jsx("div",{className:"flex items-center justify-end",children:o.jsx(ie,{icon:o.jsx(Fn,{}),type:"button",onClick:f,children:"Save"})})]})},_Yn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(st,{children:o.jsx(Jwe,{})})})}),o.jsx(pn,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Run Options"}),o.jsx(Ms,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Mr,{children:o.jsx(CYn,{onSaved:()=>t(!1)})})]})})]})};function EYn({status:e}){switch(e){case"running":return o.jsx(Zt,{});case"failed":return o.jsx(qt,{className:"text-accent2"});case"canceled":return o.jsx(Os,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(xS,{className:"text-neutral3"});case"suspended":return o.jsx(yH,{className:"text-accent3"});case"success":return o.jsx(Fn,{className:"text-accent1"});default:return o.jsx(xS,{className:"text-neutral3"})}}function M_t({status:e}){return o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx(st,{"aria-label":e,className:"shrink-0",children:o.jsx(EYn,{status:e})})}),o.jsx(pn,{children:e})]})}var wne,ABe;function QCe(){if(ABe)return wne;ABe=1;var e="\0",t="\0",n="";class r{_isDirected=!0;_isMultigraph=!1;_isCompound=!1;_label;_defaultNodeLabelFn=()=>{};_defaultEdgeLabelFn=()=>{};_nodes={};_in={};_preds={};_out={};_sucs={};_edgeObjs={};_edgeLabels={};_nodeCount=0;_edgeCount=0;_parent;_children;constructor(d){d&&(this._isDirected=Object.hasOwn(d,"directed")?d.directed:!0,this._isMultigraph=Object.hasOwn(d,"multigraph")?d.multigraph:!1,this._isCompound=Object.hasOwn(d,"compound")?d.compound:!1),this._isCompound&&(this._parent={},this._children={},this._children[t]={})}isDirected(){return this._isDirected}isMultigraph(){return this._isMultigraph}isCompound(){return this._isCompound}setGraph(d){return this._label=d,this}graph(){return this._label}setDefaultNodeLabel(d){return this._defaultNodeLabelFn=d,typeof d!="function"&&(this._defaultNodeLabelFn=()=>d),this}nodeCount(){return this._nodeCount}nodes(){return Object.keys(this._nodes)}sources(){var d=this;return this.nodes().filter(f=>Object.keys(d._in[f]).length===0)}sinks(){var d=this;return this.nodes().filter(f=>Object.keys(d._out[f]).length===0)}setNodes(d,f){var h=arguments,p=this;return d.forEach(function(m){h.length>1?p.setNode(m,f):p.setNode(m)}),this}setNode(d,f){return Object.hasOwn(this._nodes,d)?(arguments.length>1&&(this._nodes[d]=f),this):(this._nodes[d]=arguments.length>1?f:this._defaultNodeLabelFn(d),this._isCompound&&(this._parent[d]=t,this._children[d]={},this._children[t][d]=!0),this._in[d]={},this._preds[d]={},this._out[d]={},this._sucs[d]={},++this._nodeCount,this)}node(d){return this._nodes[d]}hasNode(d){return Object.hasOwn(this._nodes,d)}removeNode(d){var f=this;if(Object.hasOwn(this._nodes,d)){var h=p=>f.removeEdge(f._edgeObjs[p]);delete this._nodes[d],this._isCompound&&(this._removeFromParentsChildList(d),delete this._parent[d],this.children(d).forEach(function(p){f.setParent(p)}),delete this._children[d]),Object.keys(this._in[d]).forEach(h),delete this._in[d],delete this._preds[d],Object.keys(this._out[d]).forEach(h),delete this._out[d],delete this._sucs[d],--this._nodeCount}return this}setParent(d,f){if(!this._isCompound)throw new Error("Cannot set parent in a non-compound graph");if(f===void 0)f=t;else{f+="";for(var h=f;h!==void 0;h=this.parent(h))if(h===d)throw new Error("Setting "+f+" as parent of "+d+" would create a cycle");this.setNode(f)}return this.setNode(d),this._removeFromParentsChildList(d),this._parent[d]=f,this._children[f][d]=!0,this}_removeFromParentsChildList(d){delete this._children[this._parent[d]][d]}parent(d){if(this._isCompound){var f=this._parent[d];if(f!==t)return f}}children(d=t){if(this._isCompound){var f=this._children[d];if(f)return Object.keys(f)}else{if(d===t)return this.nodes();if(this.hasNode(d))return[]}}predecessors(d){var f=this._preds[d];if(f)return Object.keys(f)}successors(d){var f=this._sucs[d];if(f)return Object.keys(f)}neighbors(d){var f=this.predecessors(d);if(f){const p=new Set(f);for(var h of this.successors(d))p.add(h);return Array.from(p.values())}}isLeaf(d){var f;return this.isDirected()?f=this.successors(d):f=this.neighbors(d),f.length===0}filterNodes(d){var f=new this.constructor({directed:this._isDirected,multigraph:this._isMultigraph,compound:this._isCompound});f.setGraph(this.graph());var h=this;Object.entries(this._nodes).forEach(function([v,y]){d(v)&&f.setNode(v,y)}),Object.values(this._edgeObjs).forEach(function(v){f.hasNode(v.v)&&f.hasNode(v.w)&&f.setEdge(v,h.edge(v))});var p={};function m(v){var y=h.parent(v);return y===void 0||f.hasNode(y)?(p[v]=y,y):y in p?p[y]:m(y)}return this._isCompound&&f.nodes().forEach(v=>f.setParent(v,m(v))),f}setDefaultEdgeLabel(d){return this._defaultEdgeLabelFn=d,typeof d!="function"&&(this._defaultEdgeLabelFn=()=>d),this}edgeCount(){return this._edgeCount}edges(){return Object.values(this._edgeObjs)}setPath(d,f){var h=this,p=arguments;return d.reduce(function(m,v){return p.length>1?h.setEdge(m,v,f):h.setEdge(m,v),v}),this}setEdge(){var d,f,h,p,m=!1,v=arguments[0];typeof v=="object"&&v!==null&&"v"in v?(d=v.v,f=v.w,h=v.name,arguments.length===2&&(p=arguments[1],m=!0)):(d=v,f=arguments[1],h=arguments[3],arguments.length>2&&(p=arguments[2],m=!0)),d=""+d,f=""+f,h!==void 0&&(h=""+h);var y=i(this._isDirected,d,f,h);if(Object.hasOwn(this._edgeLabels,y))return m&&(this._edgeLabels[y]=p),this;if(h!==void 0&&!this._isMultigraph)throw new Error("Cannot set a named edge when isMultigraph = false");this.setNode(d),this.setNode(f),this._edgeLabels[y]=m?p:this._defaultEdgeLabelFn(d,f,h);var b=l(this._isDirected,d,f,h);return d=b.v,f=b.w,Object.freeze(b),this._edgeObjs[y]=b,s(this._preds[f],d),s(this._sucs[d],f),this._in[f][y]=b,this._out[d][y]=b,this._edgeCount++,this}edge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h);return this._edgeLabels[p]}edgeAsObj(){const d=this.edge(...arguments);return typeof d!="object"?{label:d}:d}hasEdge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h);return Object.hasOwn(this._edgeLabels,p)}removeEdge(d,f,h){var p=arguments.length===1?c(this._isDirected,arguments[0]):i(this._isDirected,d,f,h),m=this._edgeObjs[p];return m&&(d=m.v,f=m.w,delete this._edgeLabels[p],delete this._edgeObjs[p],a(this._preds[f],d),a(this._sucs[d],f),delete this._in[f][p],delete this._out[d][p],this._edgeCount--),this}inEdges(d,f){var h=this._in[d];if(h){var p=Object.values(h);return f?p.filter(m=>m.v===f):p}}outEdges(d,f){var h=this._out[d];if(h){var p=Object.values(h);return f?p.filter(m=>m.w===f):p}}nodeEdges(d,f){var h=this.inEdges(d,f);if(h)return h.concat(this.outEdges(d,f))}}function s(u,d){u[d]?u[d]++:u[d]=1}function a(u,d){--u[d]||delete u[d]}function i(u,d,f,h){var p=""+d,m=""+f;if(!u&&p>m){var v=p;p=m,m=v}return p+n+m+n+(h===void 0?e:h)}function l(u,d,f,h){var p=""+d,m=""+f;if(!u&&p>m){var v=p;p=m,m=v}var y={v:p,w:m};return h&&(y.name=h),y}function c(u,d){return i(u,d.v,d.w,d.name)}return wne=r,wne}var Sne,RBe;function TYn(){return RBe||(RBe=1,Sne="2.2.4"),Sne}var kne,PBe;function jYn(){return PBe||(PBe=1,kne={Graph:QCe(),version:TYn()}),kne}var One,$Be;function NYn(){if($Be)return One;$Be=1;var e=QCe();One={write:t,read:s};function t(a){var i={options:{directed:a.isDirected(),multigraph:a.isMultigraph(),compound:a.isCompound()},nodes:n(a),edges:r(a)};return a.graph()!==void 0&&(i.value=structuredClone(a.graph())),i}function n(a){return a.nodes().map(function(i){var l=a.node(i),c=a.parent(i),u={v:i};return l!==void 0&&(u.value=l),c!==void 0&&(u.parent=c),u})}function r(a){return a.edges().map(function(i){var l=a.edge(i),c={v:i.v,w:i.w};return i.name!==void 0&&(c.name=i.name),l!==void 0&&(c.value=l),c})}function s(a){var i=new e(a.options).setGraph(a.value);return a.nodes.forEach(function(l){i.setNode(l.v,l.value),l.parent&&i.setParent(l.v,l.parent)}),a.edges.forEach(function(l){i.setEdge({v:l.v,w:l.w,name:l.name},l.value)}),i}return One}var Cne,MBe;function IYn(){if(MBe)return Cne;MBe=1,Cne=e;function e(t){var n={},r=[],s;function a(i){Object.hasOwn(n,i)||(n[i]=!0,s.push(i),t.successors(i).forEach(a),t.predecessors(i).forEach(a))}return t.nodes().forEach(function(i){s=[],a(i),s.length&&r.push(s)}),r}return Cne}var _ne,DBe;function D_t(){if(DBe)return _ne;DBe=1;class e{_arr=[];_keyIndices={};size(){return this._arr.length}keys(){return this._arr.map(function(n){return n.key})}has(n){return Object.hasOwn(this._keyIndices,n)}priority(n){var r=this._keyIndices[n];if(r!==void 0)return this._arr[r].priority}min(){if(this.size()===0)throw new Error("Queue underflow");return this._arr[0].key}add(n,r){var s=this._keyIndices;if(n=String(n),!Object.hasOwn(s,n)){var a=this._arr,i=a.length;return s[n]=i,a.push({key:n,priority:r}),this._decrease(i),!0}return!1}removeMin(){this._swap(0,this._arr.length-1);var n=this._arr.pop();return delete this._keyIndices[n.key],this._heapify(0),n.key}decrease(n,r){var s=this._keyIndices[n];if(r>this._arr[s].priority)throw new Error("New priority is greater than current priority. Key: "+n+" Old: "+this._arr[s].priority+" New: "+r);this._arr[s].priority=r,this._decrease(s)}_heapify(n){var r=this._arr,s=2*n,a=s+1,i=n;s<r.length&&(i=r[s].priority<r[i].priority?s:i,a<r.length&&(i=r[a].priority<r[i].priority?a:i),i!==n&&(this._swap(n,i),this._heapify(i)))}_decrease(n){for(var r=this._arr,s=r[n].priority,a;n!==0&&(a=n>>1,!(r[a].priority<s));)this._swap(n,a),n=a}_swap(n,r){var s=this._arr,a=this._keyIndices,i=s[n],l=s[r];s[n]=l,s[r]=i,a[l.key]=n,a[i.key]=r}}return _ne=e,_ne}var Ene,LBe;function L_t(){if(LBe)return Ene;LBe=1;var e=D_t();Ene=n;var t=()=>1;function n(s,a,i,l){return r(s,String(a),i||t,l||function(c){return s.outEdges(c)})}function r(s,a,i,l){var c={},u=new e,d,f,h=function(p){var m=p.v!==d?p.v:p.w,v=c[m],y=i(p),b=f.distance+y;if(y<0)throw new Error("dijkstra does not allow negative edge weights. Bad edge: "+p+" Weight: "+y);b<v.distance&&(v.distance=b,v.predecessor=d,u.decrease(m,b))};for(s.nodes().forEach(function(p){var m=p===a?0:Number.POSITIVE_INFINITY;c[p]={distance:m},u.add(p,m)});u.size()>0&&(d=u.removeMin(),f=c[d],f.distance!==Number.POSITIVE_INFINITY);)l(d).forEach(h);return c}return Ene}var Tne,FBe;function AYn(){if(FBe)return Tne;FBe=1;var e=L_t();Tne=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Tne}var jne,zBe;function F_t(){if(zBe)return jne;zBe=1,jne=e;function e(t){var n=0,r=[],s={},a=[];function i(l){var c=s[l]={onStack:!0,lowlink:n,index:n++};if(r.push(l),t.successors(l).forEach(function(f){Object.hasOwn(s,f)?s[f].onStack&&(c.lowlink=Math.min(c.lowlink,s[f].index)):(i(f),c.lowlink=Math.min(c.lowlink,s[f].lowlink))}),c.lowlink===c.index){var u=[],d;do d=r.pop(),s[d].onStack=!1,u.push(d);while(l!==d);a.push(u)}}return t.nodes().forEach(function(l){Object.hasOwn(s,l)||i(l)}),a}return jne}var Nne,BBe;function RYn(){if(BBe)return Nne;BBe=1;var e=F_t();Nne=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return Nne}var Ine,UBe;function PYn(){if(UBe)return Ine;UBe=1,Ine=t;var e=()=>1;function t(r,s,a){return n(r,s||e,a||function(i){return r.outEdges(i)})}function n(r,s,a){var i={},l=r.nodes();return l.forEach(function(c){i[c]={},i[c][c]={distance:0},l.forEach(function(u){c!==u&&(i[c][u]={distance:Number.POSITIVE_INFINITY})}),a(c).forEach(function(u){var d=u.v===c?u.w:u.v,f=s(u);i[c][d]={distance:f,predecessor:c}})}),l.forEach(function(c){var u=i[c];l.forEach(function(d){var f=i[d];l.forEach(function(h){var p=f[c],m=u[h],v=f[h],y=p.distance+m.distance;y<v.distance&&(v.distance=y,v.predecessor=m.predecessor)})})}),i}return Ine}var Ane,qBe;function z_t(){if(qBe)return Ane;qBe=1;function e(n){var r={},s={},a=[];function i(l){if(Object.hasOwn(s,l))throw new t;Object.hasOwn(r,l)||(s[l]=!0,r[l]=!0,n.predecessors(l).forEach(i),delete s[l],a.push(l))}if(n.sinks().forEach(i),Object.keys(r).length!==n.nodeCount())throw new t;return a}class t extends Error{constructor(){super(...arguments)}}return Ane=e,e.CycleException=t,Ane}var Rne,VBe;function $Yn(){if(VBe)return Rne;VBe=1;var e=z_t();Rne=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return Rne}var Pne,HBe;function B_t(){if(HBe)return Pne;HBe=1,Pne=e;function e(s,a,i){Array.isArray(a)||(a=[a]);var l=s.isDirected()?f=>s.successors(f):f=>s.neighbors(f),c=i==="post"?t:n,u=[],d={};return a.forEach(f=>{if(!s.hasNode(f))throw new Error("Graph does not have node: "+f);c(f,l,d,u)}),u}function t(s,a,i,l){for(var c=[[s,!1]];c.length>0;){var u=c.pop();u[1]?l.push(u[0]):Object.hasOwn(i,u[0])||(i[u[0]]=!0,c.push([u[0],!0]),r(a(u[0]),d=>c.push([d,!1])))}}function n(s,a,i,l){for(var c=[s];c.length>0;){var u=c.pop();Object.hasOwn(i,u)||(i[u]=!0,l.push(u),r(a(u),d=>c.push(d)))}}function r(s,a){for(var i=s.length;i--;)a(s[i],i,s);return s}return Pne}var $ne,WBe;function MYn(){if(WBe)return $ne;WBe=1;var e=B_t();$ne=t;function t(n,r){return e(n,r,"post")}return $ne}var Mne,ZBe;function DYn(){if(ZBe)return Mne;ZBe=1;var e=B_t();Mne=t;function t(n,r){return e(n,r,"pre")}return Mne}var Dne,GBe;function LYn(){if(GBe)return Dne;GBe=1;var e=QCe(),t=D_t();Dne=n;function n(r,s){var a=new e,i={},l=new t,c;function u(f){var h=f.v===c?f.w:f.v,p=l.priority(h);if(p!==void 0){var m=s(f);m<p&&(i[h]=c,l.decrease(h,m))}}if(r.nodeCount()===0)return a;r.nodes().forEach(function(f){l.add(f,Number.POSITIVE_INFINITY),a.setNode(f)}),l.decrease(r.nodes()[0],0);for(var d=!1;l.size()>0;){if(c=l.removeMin(),Object.hasOwn(i,c))a.setEdge(c,i[c]);else{if(d)throw new Error("Input graph is not connected: "+r);d=!0}r.nodeEdges(c).forEach(u)}return a}return Dne}var Lne,QBe;function FYn(){return QBe||(QBe=1,Lne={components:IYn(),dijkstra:L_t(),dijkstraAll:AYn(),findCycles:RYn(),floydWarshall:PYn(),isAcyclic:$Yn(),postorder:MYn(),preorder:DYn(),prim:LYn(),tarjan:F_t(),topsort:z_t()}),Lne}var Fne,YBe;function Gg(){if(YBe)return Fne;YBe=1;var e=jYn();return Fne={Graph:e.Graph,json:NYn(),alg:FYn(),version:e.version},Fne}var zne,KBe;function zYn(){if(KBe)return zne;KBe=1;class e{constructor(){let s={};s._next=s._prev=s,this._sentinel=s}dequeue(){let s=this._sentinel,a=s._prev;if(a!==s)return t(a),a}enqueue(s){let a=this._sentinel;s._prev&&s._next&&t(s),s._next=a._next,a._next._prev=s,a._next=s,s._prev=a}toString(){let s=[],a=this._sentinel,i=a._prev;for(;i!==a;)s.push(JSON.stringify(i,n)),i=i._prev;return"["+s.join(", ")+"]"}}function t(r){r._prev._next=r._next,r._next._prev=r._prev,delete r._next,delete r._prev}function n(r,s){if(r!=="_next"&&r!=="_prev")return s}return zne=e,zne}var Bne,XBe;function BYn(){if(XBe)return Bne;XBe=1;let e=Gg().Graph,t=zYn();Bne=r;let n=()=>1;function r(u,d){if(u.nodeCount()<=1)return[];let f=i(u,d||n);return s(f.graph,f.buckets,f.zeroIdx).flatMap(p=>u.outEdges(p.v,p.w))}function s(u,d,f){let h=[],p=d[d.length-1],m=d[0],v;for(;u.nodeCount();){for(;v=m.dequeue();)a(u,d,f,v);for(;v=p.dequeue();)a(u,d,f,v);if(u.nodeCount()){for(let y=d.length-2;y>0;--y)if(v=d[y].dequeue(),v){h=h.concat(a(u,d,f,v,!0));break}}}return h}function a(u,d,f,h,p){let m=p?[]:void 0;return u.inEdges(h.v).forEach(v=>{let y=u.edge(v),b=u.node(v.v);p&&m.push({v:v.v,w:v.w}),b.out-=y,l(d,f,b)}),u.outEdges(h.v).forEach(v=>{let y=u.edge(v),b=v.w,x=u.node(b);x.in-=y,l(d,f,x)}),u.removeNode(h.v),m}function i(u,d){let f=new e,h=0,p=0;u.nodes().forEach(y=>{f.setNode(y,{v:y,in:0,out:0})}),u.edges().forEach(y=>{let b=f.edge(y.v,y.w)||0,x=d(y),w=b+x;f.setEdge(y.v,y.w,w),p=Math.max(p,f.node(y.v).out+=x),h=Math.max(h,f.node(y.w).in+=x)});let m=c(p+h+3).map(()=>new t),v=h+1;return f.nodes().forEach(y=>{l(m,v,f.node(y))}),{graph:f,buckets:m,zeroIdx:v}}function l(u,d,f){f.out?f.in?u[f.out-f.in+d].enqueue(f):u[u.length-1].enqueue(f):u[0].enqueue(f)}function c(u){const d=[];for(let f=0;f<u;f++)d.push(f);return d}return Bne}var Une,JBe;function Dl(){if(JBe)return Une;JBe=1;let e=Gg().Graph;Une={addBorderNode:d,addDummyNode:t,applyWithChunking:p,asNonCompoundGraph:r,buildLayerMatrix:l,intersectRect:i,mapValues:_,maxRank:m,normalizeRanks:c,notime:b,partition:v,pick:O,predecessorWeights:a,range:k,removeEmptyRanks:u,simplify:n,successorWeights:s,time:y,uniqueId:w,zipObject:T};function t(E,N,I,A){for(var $=A;E.hasNode($);)$=w(A);return I.dummy=N,E.setNode($,I),$}function n(E){let N=new e().setGraph(E.graph());return E.nodes().forEach(I=>N.setNode(I,E.node(I))),E.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},$=E.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+$.weight,minlen:Math.max(A.minlen,$.minlen)})}),N}function r(E){let N=new e({multigraph:E.isMultigraph()}).setGraph(E.graph());return E.nodes().forEach(I=>{E.children(I).length||N.setNode(I,E.node(I))}),E.edges().forEach(I=>{N.setEdge(I,E.edge(I))}),N}function s(E){let N=E.nodes().map(I=>{let A={};return E.outEdges(I).forEach($=>{A[$.w]=(A[$.w]||0)+E.edge($).weight}),A});return T(E.nodes(),N)}function a(E){let N=E.nodes().map(I=>{let A={};return E.inEdges(I).forEach($=>{A[$.v]=(A[$.v]||0)+E.edge($).weight}),A});return T(E.nodes(),N)}function i(E,N){let I=E.x,A=E.y,$=N.x-I,z=N.y-A,D=E.width/2,q=E.height/2;if(!$&&!z)throw new Error("Not possible to find intersection inside of the rectangle");let H,V;return Math.abs(z)*D>Math.abs($)*q?(z<0&&(q=-q),H=q*$/z,V=q):($<0&&(D=-D),H=D,V=D*z/$),{x:I+H,y:A+V}}function l(E){let N=k(m(E)+1).map(()=>[]);return E.nodes().forEach(I=>{let A=E.node(I),$=A.rank;$!==void 0&&(N[$][A.order]=I)}),N}function c(E){let N=E.nodes().map(A=>{let $=E.node(A).rank;return $===void 0?Number.MAX_VALUE:$}),I=p(Math.min,N);E.nodes().forEach(A=>{let $=E.node(A);Object.hasOwn($,"rank")&&($.rank-=I)})}function u(E){let N=E.nodes().map(D=>E.node(D).rank),I=p(Math.min,N),A=[];E.nodes().forEach(D=>{let q=E.node(D).rank-I;A[q]||(A[q]=[]),A[q].push(D)});let $=0,z=E.graph().nodeRankFactor;Array.from(A).forEach((D,q)=>{D===void 0&&q%z!==0?--$:D!==void 0&&$&&D.forEach(H=>E.node(H).rank+=$)})}function d(E,N,I,A){let $={width:0,height:0};return arguments.length>=4&&($.rank=I,$.order=A),t(E,"border",$,N)}function f(E,N=h){const I=[];for(let A=0;A<E.length;A+=N){const $=E.slice(A,A+N);I.push($)}return I}const h=65535;function p(E,N){if(N.length>h){const I=f(N);return E.apply(null,I.map(A=>E.apply(null,A)))}else return E.apply(null,N)}function m(E){const I=E.nodes().map(A=>{let $=E.node(A).rank;return $===void 0?Number.MIN_VALUE:$});return p(Math.max,I)}function v(E,N){let I={lhs:[],rhs:[]};return E.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(E,N){let I=Date.now();try{return N()}finally{console.log(E+" time: "+(Date.now()-I)+"ms")}}function b(E,N){return N()}let x=0;function w(E){var N=++x;return E+(""+N)}function k(E,N,I=1){N==null&&(N=E,E=0);let A=z=>z<N;I<0&&(A=z=>N<z);const $=[];for(let z=E;A(z);z+=I)$.push(z);return $}function O(E,N){const I={};for(const A of N)E[A]!==void 0&&(I[A]=E[A]);return I}function _(E,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(E).reduce((A,[$,z])=>(A[$]=I(z,$),A),{})}function T(E,N){return E.reduce((I,A,$)=>(I[A]=N[$],I),{})}return Une}var qne,eUe;function UYn(){if(eUe)return qne;eUe=1;let e=BYn(),t=Dl().uniqueId;qne={run:n,undo:s};function n(a){(a.graph().acyclicer==="greedy"?e(a,l(a)):r(a)).forEach(c=>{let u=a.edge(c);a.removeEdge(c),u.forwardName=c.name,u.reversed=!0,a.setEdge(c.w,c.v,u,t("rev"))});function l(c){return u=>c.edge(u).weight}}function r(a){let i=[],l={},c={};function u(d){Object.hasOwn(c,d)||(c[d]=!0,l[d]=!0,a.outEdges(d).forEach(f=>{Object.hasOwn(l,f.w)?i.push(f):u(f.w)}),delete l[d])}return a.nodes().forEach(u),i}function s(a){a.edges().forEach(i=>{let l=a.edge(i);if(l.reversed){a.removeEdge(i);let c=l.forwardName;delete l.reversed,delete l.forwardName,a.setEdge(i.w,i.v,l,c)}})}return qne}var Vne,tUe;function qYn(){if(tUe)return Vne;tUe=1;let e=Dl();Vne={run:t,undo:r};function t(s){s.graph().dummyChains=[],s.edges().forEach(a=>n(s,a))}function n(s,a){let i=a.v,l=s.node(i).rank,c=a.w,u=s.node(c).rank,d=a.name,f=s.edge(a),h=f.labelRank;if(u===l+1)return;s.removeEdge(a);let p,m,v;for(v=0,++l;l<u;++v,++l)f.points=[],m={width:0,height:0,edgeLabel:f,edgeObj:a,rank:l},p=e.addDummyNode(s,"edge",m,"_d"),l===h&&(m.width=f.width,m.height=f.height,m.dummy="edge-label",m.labelpos=f.labelpos),s.setEdge(i,p,{weight:f.weight},d),v===0&&s.graph().dummyChains.push(p),i=p;s.setEdge(i,c,{weight:f.weight},d)}function r(s){s.graph().dummyChains.forEach(a=>{let i=s.node(a),l=i.edgeLabel,c;for(s.setEdge(i.edgeObj,l);i.dummy;)c=s.successors(a)[0],s.removeNode(a),l.points.push({x:i.x,y:i.y}),i.dummy==="edge-label"&&(l.x=i.x,l.y=i.y,l.width=i.width,l.height=i.height),a=c,i=s.node(a)})}return Vne}var Hne,nUe;function VU(){if(nUe)return Hne;nUe=1;const{applyWithChunking:e}=Dl();Hne={longestPath:t,slack:n};function t(r){var s={};function a(i){var l=r.node(i);if(Object.hasOwn(s,i))return l.rank;s[i]=!0;let c=r.outEdges(i).map(d=>d==null?Number.POSITIVE_INFINITY:a(d.w)-r.edge(d).minlen);var u=e(Math.min,c);return u===Number.POSITIVE_INFINITY&&(u=0),l.rank=u}r.sources().forEach(a)}function n(r,s){return r.node(s.w).rank-r.node(s.v).rank-r.edge(s).minlen}return Hne}var Wne,rUe;function U_t(){if(rUe)return Wne;rUe=1;var e=Gg().Graph,t=VU().slack;Wne=n;function n(i){var l=new e({directed:!1}),c=i.nodes()[0],u=i.nodeCount();l.setNode(c,{});for(var d,f;r(l,i)<u;)d=s(l,i),f=l.hasNode(d.v)?t(i,d):-t(i,d),a(l,i,f);return l}function r(i,l){function c(u){l.nodeEdges(u).forEach(d=>{var f=d.v,h=u===f?d.w:f;!i.hasNode(h)&&!t(l,d)&&(i.setNode(h,{}),i.setEdge(u,h,{}),c(h))})}return i.nodes().forEach(c),i.nodeCount()}function s(i,l){return l.edges().reduce((u,d)=>{let f=Number.POSITIVE_INFINITY;return i.hasNode(d.v)!==i.hasNode(d.w)&&(f=t(l,d)),f<u[0]?[f,d]:u},[Number.POSITIVE_INFINITY,null])[1]}function a(i,l,c){i.nodes().forEach(u=>l.node(u).rank+=c)}return Wne}var Zne,sUe;function VYn(){if(sUe)return Zne;sUe=1;var e=U_t(),t=VU().slack,n=VU().longestPath,r=Gg().alg.preorder,s=Gg().alg.postorder,a=Dl().simplify;Zne=i,i.initLowLimValues=d,i.initCutValues=l,i.calcCutValue=u,i.leaveEdge=h,i.enterEdge=p,i.exchangeEdges=m;function i(x){x=a(x),n(x);var w=e(x);d(w),l(w,x);for(var k,O;k=h(w);)O=p(w,x,k),m(w,x,k,O)}function l(x,w){var k=s(x,x.nodes());k=k.slice(0,k.length-1),k.forEach(O=>c(x,w,O))}function c(x,w,k){var O=x.node(k),_=O.parent;x.edge(k,_).cutvalue=u(x,w,k)}function u(x,w,k){var O=x.node(k),_=O.parent,T=!0,E=w.edge(k,_),N=0;return E||(T=!1,E=w.edge(_,k)),N=E.weight,w.nodeEdges(k).forEach(I=>{var A=I.v===k,$=A?I.w:I.v;if($!==_){var z=A===T,D=w.edge(I).weight;if(N+=z?D:-D,y(x,k,$)){var q=x.edge(k,$).cutvalue;N+=z?-q:q}}}),N}function d(x,w){arguments.length<2&&(w=x.nodes()[0]),f(x,{},1,w)}function f(x,w,k,O,_){var T=k,E=x.node(O);return w[O]=!0,x.neighbors(O).forEach(N=>{Object.hasOwn(w,N)||(k=f(x,w,k,N,O))}),E.low=T,E.lim=k++,_?E.parent=_:delete E.parent,k}function h(x){return x.edges().find(w=>x.edge(w).cutvalue<0)}function p(x,w,k){var O=k.v,_=k.w;w.hasEdge(O,_)||(O=k.w,_=k.v);var T=x.node(O),E=x.node(_),N=T,I=!1;T.lim>E.lim&&(N=E,I=!0);var A=w.edges().filter($=>I===b(x,x.node($.v),N)&&I!==b(x,x.node($.w),N));return A.reduce(($,z)=>t(w,z)<t(w,$)?z:$)}function m(x,w,k,O){var _=k.v,T=k.w;x.removeEdge(_,T),x.setEdge(O.v,O.w,{}),d(x),l(x,w),v(x,w)}function v(x,w){var k=x.nodes().find(_=>!w.node(_).parent),O=r(x,k);O=O.slice(1),O.forEach(_=>{var T=x.node(_).parent,E=w.edge(_,T),N=!1;E||(E=w.edge(T,_),N=!0),w.node(_).rank=w.node(T).rank+(N?E.minlen:-E.minlen)})}function y(x,w,k){return x.hasEdge(w,k)}function b(x,w,k){return k.low<=w.lim&&w.lim<=k.lim}return Zne}var Gne,aUe;function HYn(){if(aUe)return Gne;aUe=1;var e=VU(),t=e.longestPath,n=U_t(),r=VYn();Gne=s;function s(c){var u=c.graph().ranker;if(u instanceof Function)return u(c);switch(c.graph().ranker){case"network-simplex":l(c);break;case"tight-tree":i(c);break;case"longest-path":a(c);break;case"none":break;default:l(c)}}var a=t;function i(c){t(c),n(c)}function l(c){r(c)}return Gne}var Qne,iUe;function WYn(){if(iUe)return Qne;iUe=1,Qne=e;function e(r){let s=n(r);r.graph().dummyChains.forEach(a=>{let i=r.node(a),l=i.edgeObj,c=t(r,s,l.v,l.w),u=c.path,d=c.lca,f=0,h=u[f],p=!0;for(;a!==l.w;){if(i=r.node(a),p){for(;(h=u[f])!==d&&r.node(h).maxRank<i.rank;)f++;h===d&&(p=!1)}if(!p){for(;f<u.length-1&&r.node(h=u[f+1]).minRank<=i.rank;)f++;h=u[f]}r.setParent(a,h),a=r.successors(a)[0]}})}function t(r,s,a,i){let l=[],c=[],u=Math.min(s[a].low,s[i].low),d=Math.max(s[a].lim,s[i].lim),f,h;f=a;do f=r.parent(f),l.push(f);while(f&&(s[f].low>u||d>s[f].lim));for(h=f,f=i;(f=r.parent(f))!==h;)c.push(f);return{path:l.concat(c.reverse()),lca:h}}function n(r){let s={},a=0;function i(l){let c=a;r.children(l).forEach(i),s[l]={low:c,lim:a++}}return r.children().forEach(i),s}return Qne}var Yne,oUe;function ZYn(){if(oUe)return Yne;oUe=1;let e=Dl();Yne={run:t,cleanup:a};function t(i){let l=e.addDummyNode(i,"root",{},"_root"),c=r(i),u=Object.values(c),d=e.applyWithChunking(Math.max,u)-1,f=2*d+1;i.graph().nestingRoot=l,i.edges().forEach(p=>i.edge(p).minlen*=f);let h=s(i)+1;i.children().forEach(p=>n(i,l,f,h,d,c,p)),i.graph().nodeRankFactor=f}function n(i,l,c,u,d,f,h){let p=i.children(h);if(!p.length){h!==l&&i.setEdge(l,h,{weight:0,minlen:c});return}let m=e.addBorderNode(i,"_bt"),v=e.addBorderNode(i,"_bb"),y=i.node(h);i.setParent(m,h),y.borderTop=m,i.setParent(v,h),y.borderBottom=v,p.forEach(b=>{n(i,l,c,u,d,f,b);let x=i.node(b),w=x.borderTop?x.borderTop:b,k=x.borderBottom?x.borderBottom:b,O=x.borderTop?u:2*u,_=w!==k?1:d-f[h]+1;i.setEdge(m,w,{weight:O,minlen:_,nestingEdge:!0}),i.setEdge(k,v,{weight:O,minlen:_,nestingEdge:!0})}),i.parent(h)||i.setEdge(l,m,{weight:0,minlen:d+f[h]})}function r(i){var l={};function c(u,d){var f=i.children(u);f&&f.length&&f.forEach(h=>c(h,d+1)),l[u]=d}return i.children().forEach(u=>c(u,1)),l}function s(i){return i.edges().reduce((l,c)=>l+i.edge(c).weight,0)}function a(i){var l=i.graph();i.removeNode(l.nestingRoot),delete l.nestingRoot,i.edges().forEach(c=>{var u=i.edge(c);u.nestingEdge&&i.removeEdge(c)})}return Yne}var Kne,lUe;function GYn(){if(lUe)return Kne;lUe=1;let e=Dl();Kne=t;function t(r){function s(a){let i=r.children(a),l=r.node(a);if(i.length&&i.forEach(s),Object.hasOwn(l,"minRank")){l.borderLeft=[],l.borderRight=[];for(let c=l.minRank,u=l.maxRank+1;c<u;++c)n(r,"borderLeft","_bl",a,l,c),n(r,"borderRight","_br",a,l,c)}}r.children().forEach(s)}function n(r,s,a,i,l,c){let u={width:0,height:0,rank:c,borderType:s},d=l[s][c-1],f=e.addDummyNode(r,"border",u,a);l[s][c]=f,r.setParent(f,i),d&&r.setEdge(d,f,{weight:1})}return Kne}var Xne,cUe;function QYn(){if(cUe)return Xne;cUe=1,Xne={adjust:e,undo:t};function e(c){let u=c.graph().rankdir.toLowerCase();(u==="lr"||u==="rl")&&n(c)}function t(c){let u=c.graph().rankdir.toLowerCase();(u==="bt"||u==="rl")&&s(c),(u==="lr"||u==="rl")&&(i(c),n(c))}function n(c){c.nodes().forEach(u=>r(c.node(u))),c.edges().forEach(u=>r(c.edge(u)))}function r(c){let u=c.width;c.width=c.height,c.height=u}function s(c){c.nodes().forEach(u=>a(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(a),Object.hasOwn(d,"y")&&a(d)})}function a(c){c.y=-c.y}function i(c){c.nodes().forEach(u=>l(c.node(u))),c.edges().forEach(u=>{let d=c.edge(u);d.points.forEach(l),Object.hasOwn(d,"x")&&l(d)})}function l(c){let u=c.x;c.x=c.y,c.y=u}return Xne}var Jne,uUe;function YYn(){if(uUe)return Jne;uUe=1;let e=Dl();Jne=t;function t(n){let r={},s=n.nodes().filter(d=>!n.children(d).length),a=s.map(d=>n.node(d).rank),i=e.applyWithChunking(Math.max,a),l=e.range(i+1).map(()=>[]);function c(d){if(r[d])return;r[d]=!0;let f=n.node(d);l[f.rank].push(d),n.successors(d).forEach(c)}return s.sort((d,f)=>n.node(d).rank-n.node(f).rank).forEach(c),l}return Jne}var ere,dUe;function KYn(){if(dUe)return ere;dUe=1;let e=Dl().zipObject;ere=t;function t(r,s){let a=0;for(let i=1;i<s.length;++i)a+=n(r,s[i-1],s[i]);return a}function n(r,s,a){let i=e(a,a.map((h,p)=>p)),l=s.flatMap(h=>r.outEdges(h).map(p=>({pos:i[p.w],weight:r.edge(p).weight})).sort((p,m)=>p.pos-m.pos)),c=1;for(;c<a.length;)c<<=1;let u=2*c-1;c-=1;let d=new Array(u).fill(0),f=0;return l.forEach(h=>{let p=h.pos+c;d[p]+=h.weight;let m=0;for(;p>0;)p%2&&(m+=d[p+1]),p=p-1>>1,d[p]+=h.weight;f+=h.weight*m}),f}return ere}var tre,fUe;function XYn(){if(fUe)return tre;fUe=1,tre=e;function e(t,n=[]){return n.map(r=>{let s=t.inEdges(r);if(s.length){let a=s.reduce((i,l)=>{let c=t.edge(l),u=t.node(l.v);return{sum:i.sum+c.weight*u.order,weight:i.weight+c.weight}},{sum:0,weight:0});return{v:r,barycenter:a.sum/a.weight,weight:a.weight}}else return{v:r}})}return tre}var nre,hUe;function JYn(){if(hUe)return nre;hUe=1;let e=Dl();nre=t;function t(s,a){let i={};s.forEach((c,u)=>{let d=i[c.v]={indegree:0,in:[],out:[],vs:[c.v],i:u};c.barycenter!==void 0&&(d.barycenter=c.barycenter,d.weight=c.weight)}),a.edges().forEach(c=>{let u=i[c.v],d=i[c.w];u!==void 0&&d!==void 0&&(d.indegree++,u.out.push(i[c.w]))});let l=Object.values(i).filter(c=>!c.indegree);return n(l)}function n(s){let a=[];function i(c){return u=>{u.merged||(u.barycenter===void 0||c.barycenter===void 0||u.barycenter>=c.barycenter)&&r(c,u)}}function l(c){return u=>{u.in.push(c),--u.indegree===0&&s.push(u)}}for(;s.length;){let c=s.pop();a.push(c),c.in.reverse().forEach(i(c)),c.out.forEach(l(c))}return a.filter(c=>!c.merged).map(c=>e.pick(c,["vs","i","barycenter","weight"]))}function r(s,a){let i=0,l=0;s.weight&&(i+=s.barycenter*s.weight,l+=s.weight),a.weight&&(i+=a.barycenter*a.weight,l+=a.weight),s.vs=a.vs.concat(s.vs),s.barycenter=i/l,s.weight=l,s.i=Math.min(a.i,s.i),a.merged=!0}return nre}var rre,pUe;function eKn(){if(pUe)return rre;pUe=1;let e=Dl();rre=t;function t(s,a){let i=e.partition(s,m=>Object.hasOwn(m,"barycenter")),l=i.lhs,c=i.rhs.sort((m,v)=>v.i-m.i),u=[],d=0,f=0,h=0;l.sort(r(!!a)),h=n(u,c,h),l.forEach(m=>{h+=m.vs.length,u.push(m.vs),d+=m.barycenter*m.weight,f+=m.weight,h=n(u,c,h)});let p={vs:u.flat(!0)};return f&&(p.barycenter=d/f,p.weight=f),p}function n(s,a,i){let l;for(;a.length&&(l=a[a.length-1]).i<=i;)a.pop(),s.push(l.vs),i++;return i}function r(s){return(a,i)=>a.barycenter<i.barycenter?-1:a.barycenter>i.barycenter?1:s?i.i-a.i:a.i-i.i}return rre}var sre,mUe;function tKn(){if(mUe)return sre;mUe=1;let e=XYn(),t=JYn(),n=eKn();sre=r;function r(i,l,c,u){let d=i.children(l),f=i.node(l),h=f?f.borderLeft:void 0,p=f?f.borderRight:void 0,m={};h&&(d=d.filter(x=>x!==h&&x!==p));let v=e(i,d);v.forEach(x=>{if(i.children(x.v).length){let w=r(i,x.v,c,u);m[x.v]=w,Object.hasOwn(w,"barycenter")&&a(x,w)}});let y=t(v,c);s(y,m);let b=n(y,u);if(h&&(b.vs=[h,b.vs,p].flat(!0),i.predecessors(h).length)){let x=i.node(i.predecessors(h)[0]),w=i.node(i.predecessors(p)[0]);Object.hasOwn(b,"barycenter")||(b.barycenter=0,b.weight=0),b.barycenter=(b.barycenter*b.weight+x.order+w.order)/(b.weight+2),b.weight+=2}return b}function s(i,l){i.forEach(c=>{c.vs=c.vs.flatMap(u=>l[u]?l[u].vs:u)})}function a(i,l){i.barycenter!==void 0?(i.barycenter=(i.barycenter*i.weight+l.barycenter*l.weight)/(i.weight+l.weight),i.weight+=l.weight):(i.barycenter=l.barycenter,i.weight=l.weight)}return sre}var are,gUe;function nKn(){if(gUe)return are;gUe=1;let e=Gg().Graph,t=Dl();are=n;function n(s,a,i,l){l||(l=s.nodes());let c=r(s),u=new e({compound:!0}).setGraph({root:c}).setDefaultNodeLabel(d=>s.node(d));return l.forEach(d=>{let f=s.node(d),h=s.parent(d);(f.rank===a||f.minRank<=a&&a<=f.maxRank)&&(u.setNode(d),u.setParent(d,h||c),s[i](d).forEach(p=>{let m=p.v===d?p.w:p.v,v=u.edge(m,d),y=v!==void 0?v.weight:0;u.setEdge(m,d,{weight:s.edge(p).weight+y})}),Object.hasOwn(f,"minRank")&&u.setNode(d,{borderLeft:f.borderLeft[a],borderRight:f.borderRight[a]}))}),u}function r(s){for(var a;s.hasNode(a=t.uniqueId("_root")););return a}return are}var ire,vUe;function rKn(){if(vUe)return ire;vUe=1,ire=e;function e(t,n,r){let s={},a;r.forEach(i=>{let l=t.parent(i),c,u;for(;l;){if(c=t.parent(l),c?(u=s[c],s[c]=l):(u=a,a=l),u&&u!==l){n.setEdge(u,l);return}l=c}})}return ire}var ore,yUe;function sKn(){if(yUe)return ore;yUe=1;let e=YYn(),t=KYn(),n=tKn(),r=nKn(),s=rKn(),a=Gg().Graph,i=Dl();ore=l;function l(f,h){if(h&&typeof h.customOrder=="function"){h.customOrder(f,l);return}let p=i.maxRank(f),m=c(f,i.range(1,p+1),"inEdges"),v=c(f,i.range(p-1,-1,-1),"outEdges"),y=e(f);if(d(f,y),h&&h.disableOptimalOrderHeuristic)return;let b=Number.POSITIVE_INFINITY,x;for(let w=0,k=0;k<4;++w,++k){u(w%2?m:v,w%4>=2),y=i.buildLayerMatrix(f);let O=t(f,y);O<b&&(k=0,x=Object.assign({},y),b=O)}d(f,x)}function c(f,h,p){const m=new Map,v=(y,b)=>{m.has(y)||m.set(y,[]),m.get(y).push(b)};for(const y of f.nodes()){const b=f.node(y);if(typeof b.rank=="number"&&v(b.rank,y),typeof b.minRank=="number"&&typeof b.maxRank=="number")for(let x=b.minRank;x<=b.maxRank;x++)x!==b.rank&&v(x,y)}return h.map(function(y){return r(f,y,p,m.get(y)||[])})}function u(f,h){let p=new a;f.forEach(function(m){let v=m.graph().root,y=n(m,v,p,h);y.vs.forEach((b,x)=>m.node(b).order=x),s(m,p,y.vs)})}function d(f,h){Object.values(h).forEach(p=>p.forEach((m,v)=>f.node(m).order=v))}return ore}var lre,bUe;function aKn(){if(bUe)return lre;bUe=1;let e=Gg().Graph,t=Dl();lre={positionX:p,findType1Conflicts:n,findType2Conflicts:r,addConflict:a,hasConflict:i,verticalAlignment:l,horizontalCompaction:c,alignCoordinates:f,findSmallestWidthAlignment:d,balance:h};function n(y,b){let x={};function w(k,O){let _=0,T=0,E=k.length,N=O[O.length-1];return O.forEach((I,A)=>{let $=s(y,I),z=$?y.node($).order:E;($||I===N)&&(O.slice(T,A+1).forEach(D=>{y.predecessors(D).forEach(q=>{let H=y.node(q),V=H.order;(V<_||z<V)&&!(H.dummy&&y.node(D).dummy)&&a(x,q,D)})}),T=A+1,_=z)}),O}return b.length&&b.reduce(w),x}function r(y,b){let x={};function w(O,_,T,E,N){let I;t.range(_,T).forEach(A=>{I=O[A],y.node(I).dummy&&y.predecessors(I).forEach($=>{let z=y.node($);z.dummy&&(z.order<E||z.order>N)&&a(x,$,I)})})}function k(O,_){let T=-1,E,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let $=y.predecessors(I);$.length&&(E=y.node($[0]).order,w(_,N,A,T,E),N=A,T=E)}w(_,N,_.length,E,O.length)}),_}return b.length&&b.reduce(k),x}function s(y,b){if(y.node(b).dummy)return y.predecessors(b).find(x=>y.node(x).dummy)}function a(y,b,x){if(b>x){let k=b;b=x,x=k}let w=y[b];w||(y[b]=w={}),w[x]=!0}function i(y,b,x){if(b>x){let w=b;b=x,x=w}return!!y[b]&&Object.hasOwn(y[b],x)}function l(y,b,x,w){let k={},O={},_={};return b.forEach(T=>{T.forEach((E,N)=>{k[E]=E,O[E]=E,_[E]=N})}),b.forEach(T=>{let E=-1;T.forEach(N=>{let I=w(N);if(I.length){I=I.sort(($,z)=>_[$]-_[z]);let A=(I.length-1)/2;for(let $=Math.floor(A),z=Math.ceil(A);$<=z;++$){let D=I[$];O[N]===N&&E<_[D]&&!i(x,N,D)&&(O[D]=N,O[N]=k[N]=k[D],E=_[D])}}})}),{root:k,align:O}}function c(y,b,x,w,k){let O={},_=u(y,b,x,k),T=k?"borderLeft":"borderRight";function E(A,$){let z=_.nodes(),D=z.pop(),q={};for(;D;)q[D]?A(D):(q[D]=!0,z.push(D),z=z.concat($(D))),D=z.pop()}function N(A){O[A]=_.inEdges(A).reduce(($,z)=>Math.max($,O[z.v]+_.edge(z)),0)}function I(A){let $=_.outEdges(A).reduce((D,q)=>Math.min(D,O[q.w]-_.edge(q)),Number.POSITIVE_INFINITY),z=y.node(A);$!==Number.POSITIVE_INFINITY&&z.borderType!==T&&(O[A]=Math.max(O[A],$))}return E(N,_.predecessors.bind(_)),E(I,_.successors.bind(_)),Object.keys(w).forEach(A=>O[A]=O[x[A]]),O}function u(y,b,x,w){let k=new e,O=y.graph(),_=m(O.nodesep,O.edgesep,w);return b.forEach(T=>{let E;T.forEach(N=>{let I=x[N];if(k.setNode(I),E){var A=x[E],$=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,E),$||0))}E=N})}),k}function d(y,b){return Object.values(b).reduce((x,w)=>{let k=Number.NEGATIVE_INFINITY,O=Number.POSITIVE_INFINITY;Object.entries(w).forEach(([T,E])=>{let N=v(y,T)/2;k=Math.max(E+N,k),O=Math.min(E-N,O)});const _=k-O;return _<x[0]&&(x=[_,w]),x},[Number.POSITIVE_INFINITY,null])[1]}function f(y,b){let x=Object.values(b),w=t.applyWithChunking(Math.min,x),k=t.applyWithChunking(Math.max,x);["u","d"].forEach(O=>{["l","r"].forEach(_=>{let T=O+_,E=y[T];if(E===b)return;let N=Object.values(E),I=w-t.applyWithChunking(Math.min,N);_!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[T]=t.mapValues(E,A=>A+I))})})}function h(y,b){return t.mapValues(y.ul,(x,w)=>{if(b)return y[b.toLowerCase()][w];{let k=Object.values(y).map(O=>O[w]).sort((O,_)=>O-_);return(k[1]+k[2])/2}})}function p(y){let b=t.buildLayerMatrix(y),x=Object.assign(n(y,b),r(y,b)),w={},k;["u","d"].forEach(_=>{k=_==="u"?b:Object.values(b).reverse(),["l","r"].forEach(T=>{T==="r"&&(k=k.map(A=>Object.values(A).reverse()));let E=(_==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,E),I=c(y,k,N.root,N.align,T==="r");T==="r"&&(I=t.mapValues(I,A=>-A)),w[_+T]=I})});let O=d(y,w);return f(w,O),h(w,y.graph().align)}function m(y,b,x){return(w,k,O)=>{let _=w.node(k),T=w.node(O),E=0,N;if(E+=_.width/2,Object.hasOwn(_,"labelpos"))switch(_.labelpos.toLowerCase()){case"l":N=-_.width/2;break;case"r":N=_.width/2;break}if(N&&(E+=x?N:-N),N=0,E+=(_.dummy?b:y)/2,E+=(T.dummy?b:y)/2,E+=T.width/2,Object.hasOwn(T,"labelpos"))switch(T.labelpos.toLowerCase()){case"l":N=T.width/2;break;case"r":N=-T.width/2;break}return N&&(E+=x?N:-N),N=0,E}}function v(y,b){return y.node(b).width}return lre}var cre,xUe;function iKn(){if(xUe)return cre;xUe=1;let e=Dl(),t=aKn().positionX;cre=n;function n(s){s=e.asNonCompoundGraph(s),r(s),Object.entries(t(s)).forEach(([a,i])=>s.node(a).x=i)}function r(s){let a=e.buildLayerMatrix(s),i=s.graph().ranksep,l=0;a.forEach(c=>{const u=c.reduce((d,f)=>{const h=s.node(f).height;return d>h?d:h},0);c.forEach(d=>s.node(d).y=l+u/2),l+=u+i})}return cre}var ure,wUe;function oKn(){if(wUe)return ure;wUe=1;let e=UYn(),t=qYn(),n=HYn(),r=Dl().normalizeRanks,s=WYn(),a=Dl().removeEmptyRanks,i=ZYn(),l=GYn(),c=QYn(),u=sKn(),d=iKn(),f=Dl(),h=Gg().Graph;ure=p;function p(R,F){let U=F&&F.debugTiming?f.time:f.notime;U("layout",()=>{let Q=U(" buildLayoutGraph",()=>E(R));U(" runLayout",()=>m(Q,U,F)),U(" updateInputGraph",()=>v(R,Q))})}function m(R,F,U){F(" makeSpaceForEdgeLabels",()=>N(R)),F(" removeSelfEdges",()=>B(R)),F(" acyclic",()=>e.run(R)),F(" nestingGraph.run",()=>i.run(R)),F(" rank",()=>n(f.asNonCompoundGraph(R))),F(" injectEdgeLabelProxies",()=>I(R)),F(" removeEmptyRanks",()=>a(R)),F(" nestingGraph.cleanup",()=>i.cleanup(R)),F(" normalizeRanks",()=>r(R)),F(" assignRankMinMax",()=>A(R)),F(" removeEdgeLabelProxies",()=>$(R)),F(" normalize.run",()=>t.run(R)),F(" parentDummyChains",()=>s(R)),F(" addBorderSegments",()=>l(R)),F(" order",()=>u(R,U)),F(" insertSelfEdges",()=>W(R)),F(" adjustCoordinateSystem",()=>c.adjust(R)),F(" position",()=>d(R)),F(" positionSelfEdges",()=>L(R)),F(" removeBorderNodes",()=>V(R)),F(" normalize.undo",()=>t.undo(R)),F(" fixupEdgeLabelCoords",()=>q(R)),F(" undoCoordinateSystem",()=>c.undo(R)),F(" translateGraph",()=>z(R)),F(" assignNodeIntersects",()=>D(R)),F(" reversePoints",()=>H(R)),F(" acyclic.undo",()=>e.undo(R))}function v(R,F){R.nodes().forEach(U=>{let Q=R.node(U),te=F.node(U);Q&&(Q.x=te.x,Q.y=te.y,Q.rank=te.rank,F.children(U).length&&(Q.width=te.width,Q.height=te.height))}),R.edges().forEach(U=>{let Q=R.edge(U),te=F.edge(U);Q.points=te.points,Object.hasOwn(te,"x")&&(Q.x=te.x,Q.y=te.y)}),R.graph().width=F.graph().width,R.graph().height=F.graph().height}let y=["nodesep","edgesep","ranksep","marginx","marginy"],b={ranksep:50,edgesep:20,nodesep:50,rankdir:"tb"},x=["acyclicer","ranker","rankdir","align"],w=["width","height","rank"],k={width:0,height:0},O=["minlen","weight","width","height","labeloffset"],_={minlen:1,weight:1,width:0,height:0,labeloffset:10,labelpos:"r"},T=["labelpos"];function E(R){let F=new h({multigraph:!0,compound:!0}),U=M(R.graph());return F.setGraph(Object.assign({},b,G(U,y),f.pick(U,x))),R.nodes().forEach(Q=>{let te=M(R.node(Q));const J=G(te,w);Object.keys(k).forEach(ee=>{J[ee]===void 0&&(J[ee]=k[ee])}),F.setNode(Q,J),F.setParent(Q,R.parent(Q))}),R.edges().forEach(Q=>{let te=M(R.edge(Q));F.setEdge(Q,Object.assign({},_,G(te,O),f.pick(te,T)))}),F}function N(R){let F=R.graph();F.ranksep/=2,R.edges().forEach(U=>{let Q=R.edge(U);Q.minlen*=2,Q.labelpos.toLowerCase()!=="c"&&(F.rankdir==="TB"||F.rankdir==="BT"?Q.width+=Q.labeloffset:Q.height+=Q.labeloffset)})}function I(R){R.edges().forEach(F=>{let U=R.edge(F);if(U.width&&U.height){let Q=R.node(F.v),J={rank:(R.node(F.w).rank-Q.rank)/2+Q.rank,e:F};f.addDummyNode(R,"edge-proxy",J,"_ep")}})}function A(R){let F=0;R.nodes().forEach(U=>{let Q=R.node(U);Q.borderTop&&(Q.minRank=R.node(Q.borderTop).rank,Q.maxRank=R.node(Q.borderBottom).rank,F=Math.max(F,Q.maxRank))}),R.graph().maxRank=F}function $(R){R.nodes().forEach(F=>{let U=R.node(F);U.dummy==="edge-proxy"&&(R.edge(U.e).labelRank=U.rank,R.removeNode(F))})}function z(R){let F=Number.POSITIVE_INFINITY,U=0,Q=Number.POSITIVE_INFINITY,te=0,J=R.graph(),ee=J.marginx||0,re=J.marginy||0;function ae(X){let ne=X.x,se=X.y,ce=X.width,le=X.height;F=Math.min(F,ne-ce/2),U=Math.max(U,ne+ce/2),Q=Math.min(Q,se-le/2),te=Math.max(te,se+le/2)}R.nodes().forEach(X=>ae(R.node(X))),R.edges().forEach(X=>{let ne=R.edge(X);Object.hasOwn(ne,"x")&&ae(ne)}),F-=ee,Q-=re,R.nodes().forEach(X=>{let ne=R.node(X);ne.x-=F,ne.y-=Q}),R.edges().forEach(X=>{let ne=R.edge(X);ne.points.forEach(se=>{se.x-=F,se.y-=Q}),Object.hasOwn(ne,"x")&&(ne.x-=F),Object.hasOwn(ne,"y")&&(ne.y-=Q)}),J.width=U-F+ee,J.height=te-Q+re}function D(R){R.edges().forEach(F=>{let U=R.edge(F),Q=R.node(F.v),te=R.node(F.w),J,ee;U.points?(J=U.points[0],ee=U.points[U.points.length-1]):(U.points=[],J=te,ee=Q),U.points.unshift(f.intersectRect(Q,J)),U.points.push(f.intersectRect(te,ee))})}function q(R){R.edges().forEach(F=>{let U=R.edge(F);if(Object.hasOwn(U,"x"))switch((U.labelpos==="l"||U.labelpos==="r")&&(U.width-=U.labeloffset),U.labelpos){case"l":U.x-=U.width/2+U.labeloffset;break;case"r":U.x+=U.width/2+U.labeloffset;break}})}function H(R){R.edges().forEach(F=>{let U=R.edge(F);U.reversed&&U.points.reverse()})}function V(R){R.nodes().forEach(F=>{if(R.children(F).length){let U=R.node(F),Q=R.node(U.borderTop),te=R.node(U.borderBottom),J=R.node(U.borderLeft[U.borderLeft.length-1]),ee=R.node(U.borderRight[U.borderRight.length-1]);U.width=Math.abs(ee.x-J.x),U.height=Math.abs(te.y-Q.y),U.x=J.x+U.width/2,U.y=Q.y+U.height/2}}),R.nodes().forEach(F=>{R.node(F).dummy==="border"&&R.removeNode(F)})}function B(R){R.edges().forEach(F=>{if(F.v===F.w){var U=R.node(F.v);U.selfEdges||(U.selfEdges=[]),U.selfEdges.push({e:F,label:R.edge(F)}),R.removeEdge(F)}})}function W(R){var F=f.buildLayerMatrix(R);F.forEach(U=>{var Q=0;U.forEach((te,J)=>{var ee=R.node(te);ee.order=J+Q,(ee.selfEdges||[]).forEach(re=>{f.addDummyNode(R,"selfedge",{width:re.label.width,height:re.label.height,rank:ee.rank,order:J+ ++Q,e:re.e,label:re.label},"_se")}),delete ee.selfEdges})})}function L(R){R.nodes().forEach(F=>{var U=R.node(F);if(U.dummy==="selfedge"){var Q=R.node(U.e.v),te=Q.x+Q.width/2,J=Q.y,ee=U.x-te,re=Q.height/2;R.setEdge(U.e,U.label),R.removeNode(F),U.label.points=[{x:te+2*ee/3,y:J-re},{x:te+5*ee/6,y:J-re},{x:te+ee,y:J},{x:te+5*ee/6,y:J+re},{x:te+2*ee/3,y:J+re}],U.label.x=U.x,U.label.y=U.y}})}function G(R,F){return f.mapValues(f.pick(R,F),Number)}function M(R){var F={};return R&&Object.entries(R).forEach(([U,Q])=>{typeof U=="string"&&(U=U.toLowerCase()),F[U]=Q}),F}return ure}var dre,SUe;function lKn(){if(SUe)return dre;SUe=1;let e=Dl(),t=Gg().Graph;dre={debugOrdering:n};function n(r){let s=e.buildLayerMatrix(r),a=new t({compound:!0,multigraph:!0}).setGraph({});return r.nodes().forEach(i=>{a.setNode(i,{label:i}),a.setParent(i,"layer"+r.node(i).rank)}),r.edges().forEach(i=>a.setEdge(i.v,i.w,{},i.name)),s.forEach((i,l)=>{let c="layer"+l;a.setNode(c,{rank:"same"}),i.reduce((u,d)=>(a.setEdge(u,d,{style:"invis"}),d))}),a}return dre}var fre,kUe;function cKn(){return kUe||(kUe=1,fre="1.1.8"),fre}var hre,OUe;function uKn(){return OUe||(OUe=1,hre={graphlib:Gg(),layout:oKn(),debug:lKn(),util:{time:Dl().time,notime:Dl().notime},version:cKn()}),hre}var dKn=uKn();const CUe=Hl(dKn);function Gl(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=Gl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var fKn={value:()=>{}};function cZ(){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 L9(n)}function L9(e){this._=e}function hKn(e,t){return e.trim().split(/^|\s+/).map(function(n){var r="",s=n.indexOf(".");if(s>=0&&(r=n.slice(s+1),n=n.slice(0,s)),n&&!t.hasOwnProperty(n))throw new Error("unknown type: "+n);return{type:n,name:r}})}L9.prototype=cZ.prototype={constructor:L9,on:function(e,t){var n=this._,r=hKn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=pKn(n[s],e.name)))return s;return}if(t!=null&&typeof t!="function")throw new Error("invalid callback: "+t);for(;++a<i;)if(s=(e=r[a]).type)n[s]=_Ue(n[s],e.name,t);else if(t==null)for(s in n)n[s]=_Ue(n[s],e.name,null);return this},copy:function(){var e={},t=this._;for(var n in t)e[n]=t[n].slice();return new L9(e)},call:function(e,t){if((s=arguments.length-2)>0)for(var n=new Array(s),r=0,s,a;r<s;++r)n[r]=arguments[r+2];if(!this._.hasOwnProperty(e))throw new Error("unknown type: "+e);for(a=this._[e],r=0,s=a.length;r<s;++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],s=0,a=r.length;s<a;++s)r[s].value.apply(t,n)}};function pKn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function _Ue(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=fKn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Bye="http://www.w3.org/1999/xhtml";const EUe={svg:"http://www.w3.org/2000/svg",xhtml:Bye,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function uZ(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),EUe.hasOwnProperty(t)?{space:EUe[t],local:e}:e}function mKn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Bye&&t.documentElement.namespaceURI===Bye?t.createElement(e):t.createElementNS(n,e)}}function gKn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function q_t(e){var t=uZ(e);return(t.local?gKn:mKn)(t)}function vKn(){}function YCe(e){return e==null?vKn:function(){return this.querySelector(e)}}function yKn(e){typeof e!="function"&&(e=YCe(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=new Array(i),c,u,d=0;d<i;++d)(c=a[d])&&(u=e.call(c,c.__data__,d,a))&&("__data__"in c&&(u.__data__=c.__data__),l[d]=u);return new np(r,this._parents)}function bKn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function xKn(){return[]}function V_t(e){return e==null?xKn:function(){return this.querySelectorAll(e)}}function wKn(e){return function(){return bKn(e.apply(this,arguments))}}function SKn(e){typeof e=="function"?e=wKn(e):e=V_t(e);for(var t=this._groups,n=t.length,r=[],s=[],a=0;a<n;++a)for(var i=t[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&(r.push(e.call(c,c.__data__,u,i)),s.push(c));return new np(r,s)}function H_t(e){return function(){return this.matches(e)}}function W_t(e){return function(t){return t.matches(e)}}var kKn=Array.prototype.find;function OKn(e){return function(){return kKn.call(this.children,e)}}function CKn(){return this.firstElementChild}function _Kn(e){return this.select(e==null?CKn:OKn(typeof e=="function"?e:W_t(e)))}var EKn=Array.prototype.filter;function TKn(){return Array.from(this.children)}function jKn(e){return function(){return EKn.call(this.children,e)}}function NKn(e){return this.selectAll(e==null?TKn:jKn(typeof e=="function"?e:W_t(e)))}function IKn(e){typeof e!="function"&&(e=H_t(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new np(r,this._parents)}function Z_t(e){return new Array(e.length)}function AKn(){return new np(this._enter||this._groups.map(Z_t),this._parents)}function HU(e,t){this.ownerDocument=e.ownerDocument,this.namespaceURI=e.namespaceURI,this._next=null,this._parent=e,this.__data__=t}HU.prototype={constructor:HU,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 RKn(e){return function(){return e}}function PKn(e,t,n,r,s,a){for(var i=0,l,c=t.length,u=a.length;i<u;++i)(l=t[i])?(l.__data__=a[i],r[i]=l):n[i]=new HU(e,a[i]);for(;i<c;++i)(l=t[i])&&(s[i]=l)}function $Kn(e,t,n,r,s,a,i){var l,c,u=new Map,d=t.length,f=a.length,h=new Array(d),p;for(l=0;l<d;++l)(c=t[l])&&(h[l]=p=i.call(c,c.__data__,l,t)+"",u.has(p)?s[l]=c:u.set(p,c));for(l=0;l<f;++l)p=i.call(e,a[l],l,a)+"",(c=u.get(p))?(r[l]=c,c.__data__=a[l],u.delete(p)):n[l]=new HU(e,a[l]);for(l=0;l<d;++l)(c=t[l])&&u.get(h[l])===c&&(s[l]=c)}function MKn(e){return e.__data__}function DKn(e,t){if(!arguments.length)return Array.from(this,MKn);var n=t?$Kn:PKn,r=this._parents,s=this._groups;typeof e!="function"&&(e=RKn(e));for(var a=s.length,i=new Array(a),l=new Array(a),c=new Array(a),u=0;u<a;++u){var d=r[u],f=s[u],h=f.length,p=LKn(e.call(d,d&&d.__data__,u,r)),m=p.length,v=l[u]=new Array(m),y=i[u]=new Array(m),b=c[u]=new Array(h);n(d,f,v,y,b,p,t);for(var x=0,w=0,k,O;x<m;++x)if(k=v[x]){for(x>=w&&(w=x+1);!(O=y[w])&&++w<m;);k._next=O||null}}return i=new np(i,r),i._enter=l,i._exit=c,i}function LKn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function FKn(){return new np(this._exit||this._groups.map(Z_t),this._parents)}function zKn(e,t,n){var r=this.enter(),s=this,a=this.exit();return typeof e=="function"?(r=e(r),r&&(r=r.selection())):r=r.append(e+""),t!=null&&(s=t(s),s&&(s=s.selection())),n==null?a.remove():n(a),r&&s?r.merge(s).order():s}function BKn(e){for(var t=e.selection?e.selection():e,n=this._groups,r=t._groups,s=n.length,a=r.length,i=Math.min(s,a),l=new Array(s),c=0;c<i;++c)for(var u=n[c],d=r[c],f=u.length,h=l[c]=new Array(f),p,m=0;m<f;++m)(p=u[m]||d[m])&&(h[m]=p);for(;c<s;++c)l[c]=n[c];return new np(l,this._parents)}function UKn(){for(var e=this._groups,t=-1,n=e.length;++t<n;)for(var r=e[t],s=r.length-1,a=r[s],i;--s>=0;)(i=r[s])&&(a&&i.compareDocumentPosition(a)^4&&a.parentNode.insertBefore(i,a),a=i);return this}function qKn(e){e||(e=VKn);function t(f,h){return f&&h?e(f.__data__,h.__data__):!f-!h}for(var n=this._groups,r=n.length,s=new Array(r),a=0;a<r;++a){for(var i=n[a],l=i.length,c=s[a]=new Array(l),u,d=0;d<l;++d)(u=i[d])&&(c[d]=u);c.sort(t)}return new np(s,this._parents).order()}function VKn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function HKn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function WKn(){return Array.from(this)}function ZKn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length;s<a;++s){var i=r[s];if(i)return i}return null}function GKn(){let e=0;for(const t of this)++e;return e}function QKn(){return!this.node()}function YKn(e){for(var t=this._groups,n=0,r=t.length;n<r;++n)for(var s=t[n],a=0,i=s.length,l;a<i;++a)(l=s[a])&&e.call(l,l.__data__,a,s);return this}function KKn(e){return function(){this.removeAttribute(e)}}function XKn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function JKn(e,t){return function(){this.setAttribute(e,t)}}function eXn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function tXn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function nXn(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 rXn(e,t){var n=uZ(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?XKn:KKn:typeof t=="function"?n.local?nXn:tXn:n.local?eXn:JKn)(n,t))}function G_t(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function sXn(e){return function(){this.style.removeProperty(e)}}function aXn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function iXn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function oXn(e,t,n){return arguments.length>1?this.each((t==null?sXn:typeof t=="function"?iXn:aXn)(e,t,n??"")):ON(this.node(),e)}function ON(e,t){return e.style.getPropertyValue(t)||G_t(e).getComputedStyle(e,null).getPropertyValue(t)}function lXn(e){return function(){delete this[e]}}function cXn(e,t){return function(){this[e]=t}}function uXn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function dXn(e,t){return arguments.length>1?this.each((t==null?lXn:typeof t=="function"?uXn:cXn)(e,t)):this.node()[e]}function Q_t(e){return e.trim().split(/^|\s+/)}function KCe(e){return e.classList||new Y_t(e)}function Y_t(e){this._node=e,this._names=Q_t(e.getAttribute("class")||"")}Y_t.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 K_t(e,t){for(var n=KCe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function X_t(e,t){for(var n=KCe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function fXn(e){return function(){K_t(this,e)}}function hXn(e){return function(){X_t(this,e)}}function pXn(e,t){return function(){(t.apply(this,arguments)?K_t:X_t)(this,e)}}function mXn(e,t){var n=Q_t(e+"");if(arguments.length<2){for(var r=KCe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?pXn:t?fXn:hXn)(n,t))}function gXn(){this.textContent=""}function vXn(e){return function(){this.textContent=e}}function yXn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function bXn(e){return arguments.length?this.each(e==null?gXn:(typeof e=="function"?yXn:vXn)(e)):this.node().textContent}function xXn(){this.innerHTML=""}function wXn(e){return function(){this.innerHTML=e}}function SXn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function kXn(e){return arguments.length?this.each(e==null?xXn:(typeof e=="function"?SXn:wXn)(e)):this.node().innerHTML}function OXn(){this.nextSibling&&this.parentNode.appendChild(this)}function CXn(){return this.each(OXn)}function _Xn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function EXn(){return this.each(_Xn)}function TXn(e){var t=typeof e=="function"?e:q_t(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function jXn(){return null}function NXn(e,t){var n=typeof e=="function"?e:q_t(e),r=t==null?jXn:typeof t=="function"?t:YCe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function IXn(){var e=this.parentNode;e&&e.removeChild(this)}function AXn(){return this.each(IXn)}function RXn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function PXn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function $Xn(e){return this.select(e?PXn:RXn)}function MXn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function DXn(e){return function(t){e.call(this,t,this.__data__)}}function LXn(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 FXn(e){return function(){var t=this.__on;if(t){for(var n=0,r=-1,s=t.length,a;n<s;++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 zXn(e,t,n){return function(){var r=this.__on,s,a=DXn(t);if(r){for(var i=0,l=r.length;i<l;++i)if((s=r[i]).type===e.type&&s.name===e.name){this.removeEventListener(s.type,s.listener,s.options),this.addEventListener(s.type,s.listener=a,s.options=n),s.value=t;return}}this.addEventListener(e.type,a,n),s={type:e.type,name:e.name,value:t,listener:a,options:n},r?r.push(s):this.__on=[s]}}function BXn(e,t,n){var r=LXn(e+""),s,a=r.length,i;if(arguments.length<2){var l=this.node().__on;if(l){for(var c=0,u=l.length,d;c<u;++c)for(s=0,d=l[c];s<a;++s)if((i=r[s]).type===d.type&&i.name===d.name)return d.value}return}for(l=t?zXn:FXn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function J_t(e,t,n){var r=G_t(e),s=r.CustomEvent;typeof s=="function"?s=new s(t,n):(s=r.document.createEvent("Event"),n?(s.initEvent(t,n.bubbles,n.cancelable),s.detail=n.detail):s.initEvent(t,!1,!1)),e.dispatchEvent(s)}function UXn(e,t){return function(){return J_t(this,e,t)}}function qXn(e,t){return function(){return J_t(this,e,t.apply(this,arguments))}}function VXn(e,t){return this.each((typeof t=="function"?qXn:UXn)(e,t))}function*HXn(){for(var e=this._groups,t=0,n=e.length;t<n;++t)for(var r=e[t],s=0,a=r.length,i;s<a;++s)(i=r[s])&&(yield i)}var eEt=[null];function np(e,t){this._groups=e,this._parents=t}function PL(){return new np([[document.documentElement]],eEt)}function WXn(){return this}np.prototype=PL.prototype={constructor:np,select:yKn,selectAll:SKn,selectChild:_Kn,selectChildren:NKn,filter:IKn,data:DKn,enter:AKn,exit:FKn,join:zKn,merge:BKn,selection:WXn,order:UKn,sort:qKn,call:HKn,nodes:WKn,node:ZKn,size:GKn,empty:QKn,each:YKn,attr:rXn,style:oXn,property:dXn,classed:mXn,text:bXn,html:kXn,raise:CXn,lower:EXn,append:TXn,insert:NXn,remove:AXn,clone:$Xn,datum:MXn,on:BXn,dispatch:VXn,[Symbol.iterator]:HXn};function Ah(e){return typeof e=="string"?new np([[document.querySelector(e)]],[document.documentElement]):new np([[e]],eEt)}function ZXn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function yg(e,t){if(e=ZXn(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 s=t.getBoundingClientRect();return[e.clientX-s.left-t.clientLeft,e.clientY-s.top-t.clientTop]}}return[e.pageX,e.pageY]}const GXn={passive:!1},pD={capture:!0,passive:!1};function pre(e){e.stopImmediatePropagation()}function Aj(e){e.preventDefault(),e.stopImmediatePropagation()}function tEt(e){var t=e.document.documentElement,n=Ah(e).on("dragstart.drag",Aj,pD);"onselectstart"in t?n.on("selectstart.drag",Aj,pD):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function nEt(e,t){var n=e.document.documentElement,r=Ah(e).on("dragstart.drag",null);t&&(r.on("click.drag",Aj,pD),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 rz=e=>()=>e;function Uye(e,{sourceEvent:t,subject:n,target:r,identifier:s,active:a,x:i,y:l,dx:c,dy:u,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:s,enumerable:!0,configurable:!0},active:{value:a,enumerable:!0,configurable:!0},x:{value:i,enumerable:!0,configurable:!0},y:{value:l,enumerable:!0,configurable:!0},dx:{value:c,enumerable:!0,configurable:!0},dy:{value:u,enumerable:!0,configurable:!0},_:{value:d}})}Uye.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function QXn(e){return!e.ctrlKey&&!e.button}function YXn(){return this.parentNode}function KXn(e,t){return t??{x:e.x,y:e.y}}function XXn(){return navigator.maxTouchPoints||"ontouchstart"in this}function rEt(){var e=QXn,t=YXn,n=KXn,r=XXn,s={},a=cZ("start","drag","end"),i=0,l,c,u,d,f=0;function h(k){k.on("mousedown.drag",p).filter(r).on("touchstart.drag",y).on("touchmove.drag",b,GXn).on("touchend.drag touchcancel.drag",x).style("touch-action","none").style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}function p(k,O){if(!(d||!e.call(this,k,O))){var _=w(this,t.call(this,k,O),k,O,"mouse");_&&(Ah(k.view).on("mousemove.drag",m,pD).on("mouseup.drag",v,pD),tEt(k.view),pre(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(Aj(k),!u){var O=k.clientX-l,_=k.clientY-c;u=O*O+_*_>f}s.mouse("drag",k)}function v(k){Ah(k.view).on("mousemove.drag mouseup.drag",null),nEt(k.view,u),Aj(k),s.mouse("end",k)}function y(k,O){if(e.call(this,k,O)){var _=k.changedTouches,T=t.call(this,k,O),E=_.length,N,I;for(N=0;N<E;++N)(I=w(this,T,k,O,_[N].identifier,_[N]))&&(pre(k),I("start",k,_[N]))}}function b(k){var O=k.changedTouches,_=O.length,T,E;for(T=0;T<_;++T)(E=s[O[T].identifier])&&(Aj(k),E("drag",k,O[T]))}function x(k){var O=k.changedTouches,_=O.length,T,E;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),T=0;T<_;++T)(E=s[O[T].identifier])&&(pre(k),E("end",k,O[T]))}function w(k,O,_,T,E,N){var I=a.copy(),A=yg(N||_,O),$,z,D;if((D=n.call(k,new Uye("beforestart",{sourceEvent:_,target:h,identifier:E,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),T))!=null)return $=D.x-A[0]||0,z=D.y-A[1]||0,function q(H,V,B){var W=A,L;switch(H){case"start":s[E]=q,L=i++;break;case"end":delete s[E],--i;case"drag":A=yg(B||V,O),L=i;break}I.call(H,k,new Uye(H,{sourceEvent:V,subject:D,target:h,identifier:E,active:L,x:A[0]+$,y:A[1]+z,dx:A[0]-W[0],dy:A[1]-W[1],dispatch:I}),T)}}return h.filter=function(k){return arguments.length?(e=typeof k=="function"?k:rz(!!k),h):e},h.container=function(k){return arguments.length?(t=typeof k=="function"?k:rz(k),h):t},h.subject=function(k){return arguments.length?(n=typeof k=="function"?k:rz(k),h):n},h.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:rz(!!k),h):r},h.on=function(){var k=a.on.apply(a,arguments);return k===a?h:k},h.clickDistance=function(k){return arguments.length?(f=(k=+k)*k,h):Math.sqrt(f)},h}function XCe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function sEt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function $L(){}var mD=.7,WU=1/mD,Rj="\\s*([+-]?\\d+)\\s*",gD="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",ky="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",JXn=/^#([0-9a-f]{3,8})$/,eJn=new RegExp(`^rgb\\(${Rj},${Rj},${Rj}\\)$`),tJn=new RegExp(`^rgb\\(${ky},${ky},${ky}\\)$`),nJn=new RegExp(`^rgba\\(${Rj},${Rj},${Rj},${gD}\\)$`),rJn=new RegExp(`^rgba\\(${ky},${ky},${ky},${gD}\\)$`),sJn=new RegExp(`^hsl\\(${gD},${ky},${ky}\\)$`),aJn=new RegExp(`^hsla\\(${gD},${ky},${ky},${gD}\\)$`),TUe={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074};XCe($L,wC,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:jUe,formatHex:jUe,formatHex8:iJn,formatHsl:oJn,formatRgb:NUe,toString:NUe});function jUe(){return this.rgb().formatHex()}function iJn(){return this.rgb().formatHex8()}function oJn(){return aEt(this).formatHsl()}function NUe(){return this.rgb().formatRgb()}function wC(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=JXn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?IUe(t):n===3?new Nf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?sz(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?sz(t>>12&15|t>>8&240,t>>8&15|t>>4&240,t>>4&15|t&240,((t&15)<<4|t&15)/255):null):(t=eJn.exec(e))?new Nf(t[1],t[2],t[3],1):(t=tJn.exec(e))?new Nf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=nJn.exec(e))?sz(t[1],t[2],t[3],t[4]):(t=rJn.exec(e))?sz(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=sJn.exec(e))?PUe(t[1],t[2]/100,t[3]/100,1):(t=aJn.exec(e))?PUe(t[1],t[2]/100,t[3]/100,t[4]):TUe.hasOwnProperty(e)?IUe(TUe[e]):e==="transparent"?new Nf(NaN,NaN,NaN,0):null}function IUe(e){return new Nf(e>>16&255,e>>8&255,e&255,1)}function sz(e,t,n,r){return r<=0&&(e=t=n=NaN),new Nf(e,t,n,r)}function lJn(e){return e instanceof $L||(e=wC(e)),e?(e=e.rgb(),new Nf(e.r,e.g,e.b,e.opacity)):new Nf}function qye(e,t,n,r){return arguments.length===1?lJn(e):new Nf(e,t,n,r??1)}function Nf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}XCe(Nf,qye,sEt($L,{brighter(e){return e=e==null?WU:Math.pow(WU,e),new Nf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?mD:Math.pow(mD,e),new Nf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new Nf(EO(this.r),EO(this.g),EO(this.b),ZU(this.opacity))},displayable(){return-.5<=this.r&&this.r<255.5&&-.5<=this.g&&this.g<255.5&&-.5<=this.b&&this.b<255.5&&0<=this.opacity&&this.opacity<=1},hex:AUe,formatHex:AUe,formatHex8:cJn,formatRgb:RUe,toString:RUe}));function AUe(){return`#${oO(this.r)}${oO(this.g)}${oO(this.b)}`}function cJn(){return`#${oO(this.r)}${oO(this.g)}${oO(this.b)}${oO((isNaN(this.opacity)?1:this.opacity)*255)}`}function RUe(){const e=ZU(this.opacity);return`${e===1?"rgb(":"rgba("}${EO(this.r)}, ${EO(this.g)}, ${EO(this.b)}${e===1?")":`, ${e})`}`}function ZU(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function EO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function oO(e){return e=EO(e),(e<16?"0":"")+e.toString(16)}function PUe(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new Cg(e,t,n,r)}function aEt(e){if(e instanceof Cg)return new Cg(e.h,e.s,e.l,e.opacity);if(e instanceof $L||(e=wC(e)),!e)return new Cg;if(e instanceof Cg)return e;e=e.rgb();var t=e.r/255,n=e.g/255,r=e.b/255,s=Math.min(t,n,r),a=Math.max(t,n,r),i=NaN,l=a-s,c=(a+s)/2;return l?(t===a?i=(n-r)/l+(n<r)*6:n===a?i=(r-t)/l+2:i=(t-n)/l+4,l/=c<.5?a+s:2-a-s,i*=60):l=c>0&&c<1?0:i,new Cg(i,l,c,e.opacity)}function uJn(e,t,n,r){return arguments.length===1?aEt(e):new Cg(e,t,n,r??1)}function Cg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}XCe(Cg,uJn,sEt($L,{brighter(e){return e=e==null?WU:Math.pow(WU,e),new Cg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?mD:Math.pow(mD,e),new Cg(this.h,this.s,this.l*e,this.opacity)},rgb(){var e=this.h%360+(this.h<0)*360,t=isNaN(e)||isNaN(this.s)?0:this.s,n=this.l,r=n+(n<.5?n:1-n)*t,s=2*n-r;return new Nf(mre(e>=240?e-240:e+120,s,r),mre(e,s,r),mre(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new Cg($Ue(this.h),az(this.s),az(this.l),ZU(this.opacity))},displayable(){return(0<=this.s&&this.s<=1||isNaN(this.s))&&0<=this.l&&this.l<=1&&0<=this.opacity&&this.opacity<=1},formatHsl(){const e=ZU(this.opacity);return`${e===1?"hsl(":"hsla("}${$Ue(this.h)}, ${az(this.s)*100}%, ${az(this.l)*100}%${e===1?")":`, ${e})`}`}}));function $Ue(e){return e=(e||0)%360,e<0?e+360:e}function az(e){return Math.max(0,Math.min(1,e||0))}function mre(e,t,n){return(e<60?t+(n-t)*e/60:e<180?n:e<240?t+(n-t)*(240-e)/60:t)*255}const JCe=e=>()=>e;function dJn(e,t){return function(n){return e+n*t}}function fJn(e,t,n){return e=Math.pow(e,n),t=Math.pow(t,n)-e,n=1/n,function(r){return Math.pow(e+r*t,n)}}function hJn(e){return(e=+e)==1?iEt:function(t,n){return n-t?fJn(t,n,e):JCe(isNaN(t)?n:t)}}function iEt(e,t){var n=t-e;return n?dJn(e,n):JCe(isNaN(e)?t:e)}const GU=(function e(t){var n=hJn(t);function r(s,a){var i=n((s=qye(s)).r,(a=qye(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=iEt(s.opacity,a.opacity);return function(d){return s.r=i(d),s.g=l(d),s.b=c(d),s.opacity=u(d),s+""}}return r.gamma=e,r})(1);function pJn(e,t){t||(t=[]);var n=e?Math.min(t.length,e.length):0,r=t.slice(),s;return function(a){for(s=0;s<n;++s)r[s]=e[s]*(1-a)+t[s]*a;return r}}function mJn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function gJn(e,t){var n=t?t.length:0,r=e?Math.min(n,e.length):0,s=new Array(r),a=new Array(n),i;for(i=0;i<r;++i)s[i]=Cx(e[i],t[i]);for(;i<n;++i)a[i]=t[i];return function(l){for(i=0;i<r;++i)a[i]=s[i](l);return a}}function vJn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function xg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function yJn(e,t){var n={},r={},s;(e===null||typeof e!="object")&&(e={}),(t===null||typeof t!="object")&&(t={});for(s in t)s in e?n[s]=Cx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Vye=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,gre=new RegExp(Vye.source,"g");function bJn(e){return function(){return e}}function xJn(e){return function(t){return e(t)+""}}function oEt(e,t){var n=Vye.lastIndex=gre.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Vye.exec(e))&&(s=gre.exec(t));)(a=s.index)>n&&(a=t.slice(n,a),l[i]?l[i]+=a:l[++i]=a),(r=r[0])===(s=s[0])?l[i]?l[i]+=s:l[++i]=s:(l[++i]=null,c.push({i,x:xg(r,s)})),n=gre.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?xJn(c[0].x):bJn(t):(t=c.length,function(u){for(var d=0,f;d<t;++d)l[(f=c[d]).i]=f.x(u);return l.join("")})}function Cx(e,t){var n=typeof t,r;return t==null||n==="boolean"?JCe(t):(n==="number"?xg:n==="string"?(r=wC(t))?(t=r,GU):oEt:t instanceof wC?GU:t instanceof Date?vJn:mJn(t)?pJn:Array.isArray(t)?gJn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?yJn:xg)(e,t)}function e_e(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var MUe=180/Math.PI,Hye={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function lEt(e,t,n,r,s,a){var i,l,c;return(i=Math.sqrt(e*e+t*t))&&(e/=i,t/=i),(c=e*n+t*r)&&(n-=e*c,r-=t*c),(l=Math.sqrt(n*n+r*r))&&(n/=l,r/=l,c/=l),e*r<t*n&&(e=-e,t=-t,c=-c,i=-i),{translateX:s,translateY:a,rotate:Math.atan2(t,e)*MUe,skewX:Math.atan(c)*MUe,scaleX:i,scaleY:l}}var iz;function wJn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Hye:lEt(t.a,t.b,t.c,t.d,t.e,t.f)}function SJn(e){return e==null||(iz||(iz=document.createElementNS("http://www.w3.org/2000/svg","g")),iz.setAttribute("transform",e),!(e=iz.transform.baseVal.consolidate()))?Hye:(e=e.matrix,lEt(e.a,e.b,e.c,e.d,e.e,e.f))}function cEt(e,t,n,r){function s(u){return u.length?u.pop()+" ":""}function a(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push("translate(",null,t,null,n);m.push({i:v-4,x:xg(u,f)},{i:v-2,x:xg(d,h)})}else(f||h)&&p.push("translate("+f+t+h+n)}function i(u,d,f,h){u!==d?(u-d>180?d+=360:d-u>180&&(u+=360),h.push({i:f.push(s(f)+"rotate(",null,r)-2,x:xg(u,d)})):d&&f.push(s(f)+"rotate("+d+r)}function l(u,d,f,h){u!==d?h.push({i:f.push(s(f)+"skewX(",null,r)-2,x:xg(u,d)}):d&&f.push(s(f)+"skewX("+d+r)}function c(u,d,f,h,p,m){if(u!==f||d!==h){var v=p.push(s(p)+"scale(",null,",",null,")");m.push({i:v-4,x:xg(u,f)},{i:v-2,x:xg(d,h)})}else(f!==1||h!==1)&&p.push(s(p)+"scale("+f+","+h+")")}return function(u,d){var f=[],h=[];return u=e(u),d=e(d),a(u.translateX,u.translateY,d.translateX,d.translateY,f,h),i(u.rotate,d.rotate,f,h),l(u.skewX,d.skewX,f,h),c(u.scaleX,u.scaleY,d.scaleX,d.scaleY,f,h),u=d=null,function(p){for(var m=-1,v=h.length,y;++m<v;)f[(y=h[m]).i]=y.x(p);return f.join("")}}}var kJn=cEt(wJn,"px, ","px)","deg)"),OJn=cEt(SJn,", ",")",")"),CJn=1e-12;function DUe(e){return((e=Math.exp(e))+1/e)/2}function _Jn(e){return((e=Math.exp(e))-1/e)/2}function EJn(e){return((e=Math.exp(2*e))-1)/(e+1)}const F9=(function e(t,n,r){function s(a,i){var l=a[0],c=a[1],u=a[2],d=i[0],f=i[1],h=i[2],p=d-l,m=f-c,v=p*p+m*m,y,b;if(v<CJn)b=Math.log(h/u)/t,y=function(T){return[l+T*p,c+T*m,u*Math.exp(t*T*b)]};else{var x=Math.sqrt(v),w=(h*h-u*u+r*v)/(2*u*n*x),k=(h*h-u*u-r*v)/(2*h*n*x),O=Math.log(Math.sqrt(w*w+1)-w),_=Math.log(Math.sqrt(k*k+1)-k);b=(_-O)/t,y=function(T){var E=T*b,N=DUe(O),I=u/(n*x)*(N*EJn(t*E+O)-_Jn(O));return[l+I*p,c+I*m,u*N/DUe(t*E+O)]}}return y.duration=b*1e3*t/Math.SQRT2,y}return s.rho=function(a){var i=Math.max(.001,+a),l=i*i,c=l*l;return e(i,l,c)},s})(Math.SQRT2,2,4);function TJn(e,t){t===void 0&&(t=e,e=Cx);for(var n=0,r=t.length-1,s=t[0],a=new Array(r<0?0:r);n<r;)a[n]=e(s,s=t[++n]);return function(i){var l=Math.max(0,Math.min(r-1,Math.floor(i*=r)));return a[l](i-l)}}var CN=0,T$=0,hP=0,uEt=1e3,QU,j$,YU=0,SC=0,dZ=0,vD=typeof performance=="object"&&performance.now?performance:Date,dEt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function t_e(){return SC||(dEt(jJn),SC=vD.now()+dZ)}function jJn(){SC=0}function KU(){this._call=this._time=this._next=null}KU.prototype=fEt.prototype={constructor:KU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?t_e():+n)+(t==null?0:+t),!this._next&&j$!==this&&(j$?j$._next=this:QU=this,j$=this),this._call=e,this._time=n,Wye()},stop:function(){this._call&&(this._call=null,this._time=1/0,Wye())}};function fEt(e,t,n){var r=new KU;return r.restart(e,t,n),r}function NJn(){t_e(),++CN;for(var e=QU,t;e;)(t=SC-e._time)>=0&&e._call.call(void 0,t),e=e._next;--CN}function LUe(){SC=(YU=vD.now())+dZ,CN=T$=0;try{NJn()}finally{CN=0,AJn(),SC=0}}function IJn(){var e=vD.now(),t=e-YU;t>uEt&&(dZ-=t,YU=e)}function AJn(){for(var e,t=QU,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:QU=n);j$=e,Wye(r)}function Wye(e){if(!CN){T$&&(T$=clearTimeout(T$));var t=e-SC;t>24?(e<1/0&&(T$=setTimeout(LUe,e-vD.now()-dZ)),hP&&(hP=clearInterval(hP))):(hP||(YU=vD.now(),hP=setInterval(IJn,uEt)),CN=1,dEt(LUe))}}function FUe(e,t,n){var r=new KU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var RJn=cZ("start","end","cancel","interrupt"),PJn=[],hEt=0,zUe=1,Zye=2,z9=3,BUe=4,Gye=5,B9=6;function fZ(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;$Jn(e,n,{name:t,index:r,group:s,on:RJn,tween:PJn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:hEt})}function n_e(e,t){var n=iv(e,t);if(n.state>hEt)throw new Error("too late; already scheduled");return n}function eb(e,t){var n=iv(e,t);if(n.state>z9)throw new Error("too late; already running");return n}function iv(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function $Jn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=fEt(a,0,n.time);function a(u){n.state=zUe,n.timer.restart(i,n.delay,n.time),n.delay<=u&&i(u-n.delay)}function i(u){var d,f,h,p;if(n.state!==zUe)return c();for(d in r)if(p=r[d],p.name===n.name){if(p.state===z9)return FUe(i);p.state===BUe?(p.state=B9,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[d]):+d<t&&(p.state=B9,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[d])}if(FUe(function(){n.state===z9&&(n.state=BUe,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Zye,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Zye){for(n.state=z9,s=new Array(h=n.tween.length),d=0,f=-1;d<h;++d)(p=n.tween[d].value.call(e,e.__data__,n.index,n.group))&&(s[++f]=p);s.length=f+1}}function l(u){for(var d=u<n.duration?n.ease.call(null,u/n.duration):(n.timer.restart(c),n.state=Gye,1),f=-1,h=s.length;++f<h;)s[f].call(e,d);n.state===Gye&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=B9,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function U9(e,t){var n=e.__transition,r,s,a=!0,i;if(n){t=t==null?null:t+"";for(i in n){if((r=n[i]).name!==t){a=!1;continue}s=r.state>Zye&&r.state<Gye,r.state=B9,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function MJn(e){return this.each(function(){U9(this,e)})}function DJn(e,t){var n,r;return function(){var s=eb(this,e),a=s.tween;if(a!==n){r=n=a;for(var i=0,l=r.length;i<l;++i)if(r[i].name===t){r=r.slice(),r.splice(i,1);break}}s.tween=r}}function LJn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=eb(this,e),i=a.tween;if(i!==r){s=(r=i).slice();for(var l={name:t,value:n},c=0,u=s.length;c<u;++c)if(s[c].name===t){s[c]=l;break}c===u&&s.push(l)}a.tween=s}}function FJn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=iv(this.node(),n).tween,s=0,a=r.length,i;s<a;++s)if((i=r[s]).name===e)return i.value;return null}return this.each((t==null?DJn:LJn)(n,e,t))}function r_e(e,t,n){var r=e._id;return e.each(function(){var s=eb(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return iv(s,r).value[t]}}function pEt(e,t){var n;return(typeof t=="number"?xg:t instanceof wC?GU:(n=wC(t))?(t=n,GU):oEt)(e,t)}function zJn(e){return function(){this.removeAttribute(e)}}function BJn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function UJn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttribute(e);return i===s?null:i===r?a:a=t(r=i,n)}}function qJn(e,t,n){var r,s=n+"",a;return function(){var i=this.getAttributeNS(e.space,e.local);return i===s?null:i===r?a:a=t(r=i,n)}}function VJn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttribute(e):(i=this.getAttribute(e),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function HJn(e,t,n){var r,s,a;return function(){var i,l=n(this),c;return l==null?void this.removeAttributeNS(e.space,e.local):(i=this.getAttributeNS(e.space,e.local),c=l+"",i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l)))}}function WJn(e,t){var n=uZ(e),r=n==="transform"?OJn:pEt;return this.attrTween(e,typeof t=="function"?(n.local?HJn:VJn)(n,r,r_e(this,"attr."+e,t)):t==null?(n.local?BJn:zJn)(n):(n.local?qJn:UJn)(n,r,t))}function ZJn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function GJn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function QJn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&GJn(e,a)),n}return s._value=t,s}function YJn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&ZJn(e,a)),n}return s._value=t,s}function KJn(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=uZ(e);return this.tween(n,(r.local?QJn:YJn)(r,t))}function XJn(e,t){return function(){n_e(this,e).delay=+t.apply(this,arguments)}}function JJn(e,t){return t=+t,function(){n_e(this,e).delay=t}}function eer(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?XJn:JJn)(t,e)):iv(this.node(),t).delay}function ter(e,t){return function(){eb(this,e).duration=+t.apply(this,arguments)}}function ner(e,t){return t=+t,function(){eb(this,e).duration=t}}function rer(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?ter:ner)(t,e)):iv(this.node(),t).duration}function ser(e,t){if(typeof t!="function")throw new Error;return function(){eb(this,e).ease=t}}function aer(e){var t=this._id;return arguments.length?this.each(ser(t,e)):iv(this.node(),t).ease}function ier(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;eb(this,e).ease=n}}function oer(e){if(typeof e!="function")throw new Error;return this.each(ier(this._id,e))}function ler(e){typeof e!="function"&&(e=H_t(e));for(var t=this._groups,n=t.length,r=new Array(n),s=0;s<n;++s)for(var a=t[s],i=a.length,l=r[s]=[],c,u=0;u<i;++u)(c=a[u])&&e.call(c,c.__data__,u,a)&&l.push(c);return new Gx(r,this._parents,this._name,this._id)}function cer(e){if(e._id!==this._id)throw new Error;for(var t=this._groups,n=e._groups,r=t.length,s=n.length,a=Math.min(r,s),i=new Array(r),l=0;l<a;++l)for(var c=t[l],u=n[l],d=c.length,f=i[l]=new Array(d),h,p=0;p<d;++p)(h=c[p]||u[p])&&(f[p]=h);for(;l<r;++l)i[l]=t[l];return new Gx(i,this._parents,this._name,this._id)}function uer(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 der(e,t,n){var r,s,a=uer(t)?n_e:eb;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function fer(e,t){var n=this._id;return arguments.length<2?iv(this.node(),n).on.on(e):this.each(der(n,e,t))}function her(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function per(){return this.on("end.remove",her(this._id))}function mer(e){var t=this._name,n=this._id;typeof e!="function"&&(e=YCe(e));for(var r=this._groups,s=r.length,a=new Array(s),i=0;i<s;++i)for(var l=r[i],c=l.length,u=a[i]=new Array(c),d,f,h=0;h<c;++h)(d=l[h])&&(f=e.call(d,d.__data__,h,l))&&("__data__"in d&&(f.__data__=d.__data__),u[h]=f,fZ(u[h],t,n,h,u,iv(d,n)));return new Gx(a,this._parents,t,n)}function ger(e){var t=this._name,n=this._id;typeof e!="function"&&(e=V_t(e));for(var r=this._groups,s=r.length,a=[],i=[],l=0;l<s;++l)for(var c=r[l],u=c.length,d,f=0;f<u;++f)if(d=c[f]){for(var h=e.call(d,d.__data__,f,c),p,m=iv(d,n),v=0,y=h.length;v<y;++v)(p=h[v])&&fZ(p,t,n,v,h,m);a.push(h),i.push(d)}return new Gx(a,i,t,n)}var ver=PL.prototype.constructor;function yer(){return new ver(this._groups,this._parents)}function ber(e,t){var n,r,s;return function(){var a=ON(this,e),i=(this.style.removeProperty(e),ON(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function mEt(e){return function(){this.style.removeProperty(e)}}function xer(e,t,n){var r,s=n+"",a;return function(){var i=ON(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function wer(e,t,n){var r,s,a;return function(){var i=ON(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),ON(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function Ser(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=eb(this,e),u=c.on,d=c.value[a]==null?l||(l=mEt(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function ker(e,t,n){var r=(e+="")=="transform"?kJn:pEt;return t==null?this.styleTween(e,ber(e,r)).on("end.style."+e,mEt(e)):typeof t=="function"?this.styleTween(e,wer(e,r,r_e(this,"style."+e,t))).each(Ser(this._id,e)):this.styleTween(e,xer(e,r,t),n).on("end.style."+e,null)}function Oer(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function Cer(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&Oer(e,i,n)),r}return a._value=t,a}function _er(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,Cer(e,t,n??""))}function Eer(e){return function(){this.textContent=e}}function Ter(e){return function(){var t=e(this);this.textContent=t??""}}function jer(e){return this.tween("text",typeof e=="function"?Ter(r_e(this,"text",e)):Eer(e==null?"":e+""))}function Ner(e){return function(t){this.textContent=e.call(this,t)}}function Ier(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&Ner(s)),t}return r._value=e,r}function Aer(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,Ier(e))}function Rer(){for(var e=this._name,t=this._id,n=gEt(),r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)if(c=i[u]){var d=iv(c,t);fZ(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new Gx(r,this._parents,e,n)}function Per(){var e,t,n=this,r=n._id,s=n.size();return new Promise(function(a,i){var l={value:i},c={value:function(){--s===0&&a()}};n.each(function(){var u=eb(this,r),d=u.on;d!==e&&(t=(e=d).copy(),t._.cancel.push(l),t._.interrupt.push(l),t._.end.push(c)),u.on=t}),s===0&&a()})}var $er=0;function Gx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function gEt(){return++$er}var $b=PL.prototype;Gx.prototype={constructor:Gx,select:mer,selectAll:ger,selectChild:$b.selectChild,selectChildren:$b.selectChildren,filter:ler,merge:cer,selection:yer,transition:Rer,call:$b.call,nodes:$b.nodes,node:$b.node,size:$b.size,empty:$b.empty,each:$b.each,on:fer,attr:WJn,attrTween:KJn,style:ker,styleTween:_er,text:jer,textTween:Aer,remove:per,tween:FJn,delay:eer,duration:rer,ease:aer,easeVarying:oer,end:Per,[Symbol.iterator]:$b[Symbol.iterator]};function Mer(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var Der={time:null,delay:0,duration:250,ease:Mer};function Ler(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 Fer(e){var t,n;e instanceof Gx?(t=e._id,e=e._name):(t=gEt(),(n=Der).time=t_e(),e=e==null?null:e+"");for(var r=this._groups,s=r.length,a=0;a<s;++a)for(var i=r[a],l=i.length,c,u=0;u<l;++u)(c=i[u])&&fZ(c,e,t,u,i,n||Ler(c,t));return new Gx(r,this._parents,e,t)}PL.prototype.interrupt=MJn;PL.prototype.transition=Fer;const oz=e=>()=>e;function zer(e,{sourceEvent:t,target:n,transform:r,dispatch:s}){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:s}})}function dx(e,t,n){this.k=e,this.x=t,this.y=n}dx.prototype={constructor:dx,scale:function(e){return e===1?this:new dx(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new dx(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 hZ=new dx(1,0,0);vEt.prototype=dx.prototype;function vEt(e){for(;!e.__zoom;)if(!(e=e.parentNode))return hZ;return e.__zoom}function vre(e){e.stopImmediatePropagation()}function pP(e){e.preventDefault(),e.stopImmediatePropagation()}function Ber(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function Uer(){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 UUe(){return this.__zoom||hZ}function qer(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function Ver(){return navigator.maxTouchPoints||"ontouchstart"in this}function Her(e,t,n){var r=e.invertX(t[0][0])-n[0][0],s=e.invertX(t[1][0])-n[1][0],a=e.invertY(t[0][1])-n[0][1],i=e.invertY(t[1][1])-n[1][1];return e.translate(s>r?(r+s)/2:Math.min(0,r)||Math.max(0,s),i>a?(a+i)/2:Math.min(0,a)||Math.max(0,i))}function yEt(){var e=Ber,t=Uer,n=Her,r=qer,s=Ver,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=F9,u=cZ("start","zoom","end"),d,f,h,p=500,m=150,v=0,y=10;function b(D){D.property("__zoom",UUe).on("wheel.zoom",E,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",$).on("touchend.zoom touchcancel.zoom",z).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(D,q,H,V){var B=D.selection?D.selection():D;B.property("__zoom",UUe),D!==B?O(D,q,H,V):B.interrupt().each(function(){_(this,arguments).event(V).start().zoom(null,typeof q=="function"?q.apply(this,arguments):q).end()})},b.scaleBy=function(D,q,H,V){b.scaleTo(D,function(){var B=this.__zoom.k,W=typeof q=="function"?q.apply(this,arguments):q;return B*W},H,V)},b.scaleTo=function(D,q,H,V){b.transform(D,function(){var B=t.apply(this,arguments),W=this.__zoom,L=H==null?k(B):typeof H=="function"?H.apply(this,arguments):H,G=W.invert(L),M=typeof q=="function"?q.apply(this,arguments):q;return n(w(x(W,M),L,G),B,i)},H,V)},b.translateBy=function(D,q,H,V){b.transform(D,function(){return n(this.__zoom.translate(typeof q=="function"?q.apply(this,arguments):q,typeof H=="function"?H.apply(this,arguments):H),t.apply(this,arguments),i)},null,V)},b.translateTo=function(D,q,H,V,B){b.transform(D,function(){var W=t.apply(this,arguments),L=this.__zoom,G=V==null?k(W):typeof V=="function"?V.apply(this,arguments):V;return n(hZ.translate(G[0],G[1]).scale(L.k).translate(typeof q=="function"?-q.apply(this,arguments):-q,typeof H=="function"?-H.apply(this,arguments):-H),W,i)},V,B)};function x(D,q){return q=Math.max(a[0],Math.min(a[1],q)),q===D.k?D:new dx(q,D.x,D.y)}function w(D,q,H){var V=q[0]-H[0]*D.k,B=q[1]-H[1]*D.k;return V===D.x&&B===D.y?D:new dx(D.k,V,B)}function k(D){return[(+D[0][0]+ +D[1][0])/2,(+D[0][1]+ +D[1][1])/2]}function O(D,q,H,V){D.on("start.zoom",function(){_(this,arguments).event(V).start()}).on("interrupt.zoom end.zoom",function(){_(this,arguments).event(V).end()}).tween("zoom",function(){var B=this,W=arguments,L=_(B,W).event(V),G=t.apply(B,W),M=H==null?k(G):typeof H=="function"?H.apply(B,W):H,R=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),F=B.__zoom,U=typeof q=="function"?q.apply(B,W):q,Q=c(F.invert(M).concat(R/F.k),U.invert(M).concat(R/U.k));return function(te){if(te===1)te=U;else{var J=Q(te),ee=R/J[2];te=new dx(ee,M[0]-J[0]*ee,M[1]-J[1]*ee)}L.zoom(null,te)}})}function _(D,q,H){return!H&&D.__zooming||new T(D,q)}function T(D,q){this.that=D,this.args=q,this.active=0,this.sourceEvent=null,this.extent=t.apply(D,q),this.taps=0}T.prototype={event:function(D){return D&&(this.sourceEvent=D),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(D,q){return this.mouse&&D!=="mouse"&&(this.mouse[1]=q.invert(this.mouse[0])),this.touch0&&D!=="touch"&&(this.touch0[1]=q.invert(this.touch0[0])),this.touch1&&D!=="touch"&&(this.touch1[1]=q.invert(this.touch1[0])),this.that.__zoom=q,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(D){var q=Ah(this.that).datum();u.call(D,this.that,new zer(D,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),q)}};function E(D,...q){if(!e.apply(this,arguments))return;var H=_(this,q).event(D),V=this.__zoom,B=Math.max(a[0],Math.min(a[1],V.k*Math.pow(2,r.apply(this,arguments)))),W=yg(D);if(H.wheel)(H.mouse[0][0]!==W[0]||H.mouse[0][1]!==W[1])&&(H.mouse[1]=V.invert(H.mouse[0]=W)),clearTimeout(H.wheel);else{if(V.k===B)return;H.mouse=[W,V.invert(W)],U9(this),H.start()}pP(D),H.wheel=setTimeout(L,m),H.zoom("mouse",n(w(x(V,B),H.mouse[0],H.mouse[1]),H.extent,i));function L(){H.wheel=null,H.end()}}function N(D,...q){if(h||!e.apply(this,arguments))return;var H=D.currentTarget,V=_(this,q,!0).event(D),B=Ah(D.view).on("mousemove.zoom",M,!0).on("mouseup.zoom",R,!0),W=yg(D,H),L=D.clientX,G=D.clientY;tEt(D.view),vre(D),V.mouse=[W,this.__zoom.invert(W)],U9(this),V.start();function M(F){if(pP(F),!V.moved){var U=F.clientX-L,Q=F.clientY-G;V.moved=U*U+Q*Q>v}V.event(F).zoom("mouse",n(w(V.that.__zoom,V.mouse[0]=yg(F,H),V.mouse[1]),V.extent,i))}function R(F){B.on("mousemove.zoom mouseup.zoom",null),nEt(F.view,V.moved),pP(F),V.event(F).end()}}function I(D,...q){if(e.apply(this,arguments)){var H=this.__zoom,V=yg(D.changedTouches?D.changedTouches[0]:D,this),B=H.invert(V),W=H.k*(D.shiftKey?.5:2),L=n(w(x(H,W),V,B),t.apply(this,q),i);pP(D),l>0?Ah(this).transition().duration(l).call(O,L,V,D):Ah(this).call(b.transform,L,V,D)}}function A(D,...q){if(e.apply(this,arguments)){var H=D.touches,V=H.length,B=_(this,q,D.changedTouches.length===V).event(D),W,L,G,M;for(vre(D),L=0;L<V;++L)G=H[L],M=yg(G,this),M=[M,this.__zoom.invert(M),G.identifier],B.touch0?!B.touch1&&B.touch0[2]!==M[2]&&(B.touch1=M,B.taps=0):(B.touch0=M,W=!0,B.taps=1+!!d);d&&(d=clearTimeout(d)),W&&(B.taps<2&&(f=M[0],d=setTimeout(function(){d=null},p)),U9(this),B.start())}}function $(D,...q){if(this.__zooming){var H=_(this,q).event(D),V=D.changedTouches,B=V.length,W,L,G,M;for(pP(D),W=0;W<B;++W)L=V[W],G=yg(L,this),H.touch0&&H.touch0[2]===L.identifier?H.touch0[0]=G:H.touch1&&H.touch1[2]===L.identifier&&(H.touch1[0]=G);if(L=H.that.__zoom,H.touch1){var R=H.touch0[0],F=H.touch0[1],U=H.touch1[0],Q=H.touch1[1],te=(te=U[0]-R[0])*te+(te=U[1]-R[1])*te,J=(J=Q[0]-F[0])*J+(J=Q[1]-F[1])*J;L=x(L,Math.sqrt(te/J)),G=[(R[0]+U[0])/2,(R[1]+U[1])/2],M=[(F[0]+Q[0])/2,(F[1]+Q[1])/2]}else if(H.touch0)G=H.touch0[0],M=H.touch0[1];else return;H.zoom("touch",n(w(L,G,M),H.extent,i))}}function z(D,...q){if(this.__zooming){var H=_(this,q).event(D),V=D.changedTouches,B=V.length,W,L;for(vre(D),h&&clearTimeout(h),h=setTimeout(function(){h=null},p),W=0;W<B;++W)L=V[W],H.touch0&&H.touch0[2]===L.identifier?delete H.touch0:H.touch1&&H.touch1[2]===L.identifier&&delete H.touch1;if(H.touch1&&!H.touch0&&(H.touch0=H.touch1,delete H.touch1),H.touch0)H.touch0[1]=this.__zoom.invert(H.touch0[0]);else if(H.end(),H.taps===2&&(L=yg(L,this),Math.hypot(f[0]-L[0],f[1]-L[1])<y)){var G=Ah(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(D){return arguments.length?(r=typeof D=="function"?D:oz(+D),b):r},b.filter=function(D){return arguments.length?(e=typeof D=="function"?D:oz(!!D),b):e},b.touchable=function(D){return arguments.length?(s=typeof D=="function"?D:oz(!!D),b):s},b.extent=function(D){return arguments.length?(t=typeof D=="function"?D:oz([[+D[0][0],+D[0][1]],[+D[1][0],+D[1][1]]]),b):t},b.scaleExtent=function(D){return arguments.length?(a[0]=+D[0],a[1]=+D[1],b):[a[0],a[1]]},b.translateExtent=function(D){return arguments.length?(i[0][0]=+D[0][0],i[1][0]=+D[1][0],i[0][1]=+D[0][1],i[1][1]=+D[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(D){return arguments.length?(n=D,b):n},b.duration=function(D){return arguments.length?(l=+D,b):l},b.interpolate=function(D){return arguments.length?(c=D,b):c},b.on=function(){var D=u.on.apply(u,arguments);return D===u?b:D},b.clickDistance=function(D){return arguments.length?(v=(D=+D)*D,b):Math.sqrt(v)},b.tapDistance=function(D){return arguments.length?(y=+D,b):y},b}const $y={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."},yD=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],bEt=["Enter"," ","Escape"],xEt={"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 _N;(function(e){e.Strict="strict",e.Loose="loose"})(_N||(_N={}));var TO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(TO||(TO={}));var bD;(function(e){e.Partial="partial",e.Full="full"})(bD||(bD={}));const wEt={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Uw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Uw||(Uw={}));var xD;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(xD||(xD={}));var ar;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(ar||(ar={}));const qUe={[ar.Left]:ar.Right,[ar.Right]:ar.Left,[ar.Top]:ar.Bottom,[ar.Bottom]:ar.Top};function SEt(e){return e===null?null:e?"valid":"invalid"}const kEt=e=>"id"in e&&"source"in e&&"target"in e,Wer=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),s_e=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),ML=(e,t=[0,0])=>{const{width:n,height:r}=x0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},Zer=(e,t={nodeOrigin:[0,0]})=>{if(e.length===0)return{x:0,y:0,width:0,height:0};const n=e.reduce((r,s)=>{const a=typeof s=="string";let i=!t.nodeLookup&&!a?s:void 0;t.nodeLookup&&(i=a?t.nodeLookup.get(s):s_e(s)?s:t.nodeLookup.get(s.id));const l=i?XU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return pZ(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return mZ(n)},DL=(e,t={})=>{let n={x:1/0,y:1/0,x2:-1/0,y2:-1/0},r=!1;return e.forEach(s=>{(t.filter===void 0||t.filter(s))&&(n=pZ(n,XU(s)),r=!0)}),r?mZ(n):{x:0,y:0,width:0,height:0}},a_e=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...FL(t,[n,r,s]),width:t.width/s,height:t.height/s},c=[];for(const u of e.values()){const{measured:d,selectable:f=!0,hidden:h=!1}=u;if(i&&!f||h)continue;const p=d.width??u.width??u.initialWidth??null,m=d.height??u.height??u.initialHeight??null,v=wD(l,TN(u)),y=(p??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},Ger=(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 Qer(e,t){const n=new Map,r=t?.nodes?new Set(t.nodes.map(s=>s.id)):null;return e.forEach(s=>{s.measured.width&&s.measured.height&&(t?.includeHiddenNodes||!s.hidden)&&(!r||r.has(s.id))&&n.set(s.id,s)}),n}async function Yer({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=Qer(e,i),c=DL(l),u=i_e(c,t,n,i?.minZoom??s,i?.maxZoom??a,i?.padding??.1);return await r.setViewport(u,{duration:i?.duration,ease:i?.ease,interpolate:i?.interpolate}),Promise.resolve(!0)}function OEt({nodeId:e,nextPosition:t,nodeLookup:n,nodeOrigin:r=[0,0],nodeExtent:s,onError:a}){const i=n.get(e),l=i.parentId?n.get(i.parentId):void 0,{x:c,y:u}=l?l.internals.positionAbsolute:{x:0,y:0},d=i.origin??r;let f=i.extent||s;if(i.extent==="parent"&&!i.expandParent)if(!l)a?.("005",$y.error005());else{const p=l.measured.width,m=l.measured.height;p&&m&&(f=[[c,u],[c+p,u+m]])}else l&&jN(i.extent)&&(f=[[i.extent[0][0]+c,i.extent[0][1]+u],[i.extent[1][0]+c,i.extent[1][1]+u]]);const h=jN(f)?kC(t,f,i.measured):t;return(i.measured.width===void 0||i.measured.height===void 0)&&a?.("015",$y.error015()),{position:{x:h.x-c+(i.measured.width??0)*d[0],y:h.y-u+(i.measured.height??0)*d[1]},positionAbsolute:h}}async function Ker({nodesToRemove:e=[],edgesToRemove:t=[],nodes:n,edges:r,onBeforeDelete:s}){const a=new Set(e.map(h=>h.id)),i=[];for(const h of n){if(h.deletable===!1)continue;const p=a.has(h.id),m=!p&&h.parentId&&i.find(v=>v.id===h.parentId);(p||m)&&i.push(h)}const l=new Set(t.map(h=>h.id)),c=r.filter(h=>h.deletable!==!1),d=Ger(i,c);for(const h of c)l.has(h.id)&&!d.find(m=>m.id===h.id)&&d.push(h);if(!s)return{edges:d,nodes:i};const f=await s({nodes:i,edges:d});return typeof f=="boolean"?f?{edges:d,nodes:i}:{edges:[],nodes:[]}:f}const EN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),kC=(e={x:0,y:0},t,n)=>({x:EN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:EN(e.y,t[0][1],t[1][1]-(n?.height??0))});function CEt(e,t,n){const{width:r,height:s}=x0(n),{x:a,y:i}=n.internals.positionAbsolute;return kC(e,[[a,i],[a+r,i+s]],t)}const VUe=(e,t,n)=>e<t?EN(Math.abs(e-t),1,t)/t:e>n?-EN(Math.abs(e-n),1,t)/t:0,_Et=(e,t,n=15,r=40)=>{const s=VUe(e.x,r,t.width-r)*n,a=VUe(e.y,r,t.height-r)*n;return[s,a]},pZ=(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)}),Qye=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),mZ=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),TN=(e,t=[0,0])=>{const{x:n,y:r}=s_e(e)?e.internals.positionAbsolute:ML(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}},XU=(e,t=[0,0])=>{const{x:n,y:r}=s_e(e)?e.internals.positionAbsolute:ML(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)}},EEt=(e,t)=>mZ(pZ(Qye(e),Qye(t))),wD=(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)},HUe=e=>Ng(e.width)&&Ng(e.height)&&Ng(e.x)&&Ng(e.y),Ng=e=>!isNaN(e)&&isFinite(e),Xer=(e,t)=>{},LL=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),FL=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?LL(l,i):l},JU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function FE(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 Jer(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=FE(e,n),s=FE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=FE(e.top??e.y??0,n),s=FE(e.bottom??e.y??0,n),a=FE(e.left??e.x??0,t),i=FE(e.right??e.x??0,t);return{top:r,right:i,bottom:s,left:a,x:a+i,y:r+s}}return{top:0,right:0,bottom:0,left:0,x:0,y:0}}function etr(e,t,n,r,s,a){const{x:i,y:l}=JU(e,[t,n,r]),{x:c,y:u}=JU({x:e.x+e.width,y:e.y+e.height},[t,n,r]),d=s-c,f=a-u;return{left:Math.floor(i),top:Math.floor(l),right:Math.floor(d),bottom:Math.floor(f)}}const i_e=(e,t,n,r,s,a)=>{const i=Jer(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=EN(u,r,s),f=e.x+e.width/2,h=e.y+e.height/2,p=t/2-f*d,m=n/2-h*d,v=etr(e,p,m,d,t,n),y={left:Math.min(v.left-i.left,0),top:Math.min(v.top-i.top,0),right:Math.min(v.right-i.right,0),bottom:Math.min(v.bottom-i.bottom,0)};return{x:p-y.left+y.right,y:m-y.top+y.bottom,zoom:d}},SD=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function jN(e){return e!=null&&e!=="parent"}function x0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function TEt(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function jEt(e,t={width:0,height:0},n,r,s){const a={...e},i=r.get(n);if(i){const l=i.origin||s;a.x+=i.internals.positionAbsolute.x-(t.width??0)*l[0],a.y+=i.internals.positionAbsolute.y-(t.height??0)*l[1]}return a}function WUe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function ttr(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function ntr(e){return{...xEt,...e||{}}}function gM(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Ig(e),l=FL({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?LL(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const o_e=e=>({width:e.offsetWidth,height:e.offsetHeight}),NEt=e=>e?.getRootNode?.()||window?.document,rtr=["INPUT","SELECT","TEXTAREA"];function IEt(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:rtr.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const AEt=e=>"clientX"in e,Ig=(e,t)=>{const n=AEt(e),r=n?e.clientX:e.touches?.[0].clientX,s=n?e.clientY:e.touches?.[0].clientY;return{x:r-(t?.left??0),y:s-(t?.top??0)}},ZUe=(e,t,n,r,s)=>{const a=t.querySelectorAll(`.${e}`);return!a||!a.length?null:Array.from(a).map(i=>{const l=i.getBoundingClientRect();return{id:i.getAttribute("data-handleid"),type:e,nodeId:s,position:i.getAttribute("data-handlepos"),x:(l.left-n.left)/r,y:(l.top-n.top)/r,...o_e(i)}})};function REt({sourceX:e,sourceY:t,targetX:n,targetY:r,sourceControlX:s,sourceControlY:a,targetControlX:i,targetControlY:l}){const c=e*.125+s*.375+i*.375+n*.125,u=t*.125+a*.375+l*.375+r*.125,d=Math.abs(c-e),f=Math.abs(u-t);return[c,u,d,f]}function lz(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function GUe({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case ar.Left:return[t-lz(t-r,a),n];case ar.Right:return[t+lz(r-t,a),n];case ar.Top:return[t,n-lz(n-s,a)];case ar.Bottom:return[t,n+lz(s-n,a)]}}function l_e({sourceX:e,sourceY:t,sourcePosition:n=ar.Bottom,targetX:r,targetY:s,targetPosition:a=ar.Top,curvature:i=.25}){const[l,c]=GUe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=GUe({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,h,p,m]=REt({sourceX:e,sourceY:t,targetX:r,targetY:s,sourceControlX:l,sourceControlY:c,targetControlX:u,targetControlY:d});return[`M${e},${t} C${l},${c} ${u},${d} ${r},${s}`,f,h,p,m]}function PEt({sourceX:e,sourceY:t,targetX:n,targetY:r}){const s=Math.abs(n-e)/2,a=n<e?n+s:n-s,i=Math.abs(r-t)/2,l=r<t?r+i:r-i;return[a,l,s,i]}function str({sourceNode:e,targetNode:t,selected:n=!1,zIndex:r=0,elevateOnSelect:s=!1,zIndexMode:a="basic"}){if(a==="manual")return r;const i=s&&n?r+1e3:r,l=Math.max(e.parentId||s&&e.selected?e.internals.z:0,t.parentId||s&&t.selected?t.internals.z:0);return i+l}function atr({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=pZ(XU(e),XU(t));a.x===a.x2&&(a.x2+=1),a.y===a.y2&&(a.y2+=1);const i={x:-s[0]/s[2],y:-s[1]/s[2],width:n/s[2],height:r/s[2]};return wD(i,mZ(a))>0}const itr=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,otr=(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)),ltr=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||itr;let s;return kEt(e)?s={...e}:s={...e,id:r(e)},otr(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function $Et({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=PEt({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const QUe={[ar.Left]:{x:-1,y:0},[ar.Right]:{x:1,y:0},[ar.Top]:{x:0,y:-1},[ar.Bottom]:{x:0,y:1}},ctr=({source:e,sourcePosition:t=ar.Bottom,target:n})=>t===ar.Left||t===ar.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},YUe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function utr({source:e,sourcePosition:t=ar.Bottom,target:n,targetPosition:r=ar.Top,center:s,offset:a,stepPosition:i}){const l=QUe[t],c=QUe[r],u={x:e.x+l.x*a,y:e.y+l.y*a},d={x:n.x+c.x*a,y:n.y+c.y*a},f=ctr({source:u,sourcePosition:t,target:d}),h=f.x!==0?"x":"y",p=f[h];let m=[],v,y;const b={x:0,y:0},x={x:0,y:0},[,,w,k]=PEt({sourceX:e.x,sourceY:e.y,targetX:n.x,targetY:n.y});if(l[h]*c[h]===-1){h==="x"?(v=s.x??u.x+(d.x-u.x)*i,y=s.y??(u.y+d.y)/2):(v=s.x??(u.x+d.x)/2,y=s.y??u.y+(d.y-u.y)*i);const E=[{x:v,y:u.y},{x:v,y:d.y}],N=[{x:u.x,y},{x:d.x,y}];l[h]===p?m=h==="x"?E:N:m=h==="x"?N:E}else{const E=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(h==="x"?m=l.x===p?N:E:m=l.y===p?E:N,t===r){const D=Math.abs(e[h]-n[h]);if(D<=a){const q=Math.min(a-1,a-D);l[h]===p?b[h]=(u[h]>e[h]?-1:1)*q:x[h]=(d[h]>n[h]?-1:1)*q}}if(t!==r){const D=h==="x"?"y":"x",q=l[h]===c[D],H=u[D]>d[D],V=u[D]<d[D];(l[h]===1&&(!q&&H||q&&V)||l[h]!==1&&(!q&&V||q&&H))&&(m=h==="x"?E:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},$=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),z=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));$>=z?(v=(I.x+A.x)/2,y=m[0].y):(v=m[0].x,y=(I.y+A.y)/2)}const O={x:u.x+b.x,y:u.y+b.y},_={x:d.x+x.x,y:d.y+x.y};return[[e,...O.x!==m[0].x||O.y!==m[0].y?[O]:[],...m,..._.x!==m[m.length-1].x||_.y!==m[m.length-1].y?[_]:[],n],v,y,w,k]}function dtr(e,t,n,r){const s=Math.min(YUe(e,t)/2,YUe(t,n)/2,r),{x:a,y:i}=t;if(e.x===a&&a===n.x||e.y===i&&i===n.y)return`L${a} ${i}`;if(e.y===i){const u=e.x<n.x?-1:1,d=e.y<n.y?1:-1;return`L ${a+s*u},${i}Q ${a},${i} ${a},${i+s*d}`}const l=e.x<n.x?1:-1,c=e.y<n.y?-1:1;return`L ${a},${i+s*c}Q ${a},${i} ${a+s*l},${i}`}function Yye({sourceX:e,sourceY:t,sourcePosition:n=ar.Bottom,targetX:r,targetY:s,targetPosition:a=ar.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,h,p,m,v]=utr({source:{x:e,y:t},sourcePosition:n,target:{x:r,y:s},targetPosition:a,center:{x:l,y:c},offset:u,stepPosition:d});let y=`M${f[0].x} ${f[0].y}`;for(let b=1;b<f.length-1;b++)y+=dtr(f[b-1],f[b],f[b+1],i);return y+=`L${f[f.length-1].x} ${f[f.length-1].y}`,[y,h,p,m,v]}function KUe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function ftr(e){const{sourceNode:t,targetNode:n}=e;if(!KUe(t)||!KUe(n))return null;const r=t.internals.handleBounds||XUe(t.handles),s=n.internals.handleBounds||XUe(n.handles),a=JUe(r?.source??[],e.sourceHandle),i=JUe(e.connectionMode===_N.Strict?s?.target??[]:(s?.target??[]).concat(s?.source??[]),e.targetHandle);if(!a||!i)return e.onError?.("008",$y.error008(a?"target":"source",{id:e.id,sourceHandle:e.sourceHandle,targetHandle:e.targetHandle})),null;const l=a?.position||ar.Bottom,c=i?.position||ar.Top,u=OC(t,a,l),d=OC(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function XUe(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 OC(e,t,n=ar.Left,r=!1){const s=(t?.x??0)+e.internals.positionAbsolute.x,a=(t?.y??0)+e.internals.positionAbsolute.y,{width:i,height:l}=t??x0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case ar.Top:return{x:s+i/2,y:a};case ar.Right:return{x:s+i,y:a+l/2};case ar.Bottom:return{x:s+i/2,y:a+l};case ar.Left:return{x:s,y:a+l/2}}}function JUe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function Kye(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function htr(e,{id:t,defaultColor:n,defaultMarkerStart:r,defaultMarkerEnd:s}){const a=new Set;return e.reduce((i,l)=>([l.markerStart||r,l.markerEnd||s].forEach(c=>{if(c&&typeof c=="object"){const u=Kye(c,t);a.has(u)||(i.push({id:u,color:c.color||n,...c}),a.add(u))}}),i),[]).sort((i,l)=>i.id.localeCompare(l.id))}const MEt=1e3,ptr=10,c_e={nodeOrigin:[0,0],nodeExtent:yD,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},mtr={...c_e,checkEquality:!0};function u_e(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function gtr(e,t,n){const r=u_e(c_e,n);for(const s of e.values())if(s.parentId)f_e(s,e,t,r);else{const a=ML(s,r.nodeOrigin),i=jN(s.extent)?s.extent:r.nodeExtent,l=kC(a,i,x0(s));s.internals.positionAbsolute=l}}function vtr(e,t){if(!e.handles)return e.measured?t?.internals.handleBounds:void 0;const n=[],r=[];for(const s of e.handles){const a={id:s.id,width:s.width??1,height:s.height??1,nodeId:e.id,x:s.x,y:s.y,position:s.position,type:s.type};s.type==="source"?n.push(a):s.type==="target"&&r.push(a)}return{source:n,target:r}}function d_e(e){return e==="manual"}function Xye(e,t,n,r={}){const s=u_e(mtr,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!d_e(s.zIndexMode)?MEt:0;let c=e.length>0,u=!1;t.clear(),n.clear();for(const d of e){let f=i.get(d.id);if(s.checkEquality&&d===f?.internals.userNode)t.set(d.id,f);else{const h=ML(d,s.nodeOrigin),p=jN(d.extent)?d.extent:s.nodeExtent,m=kC(h,p,x0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:vtr(d,f),z:DEt(d,l,s.zIndexMode),userNode:d}},t.set(d.id,f)}(f.measured===void 0||f.measured.width===void 0||f.measured.height===void 0)&&!f.hidden&&(c=!1),d.parentId&&f_e(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function ytr(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 f_e(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=u_e(c_e,r),u=e.parentId,d=t.get(u);if(!d){console.warn(`Parent node ${u} not found. Please make sure that parent nodes are in front of their child nodes in the nodes array.`);return}ytr(e,n),s&&!d.parentId&&d.internals.rootParentIndex===void 0&&c==="auto"&&(d.internals.rootParentIndex=++s.i,d.internals.z=d.internals.z+s.i*ptr),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!d_e(c)?MEt:0,{x:h,y:p,z:m}=btr(e,d,i,l,f,c),{positionAbsolute:v}=e.internals,y=h!==v.x||p!==v.y;(y||m!==e.internals.z)&&t.set(e.id,{...e,internals:{...e.internals,positionAbsolute:y?{x:h,y:p}:v,z:m}})}function DEt(e,t,n){const r=Ng(e.zIndex)?e.zIndex:0;return d_e(n)?r:r+(e.selected?t:0)}function btr(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=x0(e),u=ML(e,n),d=jN(e.extent)?kC(u,e.extent,c):u;let f=kC({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=CEt(f,c,t));const h=DEt(e,s,a),p=t.internals.z??0;return{x:f.x,y:f.y,z:p>=h?p+1:h}}function h_e(e,t,n,r=[0,0]){const s=[],a=new Map;for(const i of e){const l=t.get(i.parentId);if(!l)continue;const c=a.get(i.parentId)?.expandedRect??TN(l),u=EEt(c,i.rect);a.set(i.parentId,{expandedRect:u,parent:l})}return a.size>0&&a.forEach(({expandedRect:i,parent:l},c)=>{const u=l.internals.positionAbsolute,d=x0(l),f=l.origin??r,h=i.x<u.x?Math.round(Math.abs(u.x-i.x)):0,p=i.y<u.y?Math.round(Math.abs(u.y-i.y)):0,m=Math.max(d.width,Math.round(i.width)),v=Math.max(d.height,Math.round(i.height)),y=(m-d.width)*f[0],b=(v-d.height)*f[1];(h>0||p>0||y||b)&&(s.push({id:c,type:"position",position:{x:l.position.x-h+y,y:l.position.y-p+b}}),n.get(c)?.forEach(x=>{e.some(w=>w.id===x.id)||s.push({id:x.id,type:"position",position:{x:x.position.x+h,y:x.position.y+p}})})),(d.width<i.width||d.height<i.height||h||p)&&s.push({id:c,type:"dimensions",setAttributes:!0,dimensions:{width:m+(h?f[0]*h-y:0),height:v+(p?f[1]*p-b:0)}})}),s}function xtr(e,t,n,r,s,a,i){const l=r?.querySelector(".xyflow__viewport");let c=!1;if(!l)return{changes:[],updatedInternals:c};const u=[],d=window.getComputedStyle(l),{m22:f}=new window.DOMMatrixReadOnly(d.transform),h=[];for(const p of e.values()){const m=t.get(p.id);if(!m)continue;if(m.hidden){t.set(m.id,{...m,internals:{...m.internals,handleBounds:void 0}}),c=!0;continue}const v=o_e(p.nodeElement),y=m.measured.width!==v.width||m.measured.height!==v.height;if(!!(v.width&&v.height&&(y||!m.internals.handleBounds||p.force))){const x=p.nodeElement.getBoundingClientRect(),w=jN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=CEt(k,v,t.get(m.parentId)):w&&(k=kC(k,w,v));const O={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:ZUe("source",p.nodeElement,x,f,m.id),target:ZUe("target",p.nodeElement,x,f,m.id)}}};t.set(m.id,O),m.parentId&&f_e(O,t,n,{nodeOrigin:s,zIndexMode:i}),c=!0,y&&(u.push({id:m.id,type:"dimensions",dimensions:v}),m.expandParent&&m.parentId&&h.push({id:m.id,parentId:m.parentId,rect:TN(O,s)}))}}if(h.length>0){const p=h_e(h,t,n,s);u.push(...p)}return{changes:u,updatedInternals:c}}async function wtr({delta:e,panZoom:t,transform:n,translateExtent:r,width:s,height:a}){if(!t||!e.x&&!e.y)return Promise.resolve(!1);const i=await t.setViewportConstrained({x:n[0]+e.x,y:n[1]+e.y,zoom:n[2]},[[0,0],[s,a]],r),l=!!i&&(i.x!==n[0]||i.y!==n[1]||i.k!==n[2]);return Promise.resolve(l)}function eqe(e,t,n,r,s,a){let i=s;const l=r.get(i)||new Map;r.set(i,l.set(n,t)),i=`${s}-${e}`;const c=r.get(i)||new Map;if(r.set(i,c.set(n,t)),a){i=`${s}-${e}-${a}`;const u=r.get(i)||new Map;r.set(i,u.set(n,t))}}function LEt(e,t,n){e.clear(),t.clear();for(const r of n){const{source:s,target:a,sourceHandle:i=null,targetHandle:l=null}=r,c={edgeId:r.id,source:s,target:a,sourceHandle:i,targetHandle:l},u=`${s}-${i}--${a}-${l}`,d=`${a}-${l}--${s}-${i}`;eqe("source",c,d,e,s,i),eqe("target",c,u,e,a,l),t.set(r.id,r)}}function FEt(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:FEt(n,t):!1}function tqe(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 Str(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!FEt(i,e))&&(i.draggable||t&&typeof i.draggable>"u")){const l=e.get(a);l&&s.set(a,{id:a,position:l.position||{x:0,y:0},distance:{x:n.x-l.internals.positionAbsolute.x,y:n.y-l.internals.positionAbsolute.y},extent:l.extent,parentId:l.parentId,origin:l.origin,expandParent:l.expandParent,internals:{positionAbsolute:l.internals.positionAbsolute||{x:0,y:0}},measured:{width:l.measured.width??0,height:l.measured.height??0}})}return s}function yre({nodeId:e,dragItems:t,nodeLookup:n,dragging:r=!0}){const s=[];for(const[i,l]of t){const c=n.get(i)?.internals.userNode;c&&s.push({...c,position:l.position,dragging:r})}if(!e)return[s[0],s];const a=n.get(e)?.internals.userNode;return[a?{...a,position:t.get(e)?.position||a.position,dragging:r}:s[0],s]}function ktr({dragItems:e,snapGrid:t,x:n,y:r}){const s=e.values().next().value;if(!s)return null;const a={x:n-s.distance.x,y:r-s.distance.y},i=LL(a,t);return{x:i.x-a.x,y:i.y-a.y}}function Otr({onNodeMouseDown:e,getStoreItems:t,onDragStart:n,onDrag:r,onDragStop:s}){let a={x:null,y:null},i=0,l=new Map,c=!1,u={x:0,y:0},d=null,f=!1,h=null,p=!1,m=!1,v=null;function y({noDragClassName:x,handleSelector:w,domNode:k,isSelectable:O,nodeId:_,nodeClickDistance:T=0}){h=Ah(k);function E({x:$,y:z}){const{nodeLookup:D,nodeExtent:q,snapGrid:H,snapToGrid:V,nodeOrigin:B,onNodeDrag:W,onSelectionDrag:L,onError:G,updateNodePositions:M}=t();a={x:$,y:z};let R=!1;const F=l.size>1,U=F&&q?Qye(DL(l)):null,Q=F&&V?ktr({dragItems:l,snapGrid:H,x:$,y:z}):null;for(const[te,J]of l){if(!D.has(te))continue;let ee={x:$-J.distance.x,y:z-J.distance.y};V&&(ee=Q?{x:Math.round(ee.x+Q.x),y:Math.round(ee.y+Q.y)}:LL(ee,H));let re=null;if(F&&q&&!J.extent&&U){const{positionAbsolute:ne}=J.internals,se=ne.x-U.x+q[0][0],ce=ne.x+J.measured.width-U.x2+q[1][0],le=ne.y-U.y+q[0][1],ve=ne.y+J.measured.height-U.y2+q[1][1];re=[[se,le],[ce,ve]]}const{position:ae,positionAbsolute:X}=OEt({nodeId:te,nextPosition:ee,nodeLookup:D,nodeExtent:re||q,nodeOrigin:B,onError:G});R=R||J.position.x!==ae.x||J.position.y!==ae.y,J.position=ae,J.internals.positionAbsolute=X}if(m=m||R,!!R&&(M(l,!0),v&&(r||W||!_&&L))){const[te,J]=yre({nodeId:_,dragItems:l,nodeLookup:D});r?.(v,l,te,J),W?.(v,te,J),_||L?.(v,J)}}async function N(){if(!d)return;const{transform:$,panBy:z,autoPanSpeed:D,autoPanOnNodeDrag:q}=t();if(!q){c=!1,cancelAnimationFrame(i);return}const[H,V]=_Et(u,d,D);(H!==0||V!==0)&&(a.x=(a.x??0)-H/$[2],a.y=(a.y??0)-V/$[2],await z({x:H,y:V})&&E(a)),i=requestAnimationFrame(N)}function I($){const{nodeLookup:z,multiSelectionActive:D,nodesDraggable:q,transform:H,snapGrid:V,snapToGrid:B,selectNodesOnDrag:W,onNodeDragStart:L,onSelectionDragStart:G,unselectNodesAndEdges:M}=t();f=!0,(!W||!O)&&!D&&_&&(z.get(_)?.selected||M()),O&&W&&_&&e?.(_);const R=gM($.sourceEvent,{transform:H,snapGrid:V,snapToGrid:B,containerBounds:d});if(a=R,l=Str(z,q,R,_),l.size>0&&(n||L||!_&&G)){const[F,U]=yre({nodeId:_,dragItems:l,nodeLookup:z});n?.($.sourceEvent,l,F,U),L?.($.sourceEvent,F,U),_||G?.($.sourceEvent,U)}}const A=rEt().clickDistance(T).on("start",$=>{const{domNode:z,nodeDragThreshold:D,transform:q,snapGrid:H,snapToGrid:V}=t();d=z?.getBoundingClientRect()||null,p=!1,m=!1,v=$.sourceEvent,D===0&&I($),a=gM($.sourceEvent,{transform:q,snapGrid:H,snapToGrid:V,containerBounds:d}),u=Ig($.sourceEvent,d)}).on("drag",$=>{const{autoPanOnNodeDrag:z,transform:D,snapGrid:q,snapToGrid:H,nodeDragThreshold:V,nodeLookup:B}=t(),W=gM($.sourceEvent,{transform:D,snapGrid:q,snapToGrid:H,containerBounds:d});if(v=$.sourceEvent,($.sourceEvent.type==="touchmove"&&$.sourceEvent.touches.length>1||_&&!B.has(_))&&(p=!0),!p){if(!c&&z&&f&&(c=!0,N()),!f){const L=Ig($.sourceEvent,d),G=L.x-u.x,M=L.y-u.y;Math.sqrt(G*G+M*M)>V&&I($)}(a.x!==W.xSnapped||a.y!==W.ySnapped)&&l&&f&&(u=Ig($.sourceEvent,d),E(W))}}).on("end",$=>{if(!(!f||p)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:z,updateNodePositions:D,onNodeDragStop:q,onSelectionDragStop:H}=t();if(m&&(D(l,!1),m=!1),s||q||!_&&H){const[V,B]=yre({nodeId:_,dragItems:l,nodeLookup:z,dragging:!1});s?.($.sourceEvent,l,V,B),q?.($.sourceEvent,V,B),_||H?.($.sourceEvent,B)}}}).filter($=>{const z=$.target;return!$.button&&(!x||!tqe(z,`.${x}`,k))&&(!w||tqe(z,w,k))});h.call(A)}function b(){h?.on(".drag",null)}return{update:y,destroy:b}}function Ctr(e,t,n){const r=[],s={x:e.x-n,y:e.y-n,width:n*2,height:n*2};for(const a of t.values())wD(s,TN(a))>0&&r.push(a);return r}const _tr=250;function Etr(e,t,n,r){let s=[],a=1/0;const i=Ctr(e,n,t+_tr);for(const l of i){const c=[...l.internals.handleBounds?.source??[],...l.internals.handleBounds?.target??[]];for(const u of c){if(r.nodeId===u.nodeId&&r.type===u.type&&r.id===u.id)continue;const{x:d,y:f}=OC(l,u,u.position,!0),h=Math.sqrt(Math.pow(d-e.x,2)+Math.pow(f-e.y,2));h>t||(h<a?(s=[{...u,x:d,y:f}],a=h):h===a&&s.push({...u,x:d,y:f}))}}if(!s.length)return null;if(s.length>1){const l=r.type==="source"?"target":"source";return s.find(c=>c.type===l)??s[0]}return s[0]}function zEt(e,t,n,r,s,a=!1){const i=r.get(e);if(!i)return null;const l=s==="strict"?i.internals.handleBounds?.[t]:[...i.internals.handleBounds?.source??[],...i.internals.handleBounds?.target??[]],c=(n?l?.find(u=>u.id===n):l?.[0])??null;return c&&a?{...c,...OC(i,c,c.position,!0)}:c}function BEt(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function Ttr(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const UEt=()=>!0;function jtr(e,{connectionMode:t,connectionRadius:n,handleId:r,nodeId:s,edgeUpdaterType:a,isTarget:i,domNode:l,nodeLookup:c,lib:u,autoPanOnConnect:d,flowId:f,panBy:h,cancelConnection:p,onConnectStart:m,onConnect:v,onConnectEnd:y,isValidConnection:b=UEt,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:O,autoPanSpeed:_,dragThreshold:T=1,handleDomNode:E}){const N=NEt(e.target);let I=0,A;const{x:$,y:z}=Ig(e),D=BEt(a,E),q=l?.getBoundingClientRect();let H=!1;if(!q||!D)return;const V=zEt(s,D,r,c,t);if(!V)return;let B=Ig(e,q),W=!1,L=null,G=!1,M=null;function R(){if(!d||!q)return;const[ae,X]=_Et(B,q,_);h({x:ae,y:X}),I=requestAnimationFrame(R)}const F={...V,nodeId:s,type:D,position:V.position},U=c.get(s);let te={inProgress:!0,isValid:null,from:OC(U,F,ar.Left,!0),fromHandle:F,fromPosition:F.position,fromNode:U,to:B,toHandle:null,toPosition:qUe[F.position],toNode:null,pointer:B};function J(){H=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:D})}T===0&&J();function ee(ae){if(!H){const{x:ve,y:ye}=Ig(ae),Te=ve-$,Me=ye-z;if(!(Te*Te+Me*Me>T*T))return;J()}if(!O()||!F){re(ae);return}const X=k();B=Ig(ae,q),A=Etr(FL(B,X,!1,[1,1]),n,c,F),W||(R(),W=!0);const ne=qEt(ae,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});M=ne.handleDomNode,L=ne.connection,G=Ttr(!!A,ne.isValid);const se=c.get(s),ce=se?OC(se,F,ar.Left,!0):te.from,le={...te,from:ce,isValid:G,to:ne.toHandle&&G?JU({x:ne.toHandle.x,y:ne.toHandle.y},X):B,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:qUe[F.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:B};w(le),te=le}function re(ae){if(!("touches"in ae&&ae.touches.length>0)){if(H){(A||M)&&L&&G&&v?.(L);const{inProgress:X,...ne}=te,se={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(ae,se),a&&x?.(ae,se)}p(),cancelAnimationFrame(I),W=!1,G=!1,L=null,M=null,N.removeEventListener("mousemove",ee),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",ee),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",ee),N.addEventListener("mouseup",re),N.addEventListener("touchmove",ee),N.addEventListener("touchend",re)}function qEt(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=UEt,nodeLookup:d}){const f=a==="target",h=t?i.querySelector(`.${l}-flow__handle[data-id="${c}-${t?.nodeId}-${t?.id}-${t?.type}"]`):null,{x:p,y:m}=Ig(e),v=i.elementFromPoint(p,m),y=v?.classList.contains(`${l}-flow__handle`)?v:h,b={handleDomNode:y,isValid:!1,connection:null,toHandle:null};if(y){const x=BEt(void 0,y),w=y.getAttribute("data-nodeid"),k=y.getAttribute("data-handleid"),O=y.classList.contains("connectable"),_=y.classList.contains("connectableend");if(!w||!x)return b;const T={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=T;const N=O&&_&&(n===_N.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=N&&u(T),b.toHandle=zEt(w,x,k,d,n,!0)}return b}const Jye={onPointerDown:jtr,isValid:qEt};function Ntr({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Ah(e);function a({translateExtent:l,width:c,height:u,zoomStep:d=1,pannable:f=!0,zoomable:h=!0,inversePan:p=!1}){const m=w=>{if(w.sourceEvent.type!=="wheel"||!t)return;const k=n(),O=w.sourceEvent.ctrlKey&&SD()?10:1,_=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,T=k[2]*Math.pow(2,_*O);t.scaleTo(T)};let v=[0,0];const y=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])},b=w=>{const k=n();if(w.sourceEvent.type!=="mousemove"&&w.sourceEvent.type!=="touchmove"||!t)return;const O=[w.sourceEvent.clientX??w.sourceEvent.touches[0].clientX,w.sourceEvent.clientY??w.sourceEvent.touches[0].clientY],_=[O[0]-v[0],O[1]-v[1]];v=O;const T=r()*Math.max(k[2],Math.log(k[2]))*(p?-1:1),E={x:k[0]-_[0]*T,y:k[1]-_[1]*T},N=[[0,0],[c,u]];t.setViewportConstrained({x:E.x,y:E.y,zoom:k[2]},N,l)},x=yEt().on("start",y).on("zoom",f?b:null).on("zoom.wheel",h?m:null);s.call(x,{})}function i(){s.on("zoom",null)}return{update:a,destroy:i,pointer:yg}}const gZ=e=>({x:e.x,y:e.y,zoom:e.k}),bre=({x:e,y:t,zoom:n})=>hZ.translate(e,t).scale(n),WT=(e,t)=>e.target.closest(`.${t}`),VEt=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),Itr=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,xre=(e,t=0,n=Itr,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},HEt=e=>{const t=e.ctrlKey&&SD()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function Atr({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(WT(d,t))return d.ctrlKey&&d.preventDefault(),!1;d.preventDefault(),d.stopImmediatePropagation();const f=n.property("__zoom").k||1;if(d.ctrlKey&&i){const y=yg(d),b=HEt(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const h=d.deltaMode===1?20:1;let p=s===TO.Vertical?0:d.deltaX*h,m=s===TO.Horizontal?0:d.deltaY*h;!SD()&&d.shiftKey&&s!==TO.Vertical&&(p=d.deltaY*h,m=0),r.translateBy(n,-(p/f)*a,-(m/f)*a,{internal:!0});const v=gZ(n.property("__zoom"));clearTimeout(e.panScrollTimeout),e.isPanScrolling?(c?.(d,v),e.panScrollTimeout=setTimeout(()=>{u?.(d,v),e.isPanScrolling=!1},150)):(e.isPanScrolling=!0,l?.(d,v))}}function Rtr({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=WT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function Ptr({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=gZ(r.transform);e.mouseButton=r.sourceEvent?.button||0,e.isZoomingOrPanning=!0,e.prevViewport=s,r.sourceEvent?.type==="mousedown"&&t(!0),n&&n?.(r.sourceEvent,s)}}function $tr({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&VEt(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,gZ(a.transform))}}function Mtr({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&VEt(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=gZ(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function Dtr({zoomActivationKeyPressed:e,zoomOnScroll:t,zoomOnPinch:n,panOnDrag:r,panOnScroll:s,zoomOnDoubleClick:a,userSelectionActive:i,noWheelClassName:l,noPanClassName:c,lib:u,connectionInProgress:d}){return f=>{const h=e||t,p=n&&f.ctrlKey,m=f.type==="wheel";if(f.button===1&&f.type==="mousedown"&&(WT(f,`${u}-flow__node`)||WT(f,`${u}-flow__edge`)))return!0;if(!r&&!h&&!s&&!a&&!n||i||d&&!m||WT(f,l)&&m||WT(f,c)&&(!m||s&&m&&!e)||!n&&f.ctrlKey&&m)return!1;if(!n&&f.type==="touchstart"&&f.touches?.length>1)return f.preventDefault(),!1;if(!h&&!s&&!p&&m||!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||m)&&v}}function Ltr({domNode:e,minZoom:t,maxZoom:n,translateExtent:r,viewport:s,onPanZoom:a,onPanZoomStart:i,onPanZoomEnd:l,onDraggingChange:c}){const u={isZoomingOrPanning:!1,usedRightMouseButton:!1,prevViewport:{},mouseButton:0,timerId:void 0,panScrollTimeout:void 0,isPanScrolling:!1},d=e.getBoundingClientRect(),f=yEt().scaleExtent([t,n]).translateExtent(r),h=Ah(e).call(f);x({x:s.x,y:s.y,zoom:EN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const p=h.on("wheel.zoom"),m=h.on("dblclick.zoom");f.wheelDelta(HEt);function v(A,$){return h?new Promise(z=>{f?.interpolate($?.interpolate==="linear"?Cx:F9).transform(xre(h,$?.duration,$?.ease,()=>z(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:$,onPaneContextMenu:z,userSelectionActive:D,panOnScroll:q,panOnDrag:H,panOnScrollMode:V,panOnScrollSpeed:B,preventScrolling:W,zoomOnPinch:L,zoomOnScroll:G,zoomOnDoubleClick:M,zoomActivationKeyPressed:R,lib:F,onTransformChange:U,connectionInProgress:Q,paneClickDistance:te,selectionOnDrag:J}){D&&!u.isZoomingOrPanning&&b();const ee=q&&!R&&!D;f.clickDistance(J?1/0:!Ng(te)||te<0?0:te);const re=ee?Atr({zoomPanValues:u,noWheelClassName:A,d3Selection:h,d3Zoom:f,panOnScrollMode:V,panOnScrollSpeed:B,zoomOnPinch:L,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):Rtr({noWheelClassName:A,preventScrolling:W,d3ZoomHandler:p});if(h.on("wheel.zoom",re,{passive:!1}),!D){const X=Ptr({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const ne=$tr({zoomPanValues:u,panOnDrag:H,onPaneContextMenu:!!z,onPanZoom:a,onTransformChange:U});f.on("zoom",ne);const se=Mtr({zoomPanValues:u,panOnDrag:H,panOnScroll:q,onPaneContextMenu:z,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const ae=Dtr({zoomActivationKeyPressed:R,panOnDrag:H,zoomOnScroll:G,panOnScroll:q,zoomOnDoubleClick:M,zoomOnPinch:L,userSelectionActive:D,noPanClassName:$,noWheelClassName:A,lib:F,connectionInProgress:Q});f.filter(ae),M?h.on("dblclick.zoom",m):h.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,$,z){const D=bre(A),q=f?.constrain()(D,$,z);return q&&await v(q),new Promise(H=>H(q))}async function w(A,$){const z=bre(A);return await v(z,$),new Promise(D=>D(z))}function k(A){if(h){const $=bre(A),z=h.property("__zoom");(z.k!==A.zoom||z.x!==A.x||z.y!==A.y)&&f?.transform(h,$,null,{sync:!0})}}function O(){const A=h?vEt(h.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,$){return h?new Promise(z=>{f?.interpolate($?.interpolate==="linear"?Cx:F9).scaleTo(xre(h,$?.duration,$?.ease,()=>z(!0)),A)}):Promise.resolve(!1)}function T(A,$){return h?new Promise(z=>{f?.interpolate($?.interpolate==="linear"?Cx:F9).scaleBy(xre(h,$?.duration,$?.ease,()=>z(!0)),A)}):Promise.resolve(!1)}function E(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const $=!Ng(A)||A<0?0:A;f?.clickDistance($)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:O,scaleTo:_,scaleBy:T,setScaleExtent:E,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var NN;(function(e){e.Line="line",e.Handle="handle"})(NN||(NN={}));function Ftr({width:e,prevWidth:t,height:n,prevHeight:r,affectsX:s,affectsY:a}){const i=e-t,l=n-r,c=[i>0?1:i<0?-1:0,l>0?1:l<0?-1:0];return i&&s&&(c[0]=c[0]*-1),l&&a&&(c[1]=c[1]*-1),c}function nqe(e){const t=e.includes("right")||e.includes("left"),n=e.includes("bottom")||e.includes("top"),r=e.includes("left"),s=e.includes("top");return{isHorizontal:t,isVertical:n,affectsX:r,affectsY:s}}function vw(e,t){return Math.max(0,t-e)}function yw(e,t){return Math.max(0,e-t)}function cz(e,t,n){return Math.max(0,t-e,e-n)}function rqe(e,t){return e?!t:t}function ztr(e,t,n,r,s,a,i,l){let{affectsX:c,affectsY:u}=t;const{isHorizontal:d,isVertical:f}=t,h=d&&f,{xSnapped:p,ySnapped:m}=n,{minWidth:v,maxWidth:y,minHeight:b,maxHeight:x}=r,{x:w,y:k,width:O,height:_,aspectRatio:T}=e;let E=Math.floor(d?p-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=O+(c?-E:E),A=_+(u?-N:N),$=-a[0]*O,z=-a[1]*_;let D=cz(I,v,y),q=cz(A,b,x);if(i){let B=0,W=0;c&&E<0?B=vw(w+E+$,i[0][0]):!c&&E>0&&(B=yw(w+I+$,i[1][0])),u&&N<0?W=vw(k+N+z,i[0][1]):!u&&N>0&&(W=yw(k+A+z,i[1][1])),D=Math.max(D,B),q=Math.max(q,W)}if(l){let B=0,W=0;c&&E>0?B=yw(w+E,l[0][0]):!c&&E<0&&(B=vw(w+I,l[1][0])),u&&N>0?W=yw(k+N,l[0][1]):!u&&N<0&&(W=vw(k+A,l[1][1])),D=Math.max(D,B),q=Math.max(q,W)}if(s){if(d){const B=cz(I/T,b,x)*T;if(D=Math.max(D,B),i){let W=0;!c&&!u||c&&!u&&h?W=yw(k+z+I/T,i[1][1])*T:W=vw(k+z+(c?E:-E)/T,i[0][1])*T,D=Math.max(D,W)}if(l){let W=0;!c&&!u||c&&!u&&h?W=vw(k+I/T,l[1][1])*T:W=yw(k+(c?E:-E)/T,l[0][1])*T,D=Math.max(D,W)}}if(f){const B=cz(A*T,v,y)/T;if(q=Math.max(q,B),i){let W=0;!c&&!u||u&&!c&&h?W=yw(w+A*T+$,i[1][0])/T:W=vw(w+(u?N:-N)*T+$,i[0][0])/T,q=Math.max(q,W)}if(l){let W=0;!c&&!u||u&&!c&&h?W=vw(w+A*T,l[1][0])/T:W=yw(w+(u?N:-N)*T,l[0][0])/T,q=Math.max(q,W)}}}N=N+(N<0?q:-q),E=E+(E<0?D:-D),s&&(h?I>A*T?N=(rqe(c,u)?-E:E)/T:E=(rqe(c,u)?-N:N)*T:d?(N=E/T,u=c):(E=N*T,c=u));const H=c?w+E:w,V=u?k+N:k;return{width:O+(c?-E:E),height:_+(u?-N:N),x:a[0]*E*(c?-1:1)+H,y:a[1]*N*(u?-1:1)+V}}const WEt={width:0,height:0,x:0,y:0},Btr={...WEt,pointerX:0,pointerY:0,aspectRatio:1};function Utr(e){return[[0,0],[e.measured.width,e.measured.height]]}function qtr(e,t,n){const r=t.position.x+e.position.x,s=t.position.y+e.position.y,a=e.measured.width??0,i=e.measured.height??0,l=n[0]*a,c=n[1]*i;return[[r-l,s-c],[r+a-l,s+i-c]]}function Vtr({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Ah(e);let i={controlDirection:nqe("bottom-right"),boundaries:{minWidth:0,minHeight:0,maxWidth:Number.MAX_VALUE,maxHeight:Number.MAX_VALUE},resizeDirection:void 0,keepAspectRatio:!1};function l({controlPosition:u,boundaries:d,keepAspectRatio:f,resizeDirection:h,onResizeStart:p,onResize:m,onResizeEnd:v,shouldResize:y}){let b={...WEt},x={...Btr};i={boundaries:d,resizeDirection:h,keepAspectRatio:f,controlDirection:nqe(u)};let w,k=null,O=[],_,T,E,N=!1;const I=rEt().on("start",A=>{const{nodeLookup:$,transform:z,snapGrid:D,snapToGrid:q,nodeOrigin:H,paneDomNode:V}=n();if(w=$.get(t),!w)return;k=V?.getBoundingClientRect()??null;const{xSnapped:B,ySnapped:W}=gM(A.sourceEvent,{transform:z,snapGrid:D,snapToGrid:q,containerBounds:k});b={width:w.measured.width??0,height:w.measured.height??0,x:w.position.x??0,y:w.position.y??0},x={...b,pointerX:B,pointerY:W,aspectRatio:b.width/b.height},_=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(_=$.get(w.parentId),T=_&&w.extent==="parent"?Utr(_):void 0),O=[],E=void 0;for(const[L,G]of $)if(G.parentId===t&&(O.push({id:L,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const M=qtr(G,w,G.origin??H);E?E=[[Math.min(M[0][0],E[0][0]),Math.min(M[0][1],E[0][1])],[Math.max(M[1][0],E[1][0]),Math.max(M[1][1],E[1][1])]]:E=M}p?.(A,{...b})}).on("drag",A=>{const{transform:$,snapGrid:z,snapToGrid:D,nodeOrigin:q}=n(),H=gM(A.sourceEvent,{transform:$,snapGrid:z,snapToGrid:D,containerBounds:k}),V=[];if(!w)return;const{x:B,y:W,width:L,height:G}=b,M={},R=w.origin??q,{width:F,height:U,x:Q,y:te}=ztr(x,i.controlDirection,H,i.boundaries,i.keepAspectRatio,R,T,E),J=F!==L,ee=U!==G,re=Q!==B&&J,ae=te!==W&ⅇif(!re&&!ae&&!J&&!ee)return;if((re||ae||R[0]===1||R[1]===1)&&(M.x=re?Q:b.x,M.y=ae?te:b.y,b.x=M.x,b.y=M.y,O.length>0)){const ce=Q-B,le=te-W;for(const ve of O)ve.position={x:ve.position.x-ce+R[0]*(F-L),y:ve.position.y-le+R[1]*(U-G)},V.push(ve)}if((J||ee)&&(M.width=J&&(!i.resizeDirection||i.resizeDirection==="horizontal")?F:b.width,M.height=ee&&(!i.resizeDirection||i.resizeDirection==="vertical")?U:b.height,b.width=M.width,b.height=M.height),_&&w.expandParent){const ce=R[0]*(M.width??0);M.x&&M.x<ce&&(b.x=ce,x.x=x.x-(M.x-ce));const le=R[1]*(M.height??0);M.y&&M.y<le&&(b.y=le,x.y=x.y-(M.y-le))}const X=Ftr({width:b.width,prevWidth:L,height:b.height,prevHeight:G,affectsX:i.controlDirection.affectsX,affectsY:i.controlDirection.affectsY}),ne={...b,direction:X};y?.(A,ne)!==!1&&(N=!0,m?.(A,ne),r(M,V))}).on("end",A=>{N&&(v?.(A,{...b}),s?.({...b}),N=!1)});a.call(I)}function c(){a.on(".drag",null)}return{update:l,destroy:c}}const Htr={},sqe=e=>{let t;const n=new Set,r=(d,f)=>{const h=typeof d=="function"?d(t):d;if(!Object.is(h,t)){const p=t;t=f??(typeof h!="object"||h===null)?h:Object.assign({},t,h),n.forEach(m=>m(t,p))}},s=()=>t,c={setState:r,getState:s,getInitialState:()=>u,subscribe:d=>(n.add(d),()=>n.delete(d)),destroy:()=>{(Htr?"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()}},u=t=e(r,s,c);return c},Wtr=e=>e?sqe(e):sqe,{useDebugValue:Ztr}=ze,{useSyncExternalStoreWithSelector:Gtr}=qRn,Qtr=e=>e;function ZEt(e,t=Qtr,n){const r=Gtr(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return Ztr(r),r}const aqe=(e,t)=>{const n=Wtr(e),r=(s,a=t)=>ZEt(n,s,a);return Object.assign(r,n),r},Ytr=(e,t)=>e?aqe(e,t):aqe;function io(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,s]of e)if(!Object.is(s,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 vZ=g.createContext(null),Ktr=vZ.Provider,GEt=$y.error001();function Zs(e,t){const n=g.useContext(vZ);if(n===null)throw new Error(GEt);return ZEt(n,e,t)}function To(){const e=g.useContext(vZ);if(e===null)throw new Error(GEt);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const iqe={display:"none"},Xtr={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},QEt="react-flow__node-desc",YEt="react-flow__edge-desc",Jtr="react-flow__aria-live",enr=e=>e.ariaLiveMessage,tnr=e=>e.ariaLabelConfig;function nnr({rfId:e}){const t=Zs(enr);return o.jsx("div",{id:`${Jtr}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:Xtr,children:t})}function rnr({rfId:e,disableKeyboardA11y:t}){const n=Zs(tnr);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${QEt}-${e}`,style:iqe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${YEt}-${e}`,style:iqe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(nnr,{rfId:e})]})}const zL=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Gl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});zL.displayName="Panel";function snr({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(zL,{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:o.jsx("a",{href:"https://reactflow.dev",target:"_blank",rel:"noopener noreferrer","aria-label":"React Flow attribution",children:"React Flow"})})}const anr=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}},uz=e=>e.id;function inr(e,t){return io(e.selectedNodes.map(uz),t.selectedNodes.map(uz))&&io(e.selectedEdges.map(uz),t.selectedEdges.map(uz))}function onr({onSelectionChange:e}){const t=To(),{selectedNodes:n,selectedEdges:r}=Zs(anr,inr);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const lnr=e=>!!e.onSelectionChangeHandlers;function cnr({onSelectionChange:e}){const t=Zs(lnr);return e||t?o.jsx(onr,{onSelectionChange:e}):null}const ebe=typeof window<"u"?g.useLayoutEffect:g.useEffect,KEt=[0,0],unr={x:0,y:0,zoom:1},dnr=["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"],oqe=[...dnr,"rfId"],fnr=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}),lqe={translateExtent:yD,nodeOrigin:KEt,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function hnr(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Zs(fnr,io),u=To();ebe(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=lqe,l()}),[]);const d=g.useRef(lqe);return ebe(()=>{for(const f of oqe){const h=e[f],p=d.current[f];h!==p&&(typeof e[f]>"u"||(f==="nodes"?t(h):f==="edges"?n(h):f==="minZoom"?r(h):f==="maxZoom"?s(h):f==="translateExtent"?a(h):f==="nodeExtent"?i(h):f==="ariaLabelConfig"?u.setState({ariaLabelConfig:ntr(h)}):f==="fitView"?u.setState({fitViewQueued:h}):f==="fitViewOptions"?u.setState({fitViewOptions:h}):u.setState({[f]:h})))}d.current=e},oqe.map(f=>e[f])),null}function cqe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function pnr(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=cqe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:cqe()?.matches?"dark":"light"}const uqe=typeof document<"u"?document:null;function kD(e=null,t={target:uqe,actInsideInputWithModifier:!0}){const[n,r]=g.useState(!1),s=g.useRef(!1),a=g.useRef(new Set([])),[i,l]=g.useMemo(()=>{if(e!==null){const u=(Array.isArray(e)?e:[e]).filter(f=>typeof f=="string").map(f=>f.replace("+",`
|
|
235
235
|
`).replace(`
|
|
236
236
|
|
|
237
237
|
`,`
|
|
@@ -691,7 +691,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
|
|
|
691
691
|
}
|
|
692
692
|
]`,pSs=[{name:"input",description:"What the agent receives. A string or any JSON value.",required:!0},{name:"groundTruth",description:"Expected answer used by scorers.",required:!1},{name:"metadata",description:"Any object, useful for filtering and grouping.",required:!1}];function mSs(){const{isCopied:e,handleCopy:t}=ed({text:yrt,showToast:!1});return o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx("p",{className:"text-ui-sm text-neutral5 flex h-8 items-center font-medium",children:"Each item looks like this"}),o.jsx("dl",{className:"border-border1 divide-border1 divide-y rounded-lg border",children:pSs.map(n=>o.jsxs("div",{className:"grid grid-cols-[7rem_1fr] gap-3 px-3 py-2.5",children:[o.jsx("dt",{className:"text-ui-xs text-neutral6 font-mono",children:n.name}),o.jsxs("dd",{className:"text-ui-xs text-neutral4 flex flex-col items-start gap-1.5",children:[o.jsx("span",{children:n.description}),n.required?o.jsx(xt,{variant:"green",size:"xs",children:"required"}):o.jsx(xt,{variant:"neutral",emphasis:"muted",size:"xs",children:"optional"})]})]},n.name))}),o.jsxs("div",{className:"border-border1 overflow-hidden rounded-lg border",children:[o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center justify-between border-b py-1.5 pr-1.5 pl-3",children:[o.jsx("span",{className:"text-ui-xs text-neutral4 font-mono",children:"example.json"}),o.jsx(ie,{icon:e?o.jsx(Fn,{}):o.jsx(mu,{}),variant:"ghost",size:"xs",onClick:t,children:e?"Copied":"Copy"})]}),o.jsx(Vr,{variant:"embedded",language:"json",editable:!1,lineNumbers:!1,showCopyButton:!1,value:yrt,className:"p-3"})]}),o.jsx(ie,{variant:"ghost",as:"a",href:hSs,target:"_blank",rel:"noopener noreferrer",className:"self-start",icon:o.jsx(Cs,{}),children:"Datasets documentation"})]})}const Goe=10,gSs=`[
|
|
693
693
|
{ "input": "…", "groundTruth": "…" }
|
|
694
|
-
]`,brt="flex min-h-0 flex-1 flex-col py-0";function vSs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:a,onPastedTextChange:i,validation:l,isImporting:c}){return o.jsxs(kl,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[o.jsxs(Sl,{variant:"pill",children:[o.jsx(kr,{value:"upload",children:"Upload file"}),o.jsx(kr,{value:"paste",children:"Paste JSON"})]}),o.jsx(Hr,{value:"upload",className:brt,children:n?o.jsx(wSs,{file:n,validation:l,onReplace:s,isImporting:c}):o.jsx(ySs,{onFileSelect:r,disabled:c})}),o.jsx(Hr,{value:"paste",className:brt,children:o.jsx(Bo,{"aria-label":"JSON items",className:"text-ui-sm min-h-[200px] flex-1 resize-none font-mono",placeholder:gSs,spellCheck:!1,value:a,onChange:u=>i(u.target.value),disabled:c})})]})}function ySs({onFileSelect:e,disabled:t}){const[n,r]=g.useState(!1),s=g.useCallback(c=>{const u=c.target.files?.[0];u&&e(u),c.target.value=""},[e]),a=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!0)},[]),i=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!1)},[]),l=g.useCallback(c=>{if(c.preventDefault(),c.stopPropagation(),r(!1),t)return;const u=c.dataTransfer.files?.[0];u&&e(u)},[t,e]);return o.jsxs("div",{"data-testid":"json-dropzone",onDragOver:a,onDragLeave:i,onDrop:l,className:K("border-border1 bg-surface3 relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed px-4 py-6 text-center transition-colors","hover:border-accent1/50 hover:bg-accent1/5",n&&"border-accent1/50 bg-accent1/5",t&&"cursor-wait opacity-60"),children:[o.jsx("input",{type:"file",accept:".json,application/json","aria-label":"Choose a JSON file",onChange:s,disabled:t,className:"absolute inset-0 cursor-pointer opacity-0"}),o.jsx("div",{className:"border-border1 bg-surface2 text-neutral4 flex size-9 items-center justify-center rounded-md border",children:o.jsx(jI,{className:"size-4"})}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("p",{className:"text-ui-md text-neutral6",children:"Drop a JSON file here"}),o.jsxs("p",{className:"text-ui-sm text-neutral4",children:["or ",o.jsx("span",{className:"underline",children:"choose a file"})," from your computer"]})]}),o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[".json · an array of items · up to ",zPe]})]})}function bSs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function xSs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function wSs({file:e,validation:t,onReplace:n,isImporting:r}){const s="rows"in t?t.rows:[],a="total"in t?t.total:0,i=s.slice(0,Goe);return o.jsxs("div",{"data-testid":"json-file-card",className:"border-border1 rounded-lg border",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[o.jsx(OI,{className:"text-neutral4 size-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral6 min-w-0 flex-1 truncate font-mono",children:e.name}),o.jsx("span",{className:"text-ui-xs text-neutral3 shrink-0",children:bSs(e.size)}),o.jsx(ie,{icon:o.jsx(Ax,{}),variant:"ghost",size:"xs",onClick:n,disabled:r,children:"Replace"})]}),i.map(l=>o.jsxs("div",{className:"border-border1 grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t px-3 py-1.5",children:[o.jsx("span",{className:"text-ui-xs text-neutral3",children:l.index}),o.jsx("span",{className:"text-ui-sm text-neutral5 truncate font-mono",children:xSs(l.input)}),l.hasInput?l.hasGroundTruth?null:o.jsx(xt,{variant:"yellow",size:"xs",children:"no groundTruth"}):o.jsx(xt,{variant:"red",size:"xs",children:"no input"})]},l.index)),a>Goe&&o.jsxs("div",{className:"border-border1 text-ui-xs text-neutral3 border-t px-3 py-1.5",children:["+ ",a-Goe," more"]})]})}const SSs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function kSs({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:s}){const[a,i]=g.useState("upload"),[l,c]=g.useState(null),[u,d]=g.useState(""),[f,h]=g.useState(null),[p,m]=g.useState(""),[v,y]=g.useState(!1),b=g.useRef(0),{batchInsertItems:x}=za(),w=a==="upload"?u:p,k=g.useMemo(()=>a==="upload"&&f?{status:"error",kind:"parse",message:f}:cws(w),[a,f,w]),O=g.useCallback(async I=>{const A=++b.current;if(!I.name.toLowerCase().endsWith(".json")){h("Only .json files are supported");return}if(I.size>BZt){h(`File is larger than ${zPe}`);return}try{const $=await SSs(I);if(A!==b.current)return;c({name:I.name,size:I.size}),d($),h(null)}catch{if(A!==b.current)return;h("Could not read the file")}},[]),_=g.useCallback(()=>{b.current++,c(null),d(""),h(null)},[]),T=g.useCallback(()=>{b.current++,i("upload"),c(null),d(""),h(null),m("")},[]),E=g.useCallback(()=>{v||(r(!1),setTimeout(T,150))},[v,r,T]),N=g.useCallback(async()=>{if(k.status==="ready"){y(!0);try{await x.mutateAsync({datasetId:e,items:k.items}),Be.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(T,150)}catch(I){Be.error(I instanceof Error?I.message:"Failed to import items")}finally{y(!1)}}},[k,x,e,s,r,T]);return o.jsx(vr,{open:n,onOpenChange:E,children:o.jsxs(yr,{className:"flex max-h-[90vh] w-[960px] max-w-[calc(100vw-2rem)] flex-col gap-0 p-0",children:[o.jsxs(br,{className:"border-border1 border-b px-4 py-4",children:[o.jsx(hr,{children:"Import into dataset"}),o.jsxs(Ms,{className:"text-ui-sm text-neutral3 not-sr-only",children:["Add items to"," ",t?o.jsx("code",{className:"bg-surface3 text-ui-xs text-neutral6 rounded px-1 font-mono",children:t}):"this dataset"," ","from a JSON file or paste them directly."]})]}),o.jsx(Mr,{className:"max-h-none min-h-0 flex-1 overflow-y-auto p-0",children:o.jsxs("div",{className:"divide-border1 grid divide-y md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0",children:[o.jsx("div",{className:"flex min-h-[360px] flex-col p-4",children:o.jsx(vSs,{tab:a,onTabChange:i,file:l,onFileSelect:O,onReplace:_,pastedText:p,onPastedTextChange:m,validation:k,isImporting:v})}),o.jsx("div",{className:"p-4",children:o.jsx(mSs,{})})]})}),o.jsxs(Bl,{className:"border-border1 items-center border-t px-4 py-3 sm:justify-between",children:[o.jsx(OSs,{validation:k}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ie,{icon:o.jsx(qt,{}),onClick:E,disabled:v,children:"Cancel"}),o.jsxs(ie,{variant:"primary",onClick:N,disabled:k.status!=="ready"||v,children:[v&&o.jsx(Zt,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})]})})}function OSs({validation:e}){const t=K("size-1.5 shrink-0 rounded-full",e.status==="idle"&&"bg-neutral3",e.status==="ready"&&"bg-accent1",e.status==="error"&&"bg-accent2");let n;switch(e.status){case"idle":n="No items yet";break;case"ready":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.total})," item",e.total!==1?"s":""," ready",e.missingGroundTruthCount>0&&` · ${e.missingGroundTruthCount} without groundTruth`]});break;case"error":switch(e.kind){case"parse":n=`Not valid JSON — ${e.message}`;break;case"not-array":n="Top level must be an array of items";break;case"empty":n="The array has no items";break;case"too-large":n=`JSON is larger than ${zPe}`;break;case"missing-input":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.missingInputCount})," of ",e.total," item",e.total!==1?"s":""," ",e.missingInputCount!==1?"have":"has"," no"," ",o.jsx("code",{className:"font-mono",children:"input"})]});break}break}return o.jsxs("div",{role:"status",className:"text-ui-sm text-neutral4 flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:t}),o.jsx("span",{className:"truncate",children:n})]})}function CSs(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"?!0:!!e.closest('[role="dialog"]:not([data-item-panel])')}function YZt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=a=>{a.defaultPrevented||CSs(a.target)||(a.key==="PageUp"?(a.preventDefault(),t?.()):a.key==="PageDown"?(a.preventDefault(),n?.()):a.key==="Escape"&&(a.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const KZt=g.createContext(null);function _Ss({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=zr(),i=xbt("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(p=>{s(`/datasets/${e}/items/${encodeURIComponent(p)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>i?t.findIndex(p=>p.id===i):-1,[t,i]),d=g.useMemo(()=>{if(u<=0)return;const p=t[u-1].id;return()=>l(p)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const p=t[u+1].id;return()=>l(p)},[u,t,l]);YZt({active:!!i,onPrevious:d,onNext:f,onClose:c});const h=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:i,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,i,l,c,d,f]);return o.jsx(KZt.Provider,{value:h,children:r})}function XZt(){const e=g.useContext(KZt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function ESs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:a}){const[i,l]=da(),{activeVersion:c}=UPe(i,l),[u,d]=g.useState(!1),[f,h]=g.useState(!1),[p,m]=g.useState(!1),[v,y]=g.useState([]),[b,x]=g.useState(!1),[w,k]=g.useState([]),[O,_]=g.useState(!1),[T,E]=g.useState([]),[N,I]=g.useState(0),[A,$]=g.useState(""),[z]=vOe(A,300),{data:D}=tv(e),{data:q=[],isLoading:H,setEndOfListElement:V,isFetchingNextPage:B,hasNextPage:W}=VC(e,z||void 0,c),{deleteItems:L}=za(),{currentItemId:G,openItem:M,close:R}=XZt(),F=X=>{G===X?R():M(X)},U=X=>{y(X),m(!0)},Q=X=>{k(X),x(!0)},te=X=>{x(X),X||(k([]),I(ne=>ne+1))},J=X=>{E(X),_(!0)},ee=async()=>{await L.mutateAsync({datasetId:e,itemIds:T}),Be.success(`Deleted ${T.length} items`),_(!1),E([]),I(X=>X+1)},re=X=>{m(!1),y([]),I(ne=>ne+1),n?.(X)},ae=X=>{m(X),X||(y([]),I(ne=>ne+1))};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"grid h-full overflow-auto",children:o.jsx(fSs,{items:q,leftSlot:r,rightSlot:s,belowToolbarSlot:a,isLoading:H,onItemClick:F,featuredItemId:G,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>h(!0),onBulkDeleteClick:J,onCreateDatasetClick:U,onAddToDatasetClick:Q,datasetName:D?.name,clearSelectionTrigger:N,setEndOfListElement:V,isFetchingNextPage:B,hasNextPage:W,searchQuery:A,activeSearchQuery:z,onSearchChange:$,currentDatasetVersion:D?.version})}),o.jsx(iSs,{datasetId:e,open:u,onOpenChange:d}),o.jsx(kSs,{datasetId:e,datasetName:D?.name,open:f,onOpenChange:h}),o.jsx(Bws,{open:p,onOpenChange:ae,items:v,onSuccess:re}),o.jsx(Uws,{open:b,onOpenChange:te,items:w,currentDatasetId:e}),o.jsx(At,{open:O,onOpenChange:_,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Items"}),o.jsxs(At.Description,{children:["Are you sure you want to delete ",T.length," item",T.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:ee,children:L.isPending?"Deleting...":"Delete"})]})]})})]})}const xrt="__create_tag__";function TSs({datasetId:e}){const{data:t}=tv(e),{data:n}=Pm(),{updateDataset:r}=za(),[s,a]=g.useState(""),i=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>UZt(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const h=l.map(v=>({label:v,value:v,end:i.includes(v)?o.jsx(Fn,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),p=s.trim();return p.length>0&&!l.includes(p)&&!i.includes(p)?[{label:`Create "${p}"`,value:xrt},...h]:h},[l,i,s]),u=h=>{r.mutate({datasetId:e,tags:h},{onError:()=>Be.error("Failed to update tags")})},d=h=>{const p=h===xrt?s.trim():h;!p||i.includes(p)||u([...i,p])},f=h=>{u(i.filter(p=>p!==h))};return o.jsxs("div",{"data-testid":"dataset-tags-editor",className:"flex flex-wrap items-center gap-2",children:[i.map(h=>o.jsxs(IY,{value:h,size:"md",className:"gap-1 pr-1",children:[h,o.jsx("button",{type:"button","aria-label":`Remove tag ${h}`,disabled:r.isPending,onClick:()=>f(h),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:o.jsx(qt,{className:"size-3"})})]},h)),o.jsx(Co,{options:c,value:void 0,onValueChange:d,onInputValueChange:a,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(TI,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:"ghost",size:"xs",className:"w-auto min-w-0",disabled:r.isPending})]})}function JZt({overrideEnabled:e,onOverrideEnabledChange:t,selectedScorerIds:n,onSelectedScorerIdsChange:r,disabled:s=!1}){return o.jsxs("div",{className:"grid gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(bl,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),o.jsx(Dt,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),o.jsx("p",{className:"text-muted-foreground text-ui-sm",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?o.jsx(tK,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function jSs(e){if(!(e instanceof Error))return null;const t=e.message.match(/- ({.*})$/);if(!t)return null;try{const n=JSON.parse(t[1]);if(n.field&&Array.isArray(n.errors))return{field:n.field,errors:n.errors}}catch{}return null}function Qoe({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-ui-sm",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function NSs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[h,p]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(""),[x,w]=g.useState(null),{addItem:k}=za(),O=()=>{a("{}"),l(""),u(""),f(""),p(!1),v([]),b(""),w(null)},_=$=>{O(),n($)},T=async $=>{$.preventDefault();let z;try{z=JSON.parse(s)}catch{Be.error("Input must be valid JSON");return}let D;if(i.trim())try{D=JSON.parse(i)}catch{Be.error("Ground Truth must be valid JSON");return}let q;if(c.trim())try{q=JSON.parse(c)}catch{Be.error("Expected Trajectory must be valid JSON");return}let H;if(d.trim())try{const B=JSON.parse(d);if(!Array.isArray(B)){Be.error("Tool Mocks must be a JSON array");return}H=B}catch{Be.error("Tool Mocks must be valid JSON");return}let V;if(y.trim())try{V=JSON.parse(y)}catch{Be.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:z,groundTruth:D,expectedTrajectory:q,toolMocks:H,scorerIds:h?m:void 0,requestContext:V}),Be.success("Item added successfully"),_(!1),r?.()}catch(B){const W=jSs(B);W?w(W):Be.error(`Failed to add item: ${B instanceof Error?B.message:"Unknown error"}`)}},E=$=>{a($),x?.field==="input"&&w(null)},N=$=>{l($),x?.field==="groundTruth"&&w(null)},I=$=>{f($),x?.field==="toolMocks"&&w(null)},A=()=>{_(!1)};return o.jsxs(_i,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(_i.Top,{children:"Add Item"}),o.jsxs(_i.Content,{children:[o.jsx(_i.Header,{children:o.jsx(_i.Heading,{children:"Add Item"})}),o.jsxs("form",{onSubmit:T,className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Vr,{value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(Qoe,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Vr,{value:i,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&o.jsx(Qoe,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Vr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Vr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&o.jsx(Qoe,{field:"toolMocks",errors:x.errors})]}),o.jsx(JZt,{overrideEnabled:h,onOverrideEnabledChange:p,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Vr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ie,{icon:o.jsx(qt,{}),type:"button",onClick:A,children:"Cancel"}),o.jsx(ie,{icon:o.jsx(Zr,{}),type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}const Pk=e=>JSON.stringify(e??null,null,2),ISs=[{key:"input",title:"Input",icon:o.jsx(zO,{}),value:e=>Pk(e.input)},{key:"groundTruth",title:"Ground Truth",icon:o.jsx(xy,{}),value:e=>Pk(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:o.jsx(eft,{}),value:e=>e.expectedTrajectory!=null?Pk(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:o.jsx(Vd,{}),value:e=>Pk(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:o.jsx(kH,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":Pk(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:o.jsx(nc,{}),value:e=>e.requestContext!=null?Pk(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:o.jsx(TI,{}),value:e=>Pk(e.metadata)}];function kwe({item:e,diff:t}){return o.jsxs(o.Fragment,{children:[o.jsxs(Bn,{children:[o.jsx(Bn.Key,{children:"Dataset Id"}),o.jsx(Bn.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),o.jsx(Bn.Key,{children:"Version"}),o.jsxs(Bn.Value,{children:["v",e.datasetVersion]}),o.jsx(Bn.Key,{children:"Created"}),o.jsx(Bn.Value,{children:xr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")}),o.jsx(Bn.Key,{children:"Updated"}),o.jsx(Bn.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?xr(new Date(e.updatedAt),"MMM d, yyyy h:mm aaa"):"n/a"})]}),o.jsx("div",{className:"mt-3 grid gap-3",children:ISs.map(n=>{const r=n.value(e),s=t?n.value(t.against):void 0;return r===void 0&&s===void 0?null:o.jsx(bn.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function Yoe({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-ui-sm",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function ASs({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:a,trajectoryValue:i,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:h,setSelectedScorerIds:p,requestContextValue:m,setRequestContextValue:v,validationErrors:y,onSave:b,onCancel:x,isSaving:w}){return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4",children:o.jsxs("h3",{className:"text-header-sm flex items-center gap-2 font-medium",children:[o.jsx(Yu,{className:"h-5 w-5"})," Edit Item"]})}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Input (JSON) *"}),o.jsx(Vr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(Yoe,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Vr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(Yoe,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Expected Trajectory (JSON, optional)"}),o.jsx(Vr,{value:i,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Tool Mocks (JSON array, optional)"}),o.jsxs("p",{className:"text-muted-foreground text-ui-sm",children:["Ordered static mocks served in place of executing the tool. Each entry is"," ",o.jsx("code",{children:'{ "toolName", "args", "output" }'}),". Calling a mocked tool with non-matching args fails the item; unmocked tools run live."]}),o.jsx(Vr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&o.jsx(Yoe,{field:"toolMocks",errors:y.errors})]}),o.jsx(JZt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:h,onSelectedScorerIdsChange:p,disabled:w}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context (JSON, optional)"}),o.jsx(Vr,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Metadata (JSON, optional)"}),o.jsx(Vr,{value:s,onChange:a,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex gap-2 pt-4",children:[o.jsx(ie,{icon:o.jsx(Fn,{}),variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),o.jsx(ie,{icon:o.jsx(qt,{}),onClick:x,disabled:w,children:"Cancel"})]})]})]})}const RSs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function PSs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Yf(),{data:l,isLoading:c}=Bm(),{data:u,isLoading:d}=tf(),f=e==="agent"?Object.entries(a??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],h=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,p=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Target Type"}),o.jsx(Co,{options:RSs,value:e,onValueChange:p,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:m}),o.jsx(Co,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:h,container:s})]})]})}const $Ss=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function MSs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return xm(e)}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context"}),o.jsx(_L,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-ui-md",children:"Failed to parse request context schema"})}function Koe({index:e,done:t,isLast:n,children:r}){return o.jsxs("li",{className:"flex gap-4",children:[o.jsxs("div",{className:"flex flex-col items-center",children:[o.jsx("span",{"aria-hidden":"true",className:K("flex size-6 shrink-0 items-center justify-center rounded-full border text-ui-xs font-medium",t?"border-accent1 bg-accent1 text-white":"border-border1 text-neutral3"),children:e}),!n&&o.jsx("span",{"aria-hidden":"true",className:"bg-border1 mt-2 w-px flex-1"})]}),o.jsx("div",{className:K("min-w-0 flex-1 space-y-3",!n&&"pb-4"),children:r})]})}function nK({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:a,initialDescription:i,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),[f,h]=g.useState(a??""),[p,m]=g.useState(i??""),[v,y]=g.useState(e??""),[b,x]=g.useState(t??null),[w,k]=g.useState(r??""),[O,_]=g.useState(s??""),[T,E]=g.useState(n??null),[N,I]=g.useState({}),[A,$]=g.useState(""),{triggerExperiment:z}=za(),{data:D}=tv(v),{total:q}=VC(v,void 0,b),H=D?.requestContextSchema,V=D?.scorerIds??[],B=T===null&&V.length>0,W=T??V,L=!!(H&&Object.keys(H).length>0),G=!!(v&&w&&O&&f.trim()),M=z.isPending,R=[!f.trim()&&"name",!v&&"dataset",!O&&"target"].filter(Boolean),F=L?Object.values(N).some(ae=>ae!==void 0&&ae!==""):A.trim().length>0,U=ae=>{y(ae),x(null),E(n??null),I({})},Q=()=>{h(a??""),m(i??""),y(e??""),x(t??null),k(r??""),_(s??""),E(n??null),I({}),$("")},te=()=>{if(L){const ae=Object.entries(N).filter(([,X])=>X!==void 0&&X!=="");return ae.length>0?Object.fromEntries(ae):void 0}if(A.trim()){let ae;try{ae=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!ae||typeof ae!="object"||Array.isArray(ae))throw new Error("Request Context must be a JSON object");return ae}},J=async()=>{if(!v||!w||!O||!f.trim())return;let ae;try{ae=te()}catch(X){const ne=X instanceof Error?X.message:"Request Context must be valid JSON";fu.error(ne);return}try{const X=await z.mutateAsync({datasetId:v,name:f.trim(),description:p.trim()||void 0,targetType:w,targetId:O,scorerIds:W.length>0?W:void 0,version:b??void 0,requestContext:ae});fu.success("Experiment triggered successfully"),c(!1),u?.(X.experimentId),Q()}catch(X){const ne=X instanceof Error?X.message:"Failed to trigger experiment";fu.error(ne)}},ee=()=>{M||(c(!1),Q())},re=ae=>{(ae.metaKey||ae.ctrlKey)&&ae.key==="Enter"&&G&&!M&&(ae.preventDefault(),J())};return o.jsx(vr,{open:l,onOpenChange:ee,children:o.jsxs(yr,{ref:d,className:"w-[640px] max-w-[calc(100vw-2rem)] gap-0 p-0",onKeyDown:re,children:[o.jsxs(br,{className:"border-border1 border-b px-4 py-4",children:[o.jsx(hr,{children:"Run experiment"}),o.jsx(Ms,{className:"text-ui-sm text-neutral3 not-sr-only",children:"Pick a dataset, choose what to run it against, and optionally score the results."})]}),o.jsxs(Mr,{className:"max-h-[70vh] space-y-6 overflow-y-auto px-4 py-5",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"experiment-name",children:"Name *"}),o.jsx(In,{id:"experiment-name",value:f,onChange:ae=>h(ae.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:M})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"experiment-description",children:"Description"}),o.jsx(Bo,{id:"experiment-description",value:p,onChange:ae=>m(ae.target.value),placeholder:"Enter experiment description (optional)",disabled:M,rows:2})]})]}),o.jsxs("ol",{className:"list-none",children:[o.jsxs(Koe,{index:1,done:!!v,children:[o.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Dataset"}),o.jsx(Q0t,{value:v,onValueChange:U,container:d})]}),v&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Version"}),o.jsx(QZt,{datasetId:v,value:b,onValueChange:x,container:d})]})]}),v&&q!==void 0&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[q," ",q===1?"item":"items"]})]}),o.jsxs(Koe,{index:2,done:!!O,children:[o.jsx(PSs,{targetType:w,setTargetType:k,targetId:O,setTargetId:_,container:d}),w&&!O&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:["Choose ",w==="agent"?"an":"a"," ",w," to run"]})]}),o.jsx(Koe,{index:3,done:W.length>0,isLast:!0,children:o.jsx(tK,{selectedScorers:W,setSelectedScorers:E,disabled:M,container:d,helperText:B?"Pre-filled from the dataset's default scorers.":"Scores are computed after each item runs."})})]}),o.jsxs(cc,{children:[o.jsxs(ql,{className:"text-ui-sm flex items-center gap-2",children:[o.jsx(wr,{className:"size-4"}),"Request Context (JSON, optional)",F&&o.jsx(xt,{size:"xs",variant:"blue",children:"set"})]}),o.jsx(Vl,{className:"pt-3",children:L?o.jsx(MSs,{requestContextSchema:H,onChange:I}):o.jsx(Vr,{value:A,onChange:$,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),o.jsxs(Bl,{className:"border-border1 items-center border-t px-4 py-4 sm:justify-between",children:[o.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"flex items-center gap-2",children:R.length===0?o.jsxs(o.Fragment,{children:[o.jsx(xt,{variant:"green",indicator:"dot",children:"Ready"}),o.jsxs("span",{className:"text-ui-xs text-neutral3",children:[q??0," items · ",w," · ",W.length," scorers"]})]}):o.jsxs(xt,{variant:"neutral",indicator:"dot",children:["Missing ",R.join(", ")]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ie,{icon:o.jsx(qt,{}),onClick:ee,disabled:M,children:"Cancel"}),o.jsx(ie,{variant:"primary",onClick:J,disabled:!G||M,children:M?o.jsxs(o.Fragment,{children:[o.jsx(Zt,{className:"h-4 w-4"}),"Running..."]}):o.jsxs(o.Fragment,{children:["Run",o.jsxs("span",{className:"ml-1 inline-flex gap-0.5","aria-hidden":"true",children:[o.jsx(Tg,{size:"xs",children:$Ss?"⌘":"Ctrl"}),o.jsx(Tg,{size:"xs",children:"↵"})]})]})})]})]})]})})}const eGt=g.createContext(null);function DSs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,children:i}){const l=zr(),u=xbt("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(y=>{l(`/experiments/${e}/items/${encodeURIComponent(y)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),h=g.useMemo(()=>u?r.findIndex(y=>y.itemId===u):-1,[r,u]),p=g.useMemo(()=>{if(h<=0)return;const y=r[h-1].itemId;return()=>d(y)},[h,r,d]),m=g.useMemo(()=>{if(h<0||h>=r.length-1)return;const y=r[h+1].itemId;return()=>d(y)},[h,r,d]);YZt({active:!!u,onPrevious:p,onNext:m,onClose:f});const v=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,currentItemId:u,openItem:d,close:f,goToPreviousItem:p,goToNextItem:m}),[e,t,n,r,s,a,u,d,f,p,m]);return o.jsx(eGt.Provider,{value:v,children:i})}function tGt(){const e=g.useContext(eGt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function LSs({experimentId:e,experimentStatus:t,results:n,isLoading:r,setEndOfListElement:s,isFetchingNextPage:a,hasNextPage:i,selectedIds:l,onToggleSelect:c}){const{currentItemId:u,openItem:d,close:f}=tGt(),h=g.useMemo(()=>u?n.find(b=>b.itemId===u)?.id??null:null,[n,u]),{data:p}=Fy(e,t),m=g.useMemo(()=>{if(!p)return[];const b=new Set;for(const x of Object.values(p))for(const w of x)b.add(w.scorerId);return[...b].sort()},[p]),v=g.useCallback(b=>{const x=n.find(w=>w.id===b);x&&(x.itemId===u?f():d(x.itemId))},[n,u,f,d]),y=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"auto"},{name:"status",label:"Status",size:"auto"},{name:"input",label:"Input",size:"1fr"},{name:"tags",label:"Tags",size:"auto"},...m.map(b=>({name:b,label:b,size:"auto"}))],[m]);return o.jsx("div",{className:"h-full min-h-0 min-w-0 overflow-y-auto",children:o.jsx(KY,{results:n,isLoading:r,featuredResultId:h,onResultClick:v,columns:y,scoresByItemId:p,scorerIds:m,setEndOfListElement:s,isFetchingNextPage:a,hasNextPage:i,selectedIds:l,onToggleSelect:c})})}function FSs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${xr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function zSs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=sPe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${FSs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(tl.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(ad,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(ad,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}function nGt({children:e,className:t}){return o.jsx("div",{className:K("",t),children:e})}function BSs({date:e,className:t,withTime:n=!1}){const r=e?eSt(new Date(e)):!1,s=e?bL(new Date(e))?"Today":xr(new Date(e),"MMM dd"):"",a=e&&!r?xr(new Date(e),"yyyy"):"",i=e&&n?`${xr(new Date(e),"'at' h:mm aaa")}`:"";return o.jsxs("div",{className:K("truncate text-ui-md text-neutral2",t),children:[s," ",a," ",i]})}function qPe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function USs({columns:e,isSelectionActive:t,children:n}){return o.jsx("div",{className:K("sticky top-0 z-10 mb-2 rounded-lg bg-surface3 px-3"),children:o.jsx("div",{className:K("grid items-center gap-3 text-left text-ui-xs tracking-widest text-neutral3 uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:qPe(e)},children:n})})}function qSs({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function VSs({id:e,className:t,isShortened:n=!0}){const r=n?e.slice(0,8):e;return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral2",t),children:r})}function HSs({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function WSs({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function ZSs({children:e,className:t}){return o.jsx("label",{className:K("flex h-full w-14 items-center justify-center rounded-lg hover:bg-surface5",t),children:e})}function GSs({children:e,href:t,className:n,LinkComponent:r,tooltip:s}){const a=o.jsx(r,{href:t,className:K("flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left","hover:bg-surface4",ts.colors,zI.visible,n),children:e});return s==null?a:o.jsxs(gn,{children:[o.jsx(hn,{render:a}),o.jsx(pn,{children:s})]})}function QSs({children:e,message:t,className:n,type:r}){return!e&&!t?null:o.jsx("div",{className:K("grid border-t border-border1",n),children:t?o.jsxs("p",{className:K("grid justify-center justify-items-center gap-2 p-5 text-center text-ui-md text-neutral3","[&>svg]:size-[1.5em] [&>svg]:opacity-75",{"[&>svg]:text-red-500":r==="error"}),children:[r==="error"?o.jsx(Ic,{}):o.jsx(_m,{})," ",t]}):e})}function YSs({isLoading:e,hasMore:t,setEndOfListElement:n,loadingText:r="Loading more data...",noMoreDataText:s="No more data to load"}){return n?o.jsxs("div",{ref:n,className:"text-ui-md text-neutral3 mt-4 flex justify-center opacity-50",children:[e&&r,!t&&!e&&s]}):null}function KSs({currentPage:e,hasMore:t,onNextPage:n,onPrevPage:r}){const s=typeof e=="number"&&e>0||t;return o.jsxs("div",{className:K("flex items-center justify-center gap-4 pt-4 text-ui-md text-neutral3"),children:[o.jsxs("span",{children:["Page ",o.jsx("b",{children:e?e+1:"1"})]}),s&&o.jsxs("div",{className:K("flex gap-4","[&>button]:flex [&>button]:items-center [&>button]:gap-2 [&>button]:rounded-md [&>button]:border [&>button]:border-border1 [&>button]:p-1 [&>button]:px-2 [&>button]:text-neutral4 [&>button]:transition-colors [&>button:hover]:text-neutral5","[&_svg]:size-[1em] [&_svg]:text-neutral3"),children:[typeof e=="number"&&e>0&&o.jsxs("button",{onClick:r,children:[o.jsx(Lc,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(Df,{})]})]})]})}function XSs({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function JSs({isSelected:e,children:t,columns:n}){return o.jsx("li",{className:K("flex overflow-hidden rounded-lg border border-transparent border-t-border1 py-[3px] pb-[2px] text-ui-md text-neutral5 first:border-t-transparent","[&:last-child>button]:rounded-b-lg","[&.selected-row]:border [&.selected-row]:border-dashed [&.selected-row]:border-white/50 [&.selected-row]:pr-[3px] [&.selected-row]:first:border-t","[&:has(+.selected-row)]:rounded-b-none [&:has(+.selected-row)]:border-b-transparent","[.selected-row+&]:rounded-t-none",ts.colors,{"selected-row":e,"grid px-3 gap-3":n}),style:{gridTemplateColumns:qPe(n)},children:t})}function e1s({item:e,isFeatured:t,onClick:n,children:r,columns:s,className:a,disabled:i,tooltip:l,...c}){const u=()=>{n?.(e?.id)},d=o.jsx("button",{...c,onClick:u,className:K("grid w-full items-center gap-3 rounded-lg px-3 text-left",ts.colors,zI.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!i},a),style:{gridTemplateColumns:qPe(s)},disabled:i,children:r});return l==null?d:o.jsxs(gn,{children:[o.jsx(hn,{render:d}),o.jsx(pn,{children:l})]})}function t1s(e){return e.charAt(0).toUpperCase()+e.slice(1)}function n1s({status:e}){return e?o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx("div",{className:K("relative flex h-full w-10 items-center justify-center bg-transparent"),children:o.jsx("div",{className:K("size-2 rounded-full",{"bg-green-600":["success","completed"].includes(e),"bg-red-700":["error","failed"].includes(e),"bg-yellow-500":["pending","running"].includes(e)})})})}),o.jsx(pn,{children:t1s(e)})]}):null}function r1s({children:e,isLoading:t,className:n}){return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral4",n),children:t?o.jsx("div",{className:"bg-surface4 h-4 animate-pulse rounded-md text-transparent select-none"}):e})}const wrt={latest:"Latest version",deleted:"Deleted in this version"};function s1s({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(nGt,{className:K("grid grid-cols-[1fr_auto] pl-1"),children:[o.jsxs("div",{className:K("grid gap-1 leading-none text-neutral3",{"text-neutral4":n}),children:[o.jsxs("strong",{className:"font-normal",children:["v. ",e]}),o.jsx("em",{className:K("text-ui-sm","font-normal","text-neutral2"),children:t?xr(new Date(t),"MMM d, yyyy HH:mm"):null})]}),(n||r)&&o.jsxs("div",{className:"flex items-center gap-1",children:[n&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":wrt.latest,children:o.jsx(xt,{variant:"blue",size:"sm",icon:o.jsx(xS,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":wrt.deleted,children:o.jsx(xt,{variant:"red",size:"sm",icon:o.jsx(zwe,{})})})]})]})}const Pp=Object.assign(XSs,{Header:USs,HeaderCol:qSs,Items:HSs,Scroller:WSs,Row:JSs,RowButton:e1s,Message:QSs,NextPageLoading:YSs,Pagination:KSs,Cell:nGt,TextCell:r1s,StatusCell:n1s,VersionCell:s1s,IdCell:VSs,DateCell:BSs,LinkCell:GSs,LabelCell:ZSs}),a1s=[{name:"id",label:"ID",size:"1fr"},{name:"versionA",label:"Version A",size:"1fr"},{name:"versionB",label:"Version B",size:"1fr"},{name:"compare",label:"Compare",size:"10rem"}],b7={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(Zr,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(Qnn,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(Fdt,{}),tooltip:"Same in both versions"}};function Xoe({red:e=!1,tooltip:t}){return o.jsxs(gn,{children:[o.jsx(hn,{render:o.jsx("span",{}),role:"img",tabIndex:0,"aria-label":t,className:"focus-visible:outline-neutral5/55 rounded focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-solid",children:o.jsx(zwe,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(pn,{children:t})]})}function Joe({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{badgeVariant:n,icon:r,tooltip:s}=b7[e];return o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"text-ui-md text-neutral4 flex min-w-16 justify-end pr-3",children:["v. ",t]}),o.jsx("span",{className:"inline-flex",role:"img","aria-label":s,children:o.jsx(xt,{variant:n,size:"xs",icon:r})})]})}function i1s(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function Srt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function o1s({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=ln(),l=t>n;return o.jsx(Pp,{children:o.jsx(Pp.Scroller,{children:o.jsx(Pp.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=i1s(u,d),h=Srt({otherVersionExists:d!==void 0,status:f,isNewer:l}),p=Srt({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(Pp.Row,{columns:a1s,children:[o.jsx(Pp.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(Pp.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?b7[h].tooltip:void 0,children:o.jsx(Joe,{variant:h,version:u.datasetVersion})}):o.jsx(Pp.Cell,{className:"flex items-center justify-center",children:o.jsx(Xoe,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(Pp.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?b7[p].tooltip:void 0,children:o.jsx(Joe,{variant:p,version:d.datasetVersion})}):o.jsx(Pp.Cell,{className:"flex items-center justify-center",children:o.jsx(Xoe,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(Pp.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:b7.same.tooltip,children:o.jsx(Joe,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(Pp.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?version=${u?.datasetVersion}&compare=${d?.datasetVersion}`,children:"Compare"}):o.jsx(Pp.Cell,{children:o.jsx(Xoe,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}const x7="targetType",Z$="targetId";function VPe({resetParams:e=[]}={}){const[t,n]=da(),r=e.join(","),s=t.get(x7),a=VZt(s)?s:"",i=a?t.get(Z$)??"":"",l=g.useCallback(d=>{n(f=>{const h=new URLSearchParams(f);d?h.set(x7,d):h.delete(x7),h.delete(Z$);for(const p of r.split(","))p&&h.delete(p);return h},{replace:!0})},[n,r]),c=g.useCallback(d=>{n(f=>{const h=new URLSearchParams(f);d?h.set(Z$,d):h.delete(Z$);for(const p of r.split(","))p&&h.delete(p);return h},{replace:!0})},[n,r]),u=g.useCallback(()=>l(""),[l]);return{targetType:a,targetId:i,setTargetType:l,setTargetId:c,clear:u}}function l1s(){const e=zr(),[t,n]=g.useState(""),[r,s]=g.useState("all"),[a,i]=g.useState("all"),{targetType:l,targetId:c,setTargetType:u,setTargetId:d,clear:f}=VPe(),{data:h=[],isLoading:p,error:m,isFetchingNextPage:v,hasNextPage:y,setEndOfListElement:b}=R2n({targetType:l,targetId:c}),{data:x,isLoading:w,error:k}=RW(),O=g.useMemo(()=>x?.experiments??[],[x?.experiments]),_=g.useMemo(()=>yws(h),[h]),T=p||w,E=m||k,N=()=>{e("/datasets/new")},I=o.jsx(nv,{owner:"dataset-list",children:o.jsx(Fx,{onClick:N,tooltip:"Create a dataset",variant:"ghost",size:"sm",children:"New dataset"})});if(E&&ms(E))return o.jsx(Qn,{children:o.jsx(zs,{})});if(E&&gs(E))return o.jsx(Qn,{children:o.jsx(Ts,{resource:"datasets"})});if(E)return o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load datasets",message:E.message})});if(h.length===0&&!T&&!l)return o.jsxs(Qn,{children:[I,o.jsx(bws,{onCreateClick:N})]});const A=r!=="all"||a!=="all"||t!==""||l!=="",$=()=>{n(""),s("all"),i("all"),f()};return o.jsxs(Bt,{height:"full",children:[I,o.jsx(Bt.TopArea,{children:o.jsx(Tws,{search:t,onSearchChange:n,experimentFilter:r,onExperimentFilterChange:s,tagFilter:a,onTagFilterChange:i,tagOptions:_,targetType:l,onTargetTypeChange:u,targetId:c,onTargetIdChange:d,onReset:$,hasActiveFilters:A})}),o.jsx(gws,{datasets:h,experiments:O,isLoading:T,search:t,experimentFilter:r,tagFilter:a,isFetchingNextPage:v,hasNextPage:y,setEndOfListElement:b})]})}function L8({children:e}){return o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:e})]})}function c1s(){const{datasetId:e}=tr(),t=zr(),[n,r]=da(),{activeVersion:s,handleVersionChange:a}=UPe(n,r),[i,l]=g.useState(!1),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[h,p]=g.useState(!1),{data:m,error:v,isLoading:y}=tv(e),{data:b=[],isLoading:x}=VC(e,void 0,s),w=!x&&b.length===0;if(y)return null;if(v&&ms(v))return o.jsx(L8,{children:o.jsx(zs,{})});if(v&&gs(v))return o.jsx(L8,{children:o.jsx(Ts,{resource:"datasets"})});if(v&&R1(v)||!y&&!v&&!m)return o.jsx(L8,{children:o.jsx(mr,{iconSlot:o.jsx(Fg,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsx(ie,{as:xo,to:"/datasets",icon:o.jsx(Lc,{}),children:"Back to Datasets"})})});if(v)return o.jsx(L8,{children:o.jsx(Fs,{title:"Failed to load dataset",message:v instanceof Error?v.message:"An unexpected error occurred. Please try again."})});const k=_=>{t(`/experiments/${_}`)},O=()=>{t("/datasets")};return o.jsxs(_Ss,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"h-full",children:[o.jsx(Bt,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Bt.MainArea,{children:o.jsx(ESs,{datasetId:e,onAddItemClick:()=>u(!0),belowToolbarSlot:o.jsx(TSs,{datasetId:e}),leftSlot:o.jsx("span",{className:"text-ui-sm text-neutral3 mr-3 whitespace-nowrap",children:m?.createdAt?`Created ${xr(new Date(m.createdAt),"MMM d")}`:""}),rightSlot:o.jsxs(Wr,{children:[o.jsx(ie,{as:xo,to:`/experiments?dataset=${e}`,icon:o.jsx(Hwe,{}),children:"View experiments"}),o.jsx(QZt,{datasetId:e,value:s,onValueChange:a,currentVersion:m?.version,className:"w-36"}),w?o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx("span",{className:"cursor-not-allowed",children:o.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:o.jsx(ie,{variant:"primary",icon:o.jsx(oc,{}),children:"Run Experiment"})})})}),o.jsx(pn,{children:"Add items to the dataset before running an experiment"})]}):o.jsx(ie,{variant:"primary",onClick:()=>l(!0),icon:o.jsx(oc,{}),children:"Run Experiment"}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(d1,{})})}),o.jsxs(ot.Content,{align:"end",className:"w-48",children:[o.jsxs(ot.Item,{onSelect:()=>{t(`/datasets/${e}/edit`)},children:[o.jsx(Yu,{})," Edit Dataset"]}),o.jsxs(ot.Item,{onSelect:()=>p(!0),children:[o.jsx(mu,{})," Duplicate Dataset"]}),o.jsxs(ot.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(yi,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(qg,{})]}),o.jsx(nK,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:i,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx(NSs,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(qws,{open:h,onOpenChange:p,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx(Zws,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:O})]})}function ele({children:e}){return o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:e})]})}function u1s(){const{datasetId:e}=tr(),t=zr(),{data:n,error:r,isLoading:s}=tv(e),a=()=>{t(`/datasets/${e}`)};return s?null:r&&ms(r)?o.jsx(ele,{children:o.jsx(zs,{})}):r&&gs(r)?o.jsx(ele,{children:o.jsx(Ts,{resource:"datasets"})}):r||!n?o.jsx(ele,{children:o.jsx(Fs,{title:"Failed to load dataset",message:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[o.jsx(Ph,{className:"mb-6 p-0",children:o.jsxs(Ph.Column,{children:[o.jsxs(Ph.Title,{children:[o.jsx(Fg,{})," Edit dataset"]}),o.jsx(Ph.Description,{children:n.name})]})}),o.jsx(Uf,{className:"p-4",children:o.jsx(Wws,{dataset:{id:n.id,name:n.name,description:n.description||"",inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema,scorerIds:n.scorerIds},onSuccess:a,onCancel:a})})]})})]})}function rK({label:e,wide:t=!1,children:n}){return o.jsxs("div",{className:K("pointer-events-none absolute inset-0 z-50","grid transition-[grid-template-columns] duration-300 ease-in-out",t?"grid-cols-[1fr_4fr]":"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"pointer-events-none"}),o.jsx("div",{role:"dialog","data-item-panel":!0,"aria-label":e,className:"pointer-events-auto h-full min-h-0 min-w-0 overflow-y-auto",children:n})]})}function d1s(e){if(!(e instanceof Error))return null;const t=e.message.match(/- ({.*})$/);if(!t)return null;try{const n=JSON.parse(t[1]);if(n.field&&Array.isArray(n.errors))return{field:n.field,errors:n.errors}}catch{}return null}function f1s({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:a}=ln(),{updateItem:i,deleteItem:l}=za(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[h,p]=g.useState(""),[m,v]=g.useState(""),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,O]=g.useState(t.scorerIds!==void 0),[_,T]=g.useState(t.scorerIds??[]),[E,N]=g.useState(""),[I,A]=g.useState(null),[$,z]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),O(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),z(!1),A(null))},[t?.id]);const D=n.findIndex(M=>M.id===t.id),q=D>0?()=>r(n[D-1].id):void 0,H=D>=0&&D<n.length-1?()=>r(n[D+1].id):void 0,V=async()=>{let M;try{M=JSON.parse(d)}catch{Be.error("Input must be valid JSON");return}let R;if(h.trim())try{R=JSON.parse(h)}catch{Be.error("Ground Truth must be valid JSON");return}let F;if(m.trim())try{F=JSON.parse(m)}catch{Be.error("Metadata must be valid JSON");return}let U=null;if(y.trim())try{U=JSON.parse(y)}catch{Be.error("Expected Trajectory must be valid JSON");return}let Q;if(x.trim())try{const ee=JSON.parse(x);if(!Array.isArray(ee)){Be.error("Tool Mocks must be a JSON array");return}Q=ee}catch{Be.error("Tool Mocks must be valid JSON");return}else Q=[];let te;if(E.trim())try{te=JSON.parse(E)}catch{Be.error("Request Context must be valid JSON");return}let J;k?J=_:t.scorerIds!==void 0&&(J=null);try{const ee=await i.mutateAsync({datasetId:e,itemId:t.id,input:M,groundTruth:R,metadata:F,expectedTrajectory:U,toolMocks:Q,scorerIds:J,requestContext:te});Be.success("Item updated successfully"),O(ee.scorerIds!==void 0),T(ee.scorerIds??[]),u(!1),A(null)}catch(ee){const re=d1s(ee);re?A(re):Be.error(`Failed to update item: ${ee instanceof Error?ee.message:"Unknown error"}`)}},B=()=>{f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),O(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},W=M=>{f(M),I?.field==="input"&&A(null)},L=M=>{p(M),I?.field==="groundTruth"&&A(null)},G=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Be.success("Item deleted successfully"),z(!1),s()}catch(M){Be.error(`Failed to delete item: ${M instanceof Error?M.message:"Unknown error"}`)}};return o.jsxs(o.Fragment,{children:[o.jsxs(bn,{children:[o.jsxs(bn.Header,{children:[o.jsxs(bn.Heading,{children:["Item ",o.jsxs("b",{children:["# ",t.id.length>12?`${t.id.slice(0,12)}…`:t.id]})]}),o.jsxs(Wr,{className:"ml-auto shrink-0",children:[o.jsx(bn.NextPrevNav,{onPrevious:q,onNext:H,previousLabel:"Previous item",nextLabel:"Next item"}),!c&&o.jsxs(o.Fragment,{children:[o.jsx(ie,{as:a,href:`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`,size:"md",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:o.jsx(Kwe,{})}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{size:"md","aria-label":"Actions menu",children:o.jsx(d1,{})})}),o.jsxs(ot.Content,{align:"end",className:"w-48",children:[o.jsxs(ot.Item,{onSelect:()=>u(!0),children:[o.jsx(Yu,{}),"Edit"]}),o.jsxs(ot.Item,{onSelect:()=>z(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(yi,{}),"Delete Item"]})]})]})]}),o.jsx(bn.CloseButton,{onClick:s,tooltip:"Close detail panel"})]})]}),o.jsx(bn.Content,{children:c?o.jsx(ASs,{inputValue:d,setInputValue:W,groundTruthValue:h,setGroundTruthValue:L,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:O,selectedScorerIds:_,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:N,validationErrors:I,onSave:V,onCancel:B,isSaving:i.isPending}):o.jsx(kwe,{item:t})})]}),o.jsx(At,{open:$,onOpenChange:z,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Item"}),o.jsx(At.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:G,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function h1s(){const{itemId:e}=tr(),{datasetId:t,items:n,isLoadingItems:r,openItem:s,close:a}=XZt(),i=g.useMemo(()=>n.find(d=>d.id===e)??null,[n,e]),{data:l,isLoading:c}=HHt(i?"":t,!i&&e?e:""),u=i??l??null;return e?o.jsx(rK,{label:`Dataset item ${e}`,children:u?o.jsx("div",{className:"[&>section]:bg-surface3 flex h-full min-h-0 flex-col p-3 [&>section]:min-h-0 [&>section]:flex-1 [&>section]:rounded-lg [&>section]:shadow-lg",children:o.jsx(f1s,{datasetId:t,item:u,items:n,onItemChange:s,onClose:a})}):r||c?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Zt,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(mr,{iconSlot:o.jsx(Fg,{}),titleSlot:"Item not found",descriptionSlot:`No loaded item "${e}".`,actionSlot:o.jsx(ie,{icon:o.jsx(qt,{}),onClick:a,children:"Close"})})})})}):null}function krt(e,t){return{id:e.id,datasetId:t,datasetVersion:e.datasetVersion,input:e.input,groundTruth:e.groundTruth,expectedTrajectory:e.expectedTrajectory,toolMocks:e.toolMocks,scorerIds:e.scorerIds,requestContext:e.requestContext,metadata:e.metadata,createdAt:e.createdAt,updatedAt:e.updatedAt}}function Ort(e,t){return e.map(n=>{const r=typeof n.updatedAt=="string"?new Date(n.updatedAt):n.updatedAt;return{value:String(n.datasetVersion),label:o.jsxs("span",{className:"flex w-full items-center gap-2",children:[o.jsxs("span",{children:[o.jsxs("b",{children:["v. ",n.datasetVersion]})," · ",xr(r,"MMM d, HH:mm")]}),n.isLatest?o.jsx(xt,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function Crt(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function p1s(){const{datasetId:e,itemId:t}=tr(),[n,r]=da(),s=Crt(n.get("version")),a=Crt(n.get("compare")),i=n.get("view")==="diff",{data:l,error:c}=tv(e??""),{data:u,isLoading:d}=X0s(e??"",t??""),f=(s!=null?u?.find(_=>_.datasetVersion===s):void 0)??u?.[0],h=f?.datasetVersion??null,p=a!=null&&a!==h?a:null,{data:m,isLoading:v}=J0s(e??"",t??"",p??0,l?.version),y=(_,T)=>r(E=>{const N=new URLSearchParams(E);return T==null?N.delete(_):N.set(_,String(T)),N},{replace:!0});if(c&&ms(c))return o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zs,{})})});if(c&&gs(c))return o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{resource:"datasets"})})});if(!e||!t)return o.jsx(oa,{children:o.jsx(jx,{children:o.jsx("div",{className:"text-neutral4 py-5 text-center",children:o.jsx("p",{children:"Item not found."})})})});const b=!!(f&&m),x=i&&b,w=f?krt(f,e):null,k=m?krt(m,e):null,O=(f?.datasetVersion??0)<(m?.datasetVersion??0);return o.jsxs(oa,{children:[o.jsx(nv,{owner:"dataset-item-versions",children:b&&o.jsx(ie,{variant:"outline",onClick:()=>y("view",i?null:"diff"),children:i?o.jsxs(o.Fragment,{children:[o.jsx(qwe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(btn,{})," Diff View"]})})}),o.jsx(Bt,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-4 md:grid-cols-2",children:[o.jsxs(Uf,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(fbe,{children:o.jsx(_rt,{name:"version",value:h!=null?String(h):"",options:Ort(u??[],p!=null?new Set([p]):void 0),onValueChange:_=>y("version",Number(_))})}),o.jsx(Kx,{className:"grid content-start gap-5 overflow-y-auto",children:d?o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Loading..."}):w?o.jsx(kwe,{item:w,diff:x&&k?{against:k,side:O?"a":"b"}:void 0}):o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Item data not available"})})]}),o.jsxs(Uf,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(fbe,{children:o.jsx(_rt,{name:"compare",value:p!=null?String(p):"",placeholder:"Select a version to compare",options:Ort(u??[],h!=null?new Set([h]):void 0),onValueChange:_=>y("compare",Number(_))})}),o.jsx(Kx,{className:"grid content-start gap-5 overflow-y-auto",children:p==null?o.jsx(mr,{className:"h-full",iconSlot:o.jsx(ome,{className:"text-neutral3 size-8"}),titleSlot:"No version selected",descriptionSlot:"Pick a version above to compare it with the one on the left."}):v?o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Loading..."}):k?o.jsx(kwe,{item:k,diff:x&&w?{against:w,side:O?"b":"a"}:void 0}):o.jsxs("div",{className:"text-neutral4 text-ui-md",children:["Version ",p," not found"]})})]})]})})]})}function _rt({name:e,value:t,options:n,placeholder:r="Select version",onValueChange:s}){return o.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-4",children:[o.jsx(Kwe,{className:"size-4 opacity-50"}),o.jsxs($a,{name:e,value:t,onValueChange:s,children:[o.jsx(Da,{"aria-label":e==="compare"?"Compare version":"Version",className:"w-full",children:o.jsx(Ma,{placeholder:r,className:"flex-1"})}),o.jsx(La,{children:n.map(a=>o.jsx(Pr,{value:a.value,disabled:a.disabled,children:a.label},a.value))})]})]})}function m1s(){const{datasetId:e}=tr(),[t]=da(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=zr(),{data:s,error:a}=tv(e??""),i=VC(e??"",void 0,n[0]??null),l=VC(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const m=new Map;for(const v of[...c,...u])m.has(v.id)||m.set(v.id,{id:v.id,createdAt:new Date(v.createdAt)});return[...m.values()].sort((v,y)=>y.createdAt.getTime()-v.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(m=>[m.id,m])),[c]),h=g.useMemo(()=>new Map(u.map(m=>[m.id,m])),[u]);if(a&&ms(a))return o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zs,{})})});if(a&&gs(a))return o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(oa,{children:o.jsx(jx,{children:o.jsx("div",{className:"text-neutral4 py-5 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const p=(m,v)=>{r(`/datasets/${e}/versions?ids=${m},${v}`,{replace:!0})};return o.jsx(oa,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-4",children:[o.jsxs(Ph,{children:[o.jsxs(Ph.Column,{children:[o.jsxs(Ph.Title,{children:[o.jsx(Crn,{})," Compare Dataset Versions"]}),o.jsx(Ph.Description,{children:o.jsxs(Dd,{children:[o.jsx(Kwe,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(Ph.Column,{children:o.jsx(ie,{as:xo,to:`/datasets/${e}`,icon:o.jsx(Lc,{}),children:"Back to Dataset"})})]}),o.jsx(LM,{children:o.jsxs(tl,{children:[o.jsx(zSs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:p}),o.jsx(o1s,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h})]})})]})})})}function g1s(){const e=zr(),[t]=da(),n=t.get("targetType"),r=VZt(n)?n:void 0,s=t.get("targetIds"),a=r&&s?s.split(",").map(i=>i.trim()).filter(Boolean):void 0;return o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[o.jsx(Ph,{className:"mb-6 p-0",children:o.jsxs(Ph.Column,{children:[o.jsxs(Ph.Title,{children:[o.jsx(Fg,{})," Create new dataset"]}),o.jsx(Ph.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Uf,{className:"p-4",children:o.jsx(zws,{targetType:r,targetIds:a,onSuccess:i=>{e(`/datasets/${i}`)},onCancel:()=>{e(-1)}})})]})})]})}function Owe({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-4",t),children:e})}function v1s(e){if(!e||e.length<2)return null;const t=[...e].sort((i,l)=>new Date(i.createdAt).getTime()-new Date(l.createdAt).getTime()),n=Math.floor(t.length/2),r=n,s=t.length-n;if(r===0)return null;const a=(s-r)/r*100;return{changePct:Math.round(a*10)/10,prevValue:String(r)}}function y1s({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:a,isLoadingScorers:i,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,h=t?.length,p=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=v1s(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Total Scorers"}),i?o.jsx(Jr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(f)}),o.jsx(Jr.NoChange,{message:"Static count"})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Total Datasets"}),l?o.jsx(Jr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(h)}),o.jsx(Jr.NoChange,{message:"Static count"})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Avg Score"}),u?o.jsx(Jr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(r)}),m?o.jsx(Jr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Jr.NoChange,{})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Total Experiments"}),c?o.jsx(Jr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(p)}),v?o.jsx(Jr.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(Jr.NoChange,{})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Needs Review"}),d?o.jsx(Jr.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(a)}),a>0?o.jsx(Jr.NoChange,{message:"items pending review"}):o.jsx(Jr.NoChange,{message:"All caught up"})]}):o.jsx(Jr.NoData,{})]})]})}function rGt({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:a}=za(),i=async()=>{try{await a.mutateAsync(n),Be.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Be.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return o.jsx(At,{open:e,onOpenChange:t,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Experiment"}),o.jsxs(At.Description,{children:['Are you sure you want to delete "',r||n,'"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.']})]}),o.jsxs(At.Footer,{children:[o.jsx(ie,{icon:o.jsx(yi,{}),variant:"primary",size:"lg",onClick:i,disabled:a.isPending,children:a.isPending?"Deleting...":"Delete"}),o.jsx(At.Cancel,{children:"Cancel"})]})]})})}function sGt(e){const t=A0(e.id)??e.id;return e.name||`Experiment #${t}`}const b1s=60;function x1s({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:sGt(e)})}function w1s({experiment:e}){const t=e.description;if(!t)return o.jsx("span",{className:"text-neutral2",children:"—"});const n=o.jsx("span",{className:"text-neutral3 block min-w-0 truncate text-left",children:t});return t.length<=b1s?n:o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:n}),o.jsx(pn,{children:t})]})}function aGt(){const{data:e}=Yf(),{data:t}=Bm(),{data:n}=tf(),{data:r}=HA();return{agents:e,workflows:t,scorers:n,processors:r}}const iGt={agent:Pi,workflow:hc,scorer:D0,processor:nH},oGt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},S1s="External (caller-run)";function lGt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:a,targetId:i}=e;if(!i)return S1s;switch(a){case"agent":return t?.[i]?.name??i;case"workflow":return n?.[i]?.name??i;case"scorer":return r?.[i]?.scorer?.config?.name??i;case"processor":return s?.[i]?.name??i;default:return i}}function k1s({experiment:e,datasetName:t,review:n}){const r=e.status??"pending",s=e.succeededCount??0,a=e.failedCount??0,i=e.totalItems??0;return o.jsxs(o.Fragment,{children:[o.jsx(be.Cell,{children:o.jsx(x1s,{experiment:e})}),o.jsx(be.Cell,{children:o.jsx(w1s,{experiment:e})}),t!==void 0&&o.jsx(be.TextCell,{children:t}),o.jsx(be.Cell,{children:o.jsx(O1s,{experiment:e})}),o.jsx(be.Cell,{children:o.jsx(xt,{variant:VHt[r]??"neutral",indicator:"dot",children:rj[r]??r})}),o.jsx(be.TextCell,{className:"text-center",children:i}),o.jsx(be.TextCell,{className:"text-center",children:s}),o.jsx(be.TextCell,{className:"text-center",children:o.jsx("span",{className:a>0?"text-accent2":"",children:a})}),o.jsx(be.Cell,{className:"text-center",children:o.jsx(C1s,{review:n})}),o.jsx(be.TextCell,{children:Xps(e.createdAt)})]})}function O1s({experiment:e}){const t=aGt(),n=lGt(e,t),r=e.targetId?e.targetType:null,s=r?iGt[r]:null;return o.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[s&&o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":oGt[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function C1s({review:e}){if(!e)return o.jsx("span",{className:"text-neutral2",children:"—"});const t=e.needsReview+e.complete;return t===0?o.jsx("span",{className:"text-neutral2",children:"—"}):e.needsReview>0?o.jsxs(xt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(xt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const cGt=`${Gps} ${Qps} ${Yps} ${Kps}`,Ert=`${cGt} auto`,_1s=[{label:Av.experiment},{label:Av.description},{label:Av.dataset},{label:Av.target},{label:Av.status},{label:Av.items,className:"text-center"},{label:Av.succeeded,className:"text-center"},{label:Av.failed,className:"text-center"},{label:Av.review,className:"text-center"},{label:Av.date}],uGt=e=>e.stopPropagation();function E1s({experiment:e,rowProps:t,onDelete:n,children:r}){const{paths:s,Link:a}=ln(),i=g.useRef(null);return o.jsxs(be.RowWrapper,{...t,onSelectRow:()=>i.current?.click(),children:[o.jsx(be.RowLink,{ref:i,colEnd:-2,to:s.experimentLink(e.id),LinkComponent:a,tabIndex:-1,onClick:uGt,children:r}),o.jsx(be.ActionsCell,{className:"pl-2",children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-xs",tooltip:"Delete experiment","aria-label":`Delete experiment ${e.name??e.id}`,onClick:l=>{l.stopPropagation(),n()},children:o.jsx(yi,{className:"size-4"})})})]})}function T1s({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all",selection:l,isFetchingNextPage:c,hasNextPage:u,setEndOfListElement:d}){const f=l!==void 0,h=g.useMemo(()=>{const O=new Map;return t?.forEach(_=>O.set(_.id,_.name)),O},[t]),p=g.useMemo(()=>[...e].sort((O,_)=>{const T=O.createdAt?new Date(O.createdAt).getTime():0;return(_.createdAt?new Date(_.createdAt).getTime():0)-T}),[e]),m=g.useMemo(()=>{const O=s.toLowerCase();return p.filter(_=>{const T=_.datasetId?h.get(_.datasetId)??"":"",E=!O||_.id.toLowerCase().includes(O)||(_.name??"").toLowerCase().includes(O)||T.toLowerCase().includes(O)||(_.targetId??"").toLowerCase().includes(O),N=a==="all"||_.status===a,I=i==="all"||_.datasetId===i;return E&&N&&I})},[p,s,h,a,i]),{containerRef:v,getRowProps:y}=ll({count:m.length,global:!0}),[b,x]=g.useState(null);if(r)return o.jsx(Uo,{columns:Ert});const w=f?`auto ${cGt}`:Ert,k=_1s.map(O=>o.jsx(be.TopCell,{className:O.className,children:O.label},O.label));return o.jsxs(be,{columns:w,scrollRef:v,children:[o.jsx(be.Top,{hasLeadingCell:f,children:f?o.jsxs(o.Fragment,{children:[o.jsx(be.TopCell,{children:" "}),o.jsx(be.TopCells,{colStart:2,children:k})]}):o.jsxs(o.Fragment,{children:[k,o.jsx(be.TopCell,{"aria-hidden":!0,children:null})]})}),m.map((O,_)=>{const T=O.datasetId?h.get(O.datasetId)??A0(O.datasetId)??O.datasetId:"—",E=o.jsx(k1s,{experiment:O,datasetName:T,review:n?.get(O.id)});if(!l)return o.jsx(E1s,{experiment:O,rowProps:y(_),onDelete:()=>x(O),children:E},O.id);const N=l.selectedExperimentIds.includes(O.id),I=()=>l.onToggleSelection(O.id);return o.jsxs(be.RowWrapper,{...y(_),onSelectRow:I,children:[o.jsx(be.SelectCell,{checked:N,onToggle:I,"aria-label":`Select experiment ${O.id}`}),o.jsx(be.RowButton,{colStart:2,featured:N,tabIndex:-1,onClick:uGt,children:E})]},O.id)}),o.jsx(be.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:d}),b&&o.jsx(rGt,{open:!0,onOpenChange:O=>{O||x(null)},experimentId:b.id,experimentName:b.name??void 0})]})}const j1s=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function N1s(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const F8={completed:CB.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},I1s=[{label:"Completed",color:F8.completed},{label:"Running",color:F8.running},{label:"Pending",color:F8.pending},{label:"Failed",color:F8.failed}];function A1s({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const h=f.datasetId??"unknown";c.has(h)||c.set(h,{completed:0,running:0,pending:0,failed:0});const p=c.get(h),m=f.status;m in p&&p[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,h])=>{const p=h.completed+h.running+h.pending+h.failed;return p>u&&(u=p),{name:l.get(f)??f.slice(0,12),values:[h.completed,h.running,h.pending,h.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Wt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Wt.Loading,{}):r?o.jsx(Wt.Error,{message:"Failed to load experiments data"}):o.jsx(Wt.Content,{children:i?o.jsx(gI,{data:s,segments:I1s,maxVal:a,fmt:l=>String(l)}):o.jsx(Wt.NoData,{message:"No experiments have been run yet"})})]})}const R1s=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&o.jsx(ie,{variant:"primary",onClick:e,icon:o.jsx(oc,{}),children:"Run Experiment"}),o.jsx(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer",icon:o.jsx(Cs,{}),children:"Experiments Documentation"})]})})});function P1s({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,targetType:l,onTargetTypeChange:c,targetId:u,onTargetIdChange:d,onReset:f,hasActiveFilters:h,onRunClick:p,runTooltip:m="Run an experiment",onCompareClick:v,selection:y}){const b=y?.selectedCount===2&&!y.compareDisabledReason;return o.jsxs("div",{className:"min-h-form-md flex flex-wrap items-center gap-2",children:[o.jsx("div",{className:"max-w-120 min-w-48 flex-1",children:o.jsx(qc,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),o.jsxs(Wr,{children:[o.jsx(ad,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...j1s],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(ad,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),o.jsx(BPe,{targetType:l,targetId:u,onTargetTypeChange:c,onTargetIdChange:d}),f&&h&&o.jsx(ie,{onClick:f,size:"sm",variant:"default",icon:o.jsx(qt,{}),children:"Reset"})]}),y?o.jsxs(Wr,{className:"ml-auto shrink-0 whitespace-nowrap",children:[o.jsxs(Uh,{className:"gap-2",children:[o.jsxs(xt,{size:"sm",variant:y.selectedCount<2?"red":"green",children:[y.selectedCount," / 2"]}),"selected",y.compareDisabledReason&&o.jsxs("span",{className:"text-accent2",children:["· ",y.compareDisabledReason]})]}),o.jsx(ie,{variant:"primary",disabled:!b,onClick:y.onExecuteCompare,icon:o.jsx(ome,{}),children:"Compare Experiments"}),o.jsx(ie,{icon:o.jsx(qt,{}),onClick:y.onCancelSelection,children:"Cancel"})]}):o.jsxs(Wr,{className:"ml-auto shrink-0",children:[v&&o.jsx(ie,{onClick:v,tooltip:"Select two experiments of the same dataset to compare",icon:o.jsx(ome,{}),children:"Compare"}),p&&o.jsx(ie,{onClick:p,tooltip:m,variant:"primary",icon:o.jsx(oc,{}),children:"Run Experiment"})]})]})}const $1s={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Trt=e=>e?e instanceof Date?e.toISOString():e:null,jrt=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},Nrt=(e,t,n)=>{if(!e)return $1s;const r=new Map;for(const s of n??[])r.set(s.scorerId,s.reason??null);return{present:!0,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:Trt(t?.startedAt),completedAt:Trt(t?.completedAt),scores:Object.entries(e.scores).map(([s,a])=>({scorerId:s,value:a,reason:r.get(s)??null})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))}},M1s=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:a,contenderScores:i})=>{if(!e)return[];const l=jrt(r),c=jrt(s);return e.items.map(u=>{const d=Nrt(u.results[t],l.get(u.itemId),a?.[u.itemId]),f=Nrt(u.results[n],c.get(u.itemId),i?.[u.itemId]),h={};for(const p of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(y=>y.scorerId===p)?.value??null,v=f.scores.find(y=>y.scorerId===p)?.value??null;h[p]=m!=null&&v!=null?v-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:h}})};function eO({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(cc,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(ql,{className:K("text-ui-md flex items-center gap-1.5 font-semibold [&>svg]:size-4",n==="negative"?"text-negative1":"text-neutral5"),children:[o.jsx(wr,{}),e]}),t]}),o.jsx(Vl,{role:"region","aria-label":e,children:s})]})}function Irt({label:e,value:t}){return t==null?null:o.jsx(eO,{title:e,defaultOpen:!1,children:o.jsx("pre",{className:"text-ui-sm text-neutral4 bg-surface3 max-h-40 overflow-auto rounded-md p-3 whitespace-pre-wrap",children:typeof t=="string"?t:JSON.stringify(t,null,2)})})}function dGt({delta:e}){const t=e>0?"text-positive1":e<0?"text-negative1":"text-neutral3";return o.jsxs("span",{className:K("inline-flex min-w-20 items-center gap-1 font-mono text-ui-md",t),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?o.jsx(Idt,{className:"size-3.5"}):e<0?o.jsx(WXt,{className:"size-3.5"}):null]})}function fGt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:a}=ln();return o.jsxs("div",{className:"bg-surface2 grid gap-1 rounded-lg px-3 py-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsxs(s,{href:a.scorerLink(e),"aria-label":`Open ${e}`,className:"text-neutral5 text-ui-md flex min-w-0 items-center gap-1.5 font-medium hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(D0,{}),o.jsx("span",{className:"min-w-0 truncate",children:e})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-neutral3 text-ui-md font-mono",children:t!=null?t.toFixed(2):"-"}),n!=null&&o.jsx(dGt,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-ui-md",children:r})]})}function Art(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function D1s(e){if(!e.startedAt||!e.completedAt)return null;const t=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Number.isFinite(t)?`${(t/1e3).toFixed(2)}s`:null}const L1s="border-border1 bg-surface3 text-ui-md text-neutral4 max-h-[30vh] overflow-y-auto rounded-xl border p-4 font-mono break-all whitespace-pre-wrap dark:border-white/10 dark:bg-black/20";function Rrt({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],a=D1s(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(Zt,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 text-ui-md py-5 text-center",children:"Not present in this experiment"});const i=Art(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[a&&o.jsxs(gn,{children:[o.jsx(hn,{render:o.jsxs("p",{className:"text-neutral3 text-ui-md flex items-center justify-end gap-1.5 [&>svg]:size-3.5",children:[o.jsx(xS,{}),a]})}),o.jsx(pn,{children:"Run duration"})]}),s.error?o.jsx(eO,{title:"Error",tone:"negative",actions:o.jsx(Pa,{content:s.error.message}),children:o.jsx("p",{className:"border-negative1/40 bg-negative1/5 text-ui-md text-neutral4 rounded-xl border p-4 break-words",children:s.error.message})}):o.jsx(eO,{title:"Output",actions:o.jsx(Pa,{content:i}),children:o.jsx("pre",{className:L1s,children:i})}),s.scores.length>0&&o.jsx(eO,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx(fGt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(eO,{title:"Comment",defaultOpen:!1,children:o.jsx("p",{className:"text-neutral3 text-ui-md",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&o.jsx(eO,{title:"Metadata",defaultOpen:!1,children:o.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>o.jsxs("div",{className:"text-ui-md flex items-start justify-between gap-4",children:[o.jsx("dt",{className:"text-neutral3",children:l}),o.jsx("dd",{className:"text-neutral5 font-mono break-all",children:Art(c)})]},l))})})]})}const F1s={baseline:"Baseline",contender:"Contender"},z1s={baseline:"purple",contender:"blue"},B1s="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function Prt({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:a,paths:i}=ln(),l=F1s[e],c=t?A0(t.id)??t.id:null,u=t?.createdAt?new Date(t.createdAt):null,d=n??[];return o.jsxs("div",{className:"grid content-start gap-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(xt,{variant:z1s[e],size:"xs",children:l}),t&&o.jsx(ie,{as:a,size:"xs",href:`/experiments/${t.id}`,"aria-label":`Open experiment ${t.name||c}`,children:o.jsx("span",{className:"min-w-0 truncate",children:t.name||c})})]}),t&&o.jsxs("div",{className:"text-ui-sm text-neutral3 flex flex-wrap gap-x-4 gap-y-1",children:[t.name&&o.jsxs(Dd,{children:[o.jsx(A3,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(a,{href:i.agentLink(t.targetId),className:B1s,children:[o.jsx(Pi,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Dd,{children:[o.jsx(aft,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Dd,{children:[o.jsx(wH,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Dd,{children:[o.jsx(_7,{})," ",xr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(eO,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:h,delta:p})=>o.jsx(fGt,{scorerId:f,value:h,delta:r?p:null},f))})})]})}const oT="min-w-0 px-4 py-3";function U1s({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=ln(),{data:a,isLoading:i,error:l}=ews(e,t,n),{data:c}=w3(e,t),{data:u}=w3(e,n),d=c&&u&&c.datasetVersion!==u.datasetVersion,f=a?.baselineId??t,h=t===f?n:t,p=c?.id===f?c:u,m=c?.id===h?c:u,{data:v,isLoading:y}=S3({datasetId:e,experimentId:f,experimentStatus:p?.status}),{data:b,isLoading:x}=S3({datasetId:e,experimentId:h,experimentStatus:m?.status}),{data:w}=Fy(f,p?.status),{data:k}=Fy(h,m?.status),O=g.useMemo(()=>M1s({comparison:a,baselineId:f,contenderId:h,baselineResults:v,contenderResults:b,baselineScores:w,contenderScores:k}),[a,f,h,v,b,w,k]),_=g.useMemo(()=>[...new Set(O.flatMap(E=>Object.keys(E.deltas)))].sort(),[O]),T=g.useMemo(()=>{const E=(A,$)=>{const z=O.map(D=>D[A].scores.find(q=>q.scorerId===$)?.value).filter(D=>D!=null);return z.length>0?z.reduce((D,q)=>D+q,0)/z.length:null},N=_.map(A=>({scorerId:A,average:E("baseline",A),delta:null})),I=_.map(A=>{const $=E("baseline",A),z=E("contender",A);return{scorerId:A,average:z,delta:$!=null&&z!=null?z-$:null}});return{baseline:N,contender:I}},[O,_]);return i?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Zt,{})}):l?o.jsx(Nn,{variant:"warning",title:"Error loading comparison",children:o.jsx(Nn.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!a||a.items.length===0?o.jsx("div",{className:"text-neutral4 text-ui-md py-5 text-center",children:"No comparison data"}):o.jsx("div",{className:"grid gap-4",children:o.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",children:[o.jsxs("div",{role:"row",className:"border-border1 grid border-y xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsx("div",{role:"columnheader","aria-label":"Items",className:`${oT} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:oT,children:o.jsx(Prt,{side:"baseline",experiment:p,summary:T.baseline,versionMismatch:d})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:oT,children:o.jsx(Prt,{side:"contender",experiment:m,summary:T.contender,versionMismatch:d,showDeltas:!0})})]}),O.map(E=>{const N=Object.entries(E.deltas).filter(([,I])=>I!=null&&I!==0);return o.jsxs("div",{role:"row","aria-label":E.itemId,className:"border-border1 grid border-b xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsxs("div",{role:"cell",className:`${oT} grid content-start gap-1`,children:[o.jsx(r,{href:s.datasetItemLink(e,E.itemId),"aria-label":`Open item ${E.itemId}`,className:K("text-ui-sm flex items-start gap-1.5 font-mono break-all hover:underline [&>svg]:mt-0.5 [&>svg]:size-3.5 [&>svg]:shrink-0",E.baseline.present&&E.contender.present?"text-neutral4":"text-neutral1"),children:o.jsx("span",{className:"min-w-0",children:E.itemId})}),N.length>0&&o.jsx("span",{className:"flex flex-wrap items-center gap-2",children:N.map(([I,A])=>o.jsx(dGt,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx(Irt,{label:"Input",value:E.input}),o.jsx(Irt,{label:"Ground truth",value:E.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:oT,children:o.jsx(Rrt,{side:"baseline",row:E,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:oT,children:o.jsx(Rrt,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}const q1s=100;function HPe(e,t){const n=Ge(),r={perPage:q1s};return t?.targetType&&(r.targetType=t.targetType),t?.targetId&&(r.targetId=t.targetId),mt({queryKey:["experiments",r],queryFn:()=>n.listExperiments(r)})}const hGt=(e,{experimentId:t,targetType:n,targetId:r})=>{const s=Ge(),{data:a,isLoading:i}=HPe(void 0,{targetType:n,targetId:r}),l=a?.experiments,c=t?l?.filter(d=>d.id===t):l,u=mt({queryKey:["review-items",e,t??"all",n||"all",r||"all",c?.map(d=>d.id)],queryFn:async()=>!c||c.length===0?[]:(await Promise.all(c.map(async f=>{if(!f.datasetId)return[];try{const{results:h}=await s.listDatasetExperimentResults(f.datasetId,f.id);return h.filter(p=>p.status===e).map(p=>({id:p.id,input:p.input,output:p.output,error:p.error,itemId:p.itemId,experimentId:p.experimentId,datasetId:f.datasetId??void 0,traceId:p.traceId??void 0,scores:p.scores?Object.fromEntries(p.scores.map(m=>[m.scorerId,m.score??0])):{},tags:p.tags??[],createdAt:p.createdAt,status:p.status,groundTruth:p.groundTruth,toolMockReport:p.toolMockReport}))}catch{return[]}}))).flat(),enabled:!!l,refetchOnWindowFocus:!1});return{...u,isLoading:u.isLoading||i}},V1s=(e={})=>hGt("needs-review",e),H1s=(e={})=>hGt("complete",e),W1s=[{name:"itemId",label:"Item ID",size:"auto"},{name:"input",label:"Input",size:"minmax(0,1fr)"},{name:"tags",label:"Tags",size:"auto"},{name:"scores",label:"Scores",size:"6rem"}],tle="__untagged__",nle="all",Z1s=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}];function G1s({datasetId:e,experimentId:t,targetType:n,targetId:r,featuredItemId:s,detailPanelVariant:a="inline",toolbarStart:i,toolbarEnd:l}){const c=Ge(),{paths:u}=ln(),{data:d}=tv(e??""),{data:f,isLoading:h}=V1s({experimentId:t,targetType:n,targetId:r}),{data:p,isLoading:m}=H1s({experimentId:t,targetType:n,targetId:r}),{updateExperimentResult:v}=za(),[y,b]=g.useState(s??null);g.useEffect(()=>{s!==void 0&&b(s)},[s]);const[x,w]=g.useState(null),[k,O]=g.useState(new Set),[_,T]=g.useState(!1),[E,N]=g.useState(!1),[I,A]=g.useState(!1),[$,z]=g.useState(""),[D,q]=g.useState(""),[H,V]=g.useState(""),[B,W]=g.useState([]),[L,G]=g.useState(!1),M=g.useMemo(()=>f??[],[f]),R=g.useMemo(()=>{const de=new Set;if(d?.tags)for(const _e of d.tags)de.add(_e);for(const _e of M)for(const Ae of _e.tags)de.add(Ae);return[...de].sort()},[d,M]),F=g.useCallback(de=>{!d||!e||(d.tags??[]).includes(de)},[d,e]),U=g.useMemo(()=>x?x===tle?M.filter(de=>de.tags.length===0):M.filter(de=>de.tags.includes(x)):M,[M,x]),Q=g.useMemo(()=>{const de=new Map;let _e=0;for(const $e of M){$e.tags.length===0&&_e++;for(const me of $e.tags)de.set(me,(de.get(me)??0)+1)}const Ae=[...de.entries()].sort(($e,me)=>me[1]-$e[1]).map(([$e])=>({value:$e,label:$e}));return[{value:nle,label:"All tags"},..._e>0?[{value:tle,label:"Untagged"}]:[],...Ae]},[M]),te=!!x||_,J=g.useCallback(()=>{w(null),T(!1),b(null)},[]),ee=g.useCallback((de,_e)=>{const Ae=M.find($e=>$e.id===de);Ae?.experimentId&&Ae?.datasetId&&v.mutate({datasetId:Ae.datasetId,experimentId:Ae.experimentId,resultId:Ae.id,tags:_e})},[M,v]),re=g.useCallback(de=>{const _e=M.find(Ae=>Ae.id===de);O(Ae=>{const $e=new Set(Ae);return $e.delete(de),$e}),y===de&&b(null),_e?.experimentId&&_e?.datasetId&&v.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,status:null})},[M,v,y]),ae=g.useCallback(de=>{const _e=M.find(Ae=>Ae.id===de);O(Ae=>{const $e=new Set(Ae);return $e.delete(de),$e}),y===de&&b(null),_e?.experimentId&&_e?.datasetId&&v.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,status:"complete"})},[M,v,y]),X=g.useMemo(()=>{const de=_?p??[]:U;return!_||!x?de:x===tle?de.filter(_e=>_e.tags.length===0):de.filter(_e=>_e.tags.includes(x))},[_,p,U,x]),ne=_?m:!1,se=g.useMemo(()=>new Set(X.map(de=>de.id)),[X]),ce=g.useMemo(()=>[...k].filter(de=>se.has(de)).length,[k,se]),le=X.length>0&&ce===X.length,ve=g.useCallback(de=>{O(_e=>{const Ae=new Set(_e);return Ae.has(de)?Ae.delete(de):Ae.add(de),Ae})},[]),ye=g.useCallback(()=>{O(le?new Set:new Set(X.map(de=>de.id)))},[le,X]),Te=g.useCallback(de=>{for(const _e of k){const Ae=M.find($e=>$e.id===_e);Ae&&!Ae.tags.includes(de)&&ee(_e,[...Ae.tags,de])}},[M,k,ee]),Me=g.useCallback(de=>{for(const _e of k){const Ae=M.find($e=>$e.id===_e);Ae&&Ae.tags.includes(de)&&ee(_e,Ae.tags.filter($e=>$e!==de))}},[M,k,ee]),Ze=g.useCallback(()=>{for(const de of k)ae(de);O(new Set)},[k,ae]),Ve=g.useCallback(()=>{for(const de of k)re(de);O(new Set)},[k,re]),Ue=g.useCallback(()=>{z(""),A(!0)},[]),ke=g.useCallback(async()=>{if(!(!D||!H)){N(!0),A(!1);try{const de=M.filter(Ae=>k.has(Ae.id));if(de.length===0){N(!1);return}const _e=await c.clusterFailures({modelId:`${D}/${H}`,items:de.map(Ae=>({id:Ae.id,input:Ae.input,output:Ae.output??void 0,error:typeof Ae.error=="string"?Ae.error:Ae.error?String(Ae.error):void 0,scores:Ae.scores,existingTags:Ae.tags.length>0?Ae.tags:void 0})),availableTags:R.length>0?R:void 0,prompt:$||void 0});_e.proposedTags&&_e.proposedTags.length>0&&(W(_e.proposedTags.map(Ae=>({...Ae,accepted:!0}))),G(!0))}catch(de){console.error("Analysis failed:",de)}finally{N(!1)}}},[D,H,M,k,c,R,$]),Pe=g.useCallback(()=>{for(const de of B){if(!de.accepted)continue;const _e=M.find(Ae=>Ae.id===de.itemId);if(_e){const Ae=[...new Set([..._e.tags,...de.tags])];ee(_e.id,Ae)}}G(!1)},[B,M,ee]),Se=g.useCallback(de=>{b(_e=>_e===de?null:de)},[]),xe=g.useMemo(()=>y?X.find(de=>de.id===y)??null:null,[y,X]),{data:Ne}=Fy(xe?.experimentId??""),we=y?X.findIndex(de=>de.id===y):-1,Ie=we>0?()=>b(X[we-1].id):void 0,Qe=we>=0&&we<X.length-1?()=>b(X[we+1].id):void 0,qe=!_&&k.size>0,he=o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs(Wr,{children:[i,o.jsx(ad,{label:"Status",labelIsHidden:!0,name:"filter-status",options:Z1s,value:_?"completed":"review",onValueChange:de=>{T(de==="completed"),b(null)},className:"whitespace-nowrap"}),Q.length>1&&o.jsx(ad,{label:"Tags",labelIsHidden:!0,name:"filter-tags",options:Q,value:x??nle,onValueChange:de=>w(de===nle?null:de),className:"whitespace-nowrap"}),te&&o.jsx(ie,{onClick:J,size:"sm",variant:"default",icon:o.jsx(qt,{}),children:"Reset"})]}),(qe||l)&&o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[l,qe&&o.jsxs(o.Fragment,{children:[o.jsx(yZt,{size:"md",selectedCount:k.size,vocabulary:R,onApplyTag:Te,onRemoveTag:Me,onNewTag:de=>Te(de)}),o.jsx(ie,{variant:"primary",onClick:Ze,icon:o.jsx(kI,{}),children:"Mark as reviewed"}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{variant:"outline",disabled:E,"aria-label":"More actions",children:E?o.jsx(Zt,{className:"h-4 w-4"}):o.jsx(Ldt,{})})}),o.jsxs(ot.Content,{align:"end",children:[o.jsxs(ot.Item,{onSelect:Ue,children:[o.jsx(st,{size:"sm",children:o.jsx(SS,{})}),"Analyze"]}),o.jsx(ot.Separator,{}),o.jsxs(ot.Item,{onSelect:Ve,children:[o.jsx(st,{size:"sm",children:o.jsx(yi,{})}),"Remove from queue"]})]})]})]})]})]});if(h)return o.jsxs(o.Fragment,{children:[o.jsx(Bt.TopArea,{children:he}),o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(Zt,{className:"h-6 w-6"})})]});const fe=xe?o.jsx(CPe,{className:"h-full",result:xe,scores:Ne?.[xe.itemId],experimentLink:xe.experimentId?u.experimentItemLink(xe.experimentId,xe.itemId):void 0,tagVocabulary:R,onTagsChange:_?void 0:de=>{ee(xe.id,de);for(const _e of de)R.includes(_e)||F(_e)},onComplete:_?void 0:()=>ae(xe.id),onPrevious:Ie,onNext:Qe,onClose:()=>b(null)}):null;return o.jsxs(o.Fragment,{children:[o.jsx(Bt.TopArea,{children:he}),o.jsx(vr,{open:I,onOpenChange:A,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Analyze Items"}),o.jsx(Ms,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx(Dt,{className:"text-ui-sm mb-1 block",children:"Provider"}),o.jsx(sb,{value:D,onValueChange:q})]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"text-ui-sm mb-1 block",children:"Model"}),o.jsx(ab,{llmId:D,value:H,onValueChange:V})]})]}),o.jsxs(ge,{variant:"ui-xs",className:"text-neutral3",children:[k.size," item",k.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"text-ui-sm",children:"Instructions (optional)"}),o.jsx(Bo,{value:$,onChange:de=>z(de.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"text-ui-sm mt-1"})]})]}),o.jsxs(Bl,{children:[o.jsx(ie,{icon:o.jsx(qt,{}),variant:"outline",onClick:()=>A(!1),children:"Cancel"}),o.jsxs(ie,{onClick:ke,disabled:!D||!H||E,children:[E?o.jsx(Zt,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(vr,{open:L,onOpenChange:G,children:o.jsxs(yr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Review Proposed Tags"}),o.jsxs(Ms,{children:[B.filter(de=>de.accepted).length," of ",B.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:B.map((de,_e)=>{const Ae=M.find($e=>$e.id===de.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!de.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ul,{checked:de.accepted,onCheckedChange:$e=>W(me=>me.map((Ee,De)=>De===_e?{...Ee,accepted:!!$e}:Ee))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 block truncate",children:Ae?typeof Ae.input=="string"?Ae.input.slice(0,100):JSON.stringify(Ae.input).slice(0,100):de.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:de.tags.map(($e,me)=>o.jsx(bZt,{tag:$e,onRename:Ee=>W(De=>De.map((Ke,Ot)=>Ot===_e?{...Ke,tags:Ke.tags.map((Re,Xe)=>Xe===me?Ee:Re)}:Ke)),onRemove:()=>W(Ee=>Ee.map((De,Ke)=>Ke===_e?{...De,tags:De.tags.filter((Ot,Re)=>Re!==me)}:De))},`${$e}-${me}`))}),de.reason&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:de.reason})]})]})},de.itemId)})}),o.jsxs(Bl,{children:[o.jsx(ie,{icon:o.jsx(qt,{}),variant:"outline",onClick:()=>G(!1),children:"Cancel"}),o.jsxs(ie,{icon:o.jsx(Fn,{}),onClick:Pe,disabled:B.filter(de=>de.accepted).length===0,children:["Accept ",B.filter(de=>de.accepted).length," proposals"]})]})]})}),o.jsxs(Bt.MainArea,{className:K("grid h-full min-h-0 w-full grid-cols-1 gap-4",a==="overlay"?"overflow-visible":"overflow-hidden",xe&&a==="inline"&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"min-h-0 w-full overflow-hidden",children:ne?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zt,{className:"h-6 w-6"})}):X.length===0?o.jsx("div",{className:"flex h-full items-center-safe justify-center-safe overflow-auto py-8",children:o.jsx(mr,{iconSlot:o.jsx(Os,{className:"text-neutral3 h-8 w-8"}),titleSlot:_?"No completed reviews yet":"No items to review",descriptionSlot:_?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})}):o.jsx(KY,{results:X,isLoading:!1,featuredResultId:y,onResultClick:Se,columns:W1s,selectedIds:_?void 0:k,onToggleSelect:_?void 0:ve,onToggleSelectAll:_?void 0:ye})}),fe&&(a==="overlay"?o.jsx(rK,{label:`Review item ${xe?.id??""}`,children:o.jsx("div",{className:"[&>section]:bg-surface3 h-full min-h-0 p-3 [&>section]:rounded-lg [&>section]:shadow-lg",children:fe})}):fe)]})]})}const $rt={needsReview:"#facc15",complete:"#22c55e"},Q1s=[{label:"Needs Review",color:$rt.needsReview},{label:"Reviewed",color:$rt.complete}];function Y1s({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,h=0;const p=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;h+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);p.push({name:x,values:[m.needsReview,m.complete]})}return{data:p,maxVal:f,totalInPipeline:h}},[e,t,n]),c=a.length>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Wt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Wt.Loading,{}):s?o.jsx(Wt.Error,{message:"Failed to load review data"}):o.jsx(Wt.Content,{children:c?o.jsx(gI,{data:a,segments:Q1s,maxVal:i,fmt:u=>String(u)}):o.jsx(Wt.NoData,{message:"No items have been sent to review yet"})})]})}function pGt(){const e=Ge();return mt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function K1s(e){const t=new Map;if(!e?.counts)return t;for(const n of e.counts)t.set(n.experimentId,{needsReview:n.needsReview,complete:n.complete,total:n.total});return t}function X1s(e){return e?.counts?e.counts.reduce((t,n)=>({needsReview:t.needsReview+n.needsReview,complete:t.complete+n.complete,inPipeline:t.inPipeline+n.needsReview+n.complete}),{needsReview:0,complete:0,inPipeline:0}):{needsReview:0,complete:0,inPipeline:0}}function J1s(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=tf(),{data:l,isLoading:c,error:u}=Pm(),{data:d,isLoading:f,error:h}=RW(),{data:p,isLoading:m,isError:v,error:y}=Eds(n),{data:b,isLoading:x,isError:w,error:k}=pGt(),O=l?.datasets,_=d?.experiments,T=g.useMemo(()=>X1s(b),[b]),E=i||u||h||y||k;return E&&ms(E)?o.jsx(Qn,{children:o.jsx(zs,{})}):E&&gs(E)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"evaluation"})}):E?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load evaluation data",message:E.message})}):o.jsxs(Bt,{width:"wide",height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsx(Bt.Row,{children:o.jsx(Bt.Column,{children:o.jsx(w4,{preset:e,onPresetChange:t,dateFrom:n.start,dateTo:n.end,onDateChange:(N,I)=>r(A=>I==="from"?{...A,start:N}:{...A,end:N})})})})}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx(Owe,{children:o.jsx(y1s,{scorers:s,datasets:O,experiments:_,avgScore:p?.avgScore??null,prevAvgScore:p?.prevAvgScore??null,totalNeedsReview:T.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(eus,{summaryData:p?.summaryData??[],overTimeData:p?.overTimeData??[],scorerNames:p?.scorerNames??[],avgScore:p?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[o.jsx(kws,{experiments:_,isLoading:f,isError:!!h}),o.jsx(A1s,{experiments:_,datasets:O,isLoading:f,isError:!!h})]}),o.jsx(Y1s,{reviewSummary:b,experiments:_,datasets:O,isLoading:x,isError:!!w})]})]})}const eks=100;function tks(e,t){const n=Ge(),{inView:r,setRef:s}=Yy(),a=t?.targetType||void 0,i=t?.targetId||void 0,l=ev({queryKey:e?["dataset-experiments",e,"infinite",{targetType:a,targetId:i}]:["experiments","infinite",{targetType:a,targetId:i}],queryFn:({pageParam:c})=>{const u={page:c,perPage:eks};return a&&(u.targetType=a),i&&(u.targetId=i),e?n.listDatasetExperiments(e,u):n.listExperiments(u)},initialPageParam:0,getNextPageParam:(c,u,d)=>{if(!(!c?.experiments?.length||!c.pagination?.hasMore))return d+1},select:c=>c.pages.flatMap(u=>u?.experiments??[])});return g.useEffect(()=>{r&&l.hasNextPage&&!l.isFetchingNextPage&&l.fetchNextPage()},[r,l]),{...l,setEndOfListElement:s}}function nks(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState(!1),[i,l]=g.useState(!1),[c,u]=g.useState([]),d=zr(),[f,h]=da(),p=f.get("dataset")??"all",m=g.useCallback(J=>{h(ee=>{const re=new URLSearchParams(ee);return J==="all"?re.delete("dataset"):re.set("dataset",J),re},{replace:!0})},[h]),{targetType:v,targetId:y,setTargetType:b,setTargetId:x}=VPe(),{data:w,isLoading:k,error:O}=Pm(),{data:_,isLoading:T,error:E,isFetchingNextPage:N,hasNextPage:I,setEndOfListElement:A}=tks(p==="all"?void 0:p,{targetType:v,targetId:y}),{data:$}=pGt(),z=g.useMemo(()=>w?.datasets??[],[w?.datasets]),D=g.useMemo(()=>_??[],[_]),q=g.useMemo(()=>N1s(z),[z]),H=g.useMemo(()=>K1s($),[$]),V=k||T,B=E||O,W=J=>{u(ee=>ee.includes(J)?ee.filter(re=>re!==J):ee.length>=2?[ee[0],J]:[...ee,J])},L=()=>{u([]),l(!1)},{selectedIds:G,selectedDatasetIds:M}=g.useMemo(()=>{const J=new Map(D.map(re=>[re.id,re.datasetId])),ee=c.filter(re=>J.has(re));return{selectedIds:ee,selectedDatasetIds:new Set(ee.map(re=>J.get(re)))}},[D,c]),R=G.length===2&&M.size!==1?"not the same dataset":void 0,F=()=>{if(G.length!==2||R)return;const[J,ee]=G,[re]=M;if(!re)return;const ae=new URLSearchParams({dataset:re,baseline:J,contender:ee});d(`/experiments/compare?${ae.toString()}`)};if(B&&ms(B))return o.jsx(Qn,{children:o.jsx(zs,{})});if(E&&gs(E))return o.jsx(Qn,{children:o.jsx(Ts,{resource:"experiments"})});if(O&&gs(O))return o.jsx(Qn,{children:o.jsx(Ts,{resource:"datasets"})});if(B)return o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load experiments",message:B.message})});const U=o.jsx(nK,{open:s,onOpenChange:a,onSuccess:J=>{d(`/experiments/${J}`)}});if(D.length===0&&!V&&p==="all"&&!v)return o.jsxs(Qn,{children:[o.jsx(R1s,{onRunExperiment:()=>a(!0)}),U]});const Q=n!=="all"||p!=="all"||e!==""||v!=="",te=()=>{t(""),r("all"),h(J=>{const ee=new URLSearchParams(J);return ee.delete("dataset"),ee.delete(x7),ee.delete(Z$),ee},{replace:!0})};return o.jsxs(Bt,{height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsx(P1s,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:p,onDatasetFilterChange:m,datasetOptions:q,targetType:v,onTargetTypeChange:b,targetId:y,onTargetIdChange:x,onReset:te,hasActiveFilters:Q,onRunClick:()=>a(!0),onCompareClick:()=>l(!0),selection:i?{selectedCount:G.length,onExecuteCompare:F,onCancelSelection:L,compareDisabledReason:R}:void 0})}),o.jsx(T1s,{experiments:D,datasets:z,reviewByExperiment:H,isLoading:V,search:e,statusFilter:n,datasetFilter:p,isFetchingNextPage:N,hasNextPage:I,setEndOfListElement:A,selection:i?{selectedExperimentIds:G,onToggleSelection:W}:void 0}),U]})}function z8({experimentId:e}){const{Link:t,paths:n}=ln();return o.jsx(ie,{as:t,href:n.experimentLink(e),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function rks(){const[e,t]=da(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",a=w3(n,r),i=w3(n,s),l=a.isLoading||i.isLoading,c=a.error??i.error;return c&&ms(c)?o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zs,{})})}):c&&gs(c)?o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{resource:"experiments"})})}):!n||!r||!s?o.jsx(oa,{children:o.jsx(jx,{children:o.jsxs("div",{className:"text-neutral4 py-5 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"text-ui-md mt-2",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):l?null:c&&!R1(c)?o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{title:"Failed to load experiments",message:c.message})})}):c||!a.data||!i.data?o.jsx(oa,{children:o.jsx(jx,{children:o.jsxs("div",{className:"text-neutral4 py-5 text-center",children:[o.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),o.jsxs("p",{className:"text-ui-md mt-2 flex items-center justify-center gap-2",children:["One of",o.jsx(z8,{experimentId:r}),"and",o.jsx(z8,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(oa,{children:o.jsx(jx,{children:o.jsxs("div",{className:"grid w-full content-start",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-4 py-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(ge,{as:"h1",variant:"ui-lg",className:"text-neutral6 font-medium",children:"Experiments comparison"}),o.jsxs("p",{className:"text-ui-sm text-neutral4 flex items-center gap-2",children:[o.jsx(z8,{experimentId:r}),"and",o.jsx(z8,{experimentId:s})]})]}),o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx(ie,{onClick:()=>t({dataset:n,baseline:s,contender:r}),icon:o.jsx(Ndt,{}),children:"Swap sides"})}),o.jsx(pn,{children:"Switch baseline and contender"})]})]}),o.jsx(U1s,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}function sks({selection:e}){const{selectedIds:t,selectedResults:n,tagVocabulary:r,isFlagging:s,isTagging:a}=e;if(t.size===0)return null;const i=s||a;return o.jsxs(Wr,{className:"whitespace-nowrap",children:[o.jsxs(ie,{variant:"outline",disabled:i,onClick:e.flagSelectedForReview,icon:o.jsx(l0,{}),children:["Flag ",t.size," to review"]}),o.jsx(QHt,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:i}),o.jsx(ie,{icon:o.jsx(qt,{}),variant:"ghost",onClick:e.clearSelection,children:"Clear"})]})}function mGt(e){const{data:t}=Fy(e.id,e.status);return g.useMemo(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];const n=new Set;for(const r of Object.values(t))for(const s of r)n.add(s.scorerId);return[...n].sort()},[e.scorerIds,t])}function rle({icon:e,typeLabel:t,subject:n,description:r,isLast:s=!1}){return o.jsxs("li",{className:"relative grid grid-cols-[auto_1fr] gap-x-2.5 pb-4 last:pb-0",children:[o.jsxs("div",{className:"flex flex-col items-center",children:[o.jsxs(gn,{children:[o.jsx(hn,{render:o.jsx("span",{className:"text-neutral3 flex size-5 shrink-0 items-center justify-center [&_svg]:size-3.5",role:"img","aria-label":t}),children:e}),o.jsx(pn,{children:t})]}),!s&&o.jsx("span",{"aria-hidden":!0,className:"bg-border1 mt-1 w-px flex-1"})]}),o.jsxs("div",{className:"grid min-w-0 gap-0.5",children:[o.jsx("div",{className:"text-ui-sm text-neutral5 flex min-h-5 items-center",children:n}),o.jsx("p",{className:"text-ui-xs text-neutral2",children:r})]})]})}const sle="text-neutral5 inline-flex min-w-0 items-center gap-1.5 hover:underline";function aks({experiment:e,className:t}){const{Link:n,paths:r}=ln(),s=aGt(),{scorers:a}=s,{data:i,isLoading:l}=tv(e.datasetId??""),c=mGt(e),u=e.targetType,d=e.targetId,f=lGt(e,s),h=(()=>{if(!d)return null;switch(u){case"agent":return r.agentLink(d);case"workflow":return r.workflowLink(d);case"scorer":return r.scorerLink(d);default:return null}})(),p=u&&iGt[u]||Pi,m=u&&oGt[u]||"Evaluation target";return o.jsxs("ol",{className:K("grid",t),children:[o.jsx(rle,{icon:o.jsx(eK,{}),typeLabel:"Dataset",description:`Each item will be passed to the ${m.toLowerCase()}`,subject:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:sle,children:[o.jsx("span",{className:"truncate",children:l?o.jsx(Et,{className:"h-4 w-28"}):i?.name??e.datasetId}),e.datasetVersion!=null&&o.jsxs("span",{className:"text-neutral3 shrink-0",children:["(v",e.datasetVersion,")"]})]}):o.jsx("span",{className:"text-neutral3",children:"No dataset"})}),o.jsx(rle,{icon:o.jsx(p,{}),typeLabel:m,description:"Its output is then scored",subject:h?o.jsx(n,{href:h,className:sle,children:o.jsx("span",{className:"truncate",children:f})}):o.jsx("span",{className:"text-neutral3 truncate",children:f})}),o.jsx(rle,{icon:o.jsx(D0,{}),typeLabel:"Scorers",description:"It gives a score by comparing ground truth",isLast:!0,subject:c.length===0?o.jsx("span",{className:"text-neutral3",children:"No scorer has produced a score yet"}):o.jsx("ul",{className:"grid min-w-0 gap-0.5",children:c.map(v=>{const y=a?.[v]?.scorer?.config?.name??v;return o.jsx("li",{className:"min-w-0",children:o.jsx(n,{href:r.scorerLink(v),className:sle,children:o.jsx("span",{className:"truncate",children:y})})},v)})})})]})}function lT({label:e,children:t}){return o.jsxs(o.Fragment,{children:[o.jsx(Bn.Key,{children:e}),o.jsx(Bn.Value,{className:"flex flex-wrap items-baseline justify-end gap-x-1.5 text-right",children:t})]})}function Mrt(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1).replace(/\.0$/,"")}s`;const t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);if(t<60)return n>0?`${t}m ${n}s`:`${t}m`;const r=Math.floor(t/60),s=t%60;return s>0?`${r}h ${s}m`:`${r}h`}function iks({experiment:e,metrics:t}){const{data:n}=Fy(e.id,e.status),r=e.status==="running"||e.status==="pending",s=g.useMemo(()=>{if(!n)return;const c=Object.values(n).flat();if(c.length!==0)return c.reduce((u,d)=>u+d.score,0)/c.length},[n]),a=e.startedAt??e.createdAt,i=a?new Date(a):null,l=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const c=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return c<0?"—":Mrt(c)})();return o.jsxs(Bn,{children:[o.jsx(lT,{label:"Avg score",children:s===void 0?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:s.toFixed(3)}),r&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(lT,{label:"Items",children:r?o.jsxs("span",{className:"text-neutral3",children:[(e.succeededCount??0)+(e.failedCount??0),"/",e.totalItems," items processed"]}):o.jsxs(o.Fragment,{children:[o.jsxs("span",{children:[e.totalItems," item",e.totalItems===1?"":"s"]}),(e.failedCount??0)>0&&o.jsxs("span",{className:"text-error",children:["· ",e.failedCount," errored"]})]})}),o.jsx(lT,{label:"Started",children:i?o.jsx("span",{title:e4n(i,{addSuffix:!0}),children:xr(i,"MMM d, h:mm a")}):o.jsx("span",{children:"—"})}),o.jsx(lT,{label:"Duration",children:o.jsx("span",{children:l})}),t?.isEnabled&&o.jsxs(o.Fragment,{children:[o.jsx(lT,{label:"Tokens",children:t.data?.totalTokens==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:ao(t.data.totalTokens)}),t.data.estimatedCost!=null&&o.jsxs("span",{className:"text-neutral3",children:["· ",Ud(t.data.estimatedCost,t.data.costUnit)]}),r&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(lT,{label:"Latency (avg)",children:t.data?.avgAgentDurationMs==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsx("span",{children:Mrt(Math.round(t.data.avgAgentDurationMs))})})]})]})}function oks({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=ln(),{data:s}=tf(),a=g.useMemo(()=>{if(!e)return[];const i={};for(const l of Object.values(e))for(const c of l)i[c.scorerId]||(i[c.scorerId]={sum:0,count:0}),i[c.scorerId].sum+=c.score,i[c.scorerId].count++;return Object.entries(i).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(a.length===0){const i=t==="running"||t==="pending",l=e!==void 0;let c,u;return i?(c="Experiment in progress",u="Summary metrics will appear here once the experiment completes."):l?(c="No scorers configured",u="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(c="Loading scores",u="Fetching scorer results…"),o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-2",children:[o.jsx(Uy,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"text-neutral4",children:c}),o.jsx("span",{className:"truncate",children:u})]})}return o.jsx("div",{className:"flex flex-col gap-2",children:a.map(({scorerId:i,avg:l})=>{const c=s?.[i]?.scorer?.config?.name??i;return o.jsxs(Jr,{className:"min-w-0 p-3",children:[o.jsxs(n,{href:r.scorerLink(i),className:"text-ui-sm text-neutral3 [&>svg]:text-neutral3 flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3 [&>svg]:shrink-0",children:[o.jsxs(gn,{children:[o.jsx(hn,{render:o.jsx(D0,{role:"img","aria-label":"Scorer"})}),o.jsx(pn,{children:"Scorer"})]}),o.jsx("span",{className:"truncate",children:c})]}),o.jsxs("strong",{className:"text-ui-md text-neutral4 font-semibold",children:[l.toFixed(3),o.jsx("span",{className:"text-ui-sm text-neutral3 ml-1.5 font-normal",children:"avg score"})]})]},i)})})}function ale({title:e,children:t}){return o.jsxs("section",{className:"grid gap-3",children:[o.jsx("h2",{className:"text-ui-md text-neutral2 tracking-widest uppercase",children:e}),t]})}function lks({experiment:e,metrics:t,className:n}){const{Link:r,paths:s}=ln(),{data:a}=Fy(e.id,e.status),i=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${s.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsxs(Uf,{as:"aside","aria-label":"Experiment details",className:K("grid content-start gap-5 p-5",n),children:[o.jsxs(ale,{title:"Pipeline",children:[o.jsx(aks,{experiment:e}),e.agentVersion&&o.jsxs(Bn,{children:[o.jsx(Bn.Key,{children:"Version"}),i?o.jsx(Bn.ValueLink,{href:i,as:r,children:e.agentVersion}):o.jsx(Bn.Value,{children:e.agentVersion})]})]}),o.jsx(ale,{title:"Run",children:o.jsx(iks,{experiment:e,metrics:t})}),o.jsx(ale,{title:"Scorers",children:o.jsx(oks,{scoresByItemId:a,experimentStatus:e.status})})]})}function cks({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[a,i]=g.useState(e.description??""),{updateExperiment:l}=za(),c=!!r.trim()&&!l.isPending,u=async d=>{if(d.preventDefault(),!(!c||!e.datasetId))try{await l.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:a.trim()}),Be.success("Experiment renamed"),n(!1)}catch(f){Be.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return o.jsx(vr,{open:t,onOpenChange:n,children:o.jsxs(yr,{className:"max-w-md",children:[o.jsx(br,{children:o.jsx(hr,{children:"Rename Experiment"})}),o.jsx(Mr,{children:o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"rename-experiment-name",children:"Name *"}),o.jsx(In,{id:"rename-experiment-name",value:r,onChange:d=>s(d.target.value),placeholder:"Enter experiment name",autoFocus:!0})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"rename-experiment-description",children:"Description"}),o.jsx(In,{id:"rename-experiment-description",value:a,onChange:d=>i(d.target.value),placeholder:"Enter experiment description (optional)"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ie,{icon:o.jsx(qt,{}),type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(ie,{icon:o.jsx(Fn,{}),type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}const uks=["agent","workflow","scorer"];function dks({experiment:e}){const[t,n]=g.useState(!1),r=zr(),{paths:s}=ln(),a=mGt(e),i=uks.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsx(ie,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",icon:o.jsx(oc,{}),children:"Rerun"}),t&&o.jsx(nK,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:i,initialTargetId:e.targetId,initialScorerIds:a,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:l=>{r(s.experimentLink(l))}},a.join(","))]})}function fks({experiment:e,onDeleteClick:t,children:n}){const{Link:r}=ln(),[s,a]=g.useState(!1),i=!!e.datasetId,l=i||!!t;return o.jsxs(Bt.TopArea,{children:[o.jsxs(Bt.Row,{className:"items-center justify-start gap-2",children:[o.jsxs(Wr,{className:"whitespace-nowrap",children:[o.jsx(dks,{experiment:e}),o.jsx(ie,{as:r,to:$3t(e.id),icon:o.jsx(l0,{}),children:"Review queue"}),l&&o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{size:"lg","aria-label":"Experiment actions menu",children:o.jsx(d1,{})})}),o.jsxs(ot.Content,{align:"start",className:"w-48",children:[i&&o.jsxs(ot.Item,{onSelect:()=>a(!0),children:[o.jsx(Yu,{})," Rename Experiment"]}),t&&o.jsxs(ot.Item,{onSelect:t,className:"text-red-500 focus:text-red-400",children:[o.jsx(yi,{})," Delete Experiment"]})]})]})]}),n]}),s&&o.jsx(cks,{experiment:e,open:!0,onOpenChange:a})]})}const hks=({experimentId:e,experimentStatus:t})=>{const n=Ge(),{supportsMetrics:r}=NY(),s=!!e&&r,i=mt({queryKey:["experiment-metrics",e],enabled:s,refetchInterval:t==="running"||t==="pending"?2e3:!1,queryFn:async()=>{if(!e)throw new Error("experimentId is required");const l={experimentId:e},[c,u,d]=await Promise.all([n.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"avg",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:l})]);return{totalTokens:c.value??null,estimatedCost:c.estimatedCost??null,costUnit:c.costUnit??null,avgAgentDurationMs:u.value??null,agentRuns:d.value??null}}});return{data:i.data,isLoading:i.isLoading,isEnabled:s}};function pks({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=za();return{addTag:g.useCallback(async(i,l)=>{const c=l.filter(d=>!(d.tags??[]).includes(i));if(n||c.length===0)return;r(!0);let u=0;try{u=(await Promise.allSettled(c.map(f=>s.mutateAsync({datasetId:e,experimentId:t,resultId:f.id,tags:[...f.tags??[],i]})))).filter(f=>f.status==="fulfilled").length}finally{r(!1)}u>0?Be(`Tag "${i}" added to ${u} result${u>1?"s":""}`):Be.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function gGt(e,t){const{data:n}=tv(e);return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}function mks({datasetId:e,experimentId:t,results:n}){const[r,s]=g.useState(new Set),[a,i]=g.useState(!1),{updateExperimentResult:l}=za(),{addTag:c,isPending:u}=pks({datasetId:e,experimentId:t}),d=gGt(e,n),f=g.useMemo(()=>n.filter(y=>r.has(y.id)),[n,r]),h=g.useCallback(y=>{s(b=>{const x=new Set(b);return x.has(y)?x.delete(y):x.add(y),x})},[]),p=g.useCallback(()=>s(new Set),[]),m=g.useCallback(async()=>{if(a||r.size===0)return;i(!0);const y=new Set;try{for(const b of r)try{await l.mutateAsync({datasetId:e,experimentId:t,resultId:b,status:"needs-review"}),y.add(b)}catch{}}finally{i(!1)}y.size>0&&(s(b=>{const x=new Set(b);for(const w of y)x.delete(w);return x}),Be(`${y.size} result${y.size>1?"s":""} flagged for review`))},[e,t,a,r,l]),v=g.useCallback(y=>c(y,f),[c,f]);return{selectedIds:r,selectedResults:f,toggleSelect:h,clearSelection:p,flagSelectedForReview:m,isFlagging:a,addTagToSelected:v,isTagging:u,tagVocabulary:d}}const gks=[];function B8({children:e}){return o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:e})]})}function vks(){const{experimentId:e}=tr(),t=zr(),[n,r]=g.useState(!1),{data:s,isLoading:a}=RW(),l=s?.experiments?.find(w=>w.id===e)?.datasetId??"",{data:c,isLoading:u,error:d}=w3(l,e??""),{data:f,isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v}=S3({datasetId:l,experimentId:e??"",experimentStatus:c?.status}),y=hks({experimentId:e,experimentStatus:c?.status}),b=mks({datasetId:l,experimentId:e??"",results:f??gks});if(!e||a||u)return null;if(d&&ms(d))return o.jsx(B8,{children:o.jsx(zs,{})});if(d&&gs(d))return o.jsx(B8,{children:o.jsx(Ts,{resource:"datasets"})});const x=o.jsx(B8,{children:o.jsx(mr,{iconSlot:o.jsx(Bwe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsx(ie,{as:xo,to:"/experiments",icon:o.jsx(Lc,{}),children:"Back to Experiments"})})});return d&&R1(d)?x:d?o.jsx(B8,{children:o.jsx(Fs,{title:"Failed to load experiment",message:d instanceof Error?d.message:"An unexpected error occurred. Please try again."})}):!l||!c?x:o.jsx(DSs,{experimentId:e,datasetId:l,experimentStatus:c.status,results:f??[],isLoadingResults:h,hasNextPage:v,children:o.jsxs("div",{className:"h-full",children:[o.jsxs(Bt,{height:"full",children:[o.jsx(fks,{experiment:c,onDeleteClick:()=>r(!0),children:o.jsx(sks,{selection:b})}),o.jsxs(Bt.MainArea,{className:"grid grid-cols-[1fr_auto] gap-4 overflow-visible",children:[o.jsx(LSs,{experimentId:e,experimentStatus:c.status,results:f??[],isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v,selectedIds:b.selectedIds,onToggleSelect:b.toggleSelect}),o.jsx(lks,{experiment:c,metrics:y,className:"w-80 overflow-y-auto"})]})]}),o.jsx(qg,{}),o.jsx(rGt,{open:n,onOpenChange:r,experimentId:e,experimentName:c.name??void 0,onSuccess:()=>t("/experiments")})]})})}function yks(){const{itemId:e}=tr();return e?o.jsx(bks,{itemId:e},e):null}function bks({itemId:e}){const{experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:a,hasNextPage:i,close:l,goToPreviousItem:c,goToNextItem:u}=tGt(),d=g.useMemo(()=>s.find(w=>w.itemId===e)??null,[s,e]),{data:f}=Fy(t,r),{updateExperimentResult:h}=za(),p=g.useCallback(async w=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,status:"needs-review"}),Be("Result flagged for review")}catch{Be.error("Failed to flag result for review")}},[n,t,h]),m=gGt(n,s),v=g.useCallback(async(w,k)=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,tags:k})}catch{Be.error("Failed to update tags")}},[n,t,h]),y=g.useCallback(async w=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,status:"complete"}),Be("Result marked as reviewed")}catch{Be.error("Failed to complete result")}},[n,t,h]),b=d?f?.[d.itemId]:void 0,x=KHt(b);return o.jsx(rK,{label:`Experiment item ${e}`,wide:x.wide,children:d?o.jsx(CPe,{className:"p-3",result:d,scores:b,state:x,onPrevious:c,onNext:u,onClose:l,onComplete:()=>y(d.id),onFlagForReview:()=>{p(d.id)},onTagsChange:w=>{v(d.id,w)},tagVocabulary:m,isUpdatingTags:h.isPending}):a||i?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Zt,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(mr,{iconSlot:o.jsx(Bwe,{}),titleSlot:"Item not found",descriptionSlot:`No loaded result for item "${e}".`,actionSlot:o.jsx(ie,{icon:o.jsx(qt,{}),onClick:l,children:"Close"})})})})})}const WPe=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 9.83952 9.3295",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.67171 0.838331H6.70163V4.05307L9.68767 8.09999C10.0634 8.6093 9.69869 9.32932 9.06643 9.3295H0.772551C0.140289 9.3293 -0.223777 8.60929 0.151995 8.09999L3.13804 4.05307V0.838331H2.17136V0H7.67171V0.838331ZM3.97705 4.32955L3.89513 4.44015L2.34681 6.53802H7.49285L5.94453 4.44015L5.86261 4.32955V0.860859H3.97705V4.32955Z",fill:"currentColor"})}),mH="all",Drt=60,xks=e=>e.length>Drt?`${e.slice(0,Drt)}…`:e;function wks({value:e,onValueChange:t,className:n,variant:r,allOption:s,targetType:a,targetId:i}){const{data:l,isLoading:c,isError:u}=HPe(void 0,{targetType:a,targetId:i}),d=(l?.experiments??[]).map(h=>({label:sGt(h),value:h.id,start:o.jsx(WPe,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:h.description?xks(h.description):A0(h.id)??h.id})),f=s?[{label:"All experiments",value:mH},...d]:d;return o.jsx(Co,{options:f,value:e??(s?mH:""),onValueChange:t,placeholder:c?"Loading experiments...":u?"Failed to load experiments":"Select experiment",searchPlaceholder:"Search experiments...",emptyText:"No experiments found.",className:n,disabled:c||u,variant:r})}function Sks(){const[e,t]=da(),n=e.get("experiment"),r=e.get("review"),{targetType:s,targetId:a,setTargetType:i,setTargetId:l}=VPe({resetParams:["experiment","review"]}),{Link:c,paths:u}=ln(),{data:d,error:f}=HPe(void 0,{targetType:s,targetId:a}),h=d?.experiments.find(m=>m.id===n),p=m=>{t(v=>{const y=new URLSearchParams(v);return m===mH?y.delete("experiment"):y.set("experiment",m),y.delete("review"),y},{replace:!0})};return f&&ms(f)?o.jsx(Qn,{children:o.jsx(zs,{})}):f&&gs(f)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"experiments"})}):f?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load experiments",message:f.message})}):o.jsx(Bt,{height:"full",children:o.jsx(G1s,{datasetId:h?.datasetId??void 0,experimentId:n??void 0,targetType:s,targetId:a,featuredItemId:r,detailPanelVariant:"overlay",toolbarStart:o.jsxs(o.Fragment,{children:[o.jsx(BPe,{targetType:s,targetId:a,onTargetTypeChange:i,onTargetIdChange:l}),o.jsx(wks,{allOption:!0,value:n??void 0,onValueChange:p,targetType:s,targetId:a,className:"w-72"})]}),toolbarEnd:n?o.jsx(ie,{as:c,href:u.experimentLink(n),icon:o.jsx(Idt,{}),children:"See experiment"}):void 0},`${s}:${a}:${n??mH}`)})}const vGt=[{name:"itemId",label:"Item ID",size:"auto"},{name:"status",label:"Status",size:"auto"},{name:"input",label:"Input",size:"minmax(0,1fr)"},{name:"tags",label:"Tags",size:"auto"}],kks=vGt.map(e=>e.size).join(" ");function Oks({items:e,isLoading:t,error:n}){const r=zr(),[s,a]=g.useState(""),i=s.trim().toLowerCase(),l=i?e.filter(c=>[c.itemId,c.experimentId,c.datasetId,c.traceId??""].some(u=>u.toLowerCase().includes(i))):e;return t?o.jsx(Uo,{columns:kks}):n?o.jsx(Fs,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(mr,{iconSlot:o.jsx(Os,{className:"text-neutral3 h-8 w-8"}),titleSlot:"Nothing to review",descriptionSlot:"Experiment results that need review will show up here."}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(qc,{onSearch:a,label:"Filter dataset items",placeholder:"Filter by item, experiment, dataset or trace",shortcutDisabled:!0})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsx(KY,{results:l,isLoading:!1,featuredResultId:null,onResultClick:c=>{const u=l.find(d=>d.id===c);u&&r($3t(u.experimentId,u.id))},columns:vGt,emptyMessage:"No dataset items match your search"})})]})}function Cks(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"Your inbox is empty",descriptionSlot:o.jsxs(o.Fragment,{children:["Feedback left on traces and experiment results flagged for review ",o.jsx("br",{}),"will show up here until you mark them reviewed."]}),actionSlot:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ie,{icon:o.jsx(WPe,{}),as:xo,to:"/experiments",variant:"outline",children:"Go to experiments"}),o.jsx(ie,{icon:o.jsx(__,{}),as:xo,to:"/traces",variant:"outline",children:"Go to traces"})]})})})}function Cwe(e){return e.comment?e.comment:typeof e.value=="string"?e.value:e.feedbackType==="thumbs"?e.value===1?"Thumbs up":"Thumbs down":JSON.stringify(e.value)??String(e.value)}const Lrt="minmax(0, 2fr) minmax(0, 1fr) auto minmax(0, 1fr) auto auto",_ks=e=>e.stopPropagation();function Eks({items:e,isLoading:t,error:n,hasNextPage:r,isFetchingNextPage:s,fetchNextPage:a,onMarkReviewed:i,pendingFeedbackId:l,onSelect:c,selectedFeedbackId:u}){const[d,f]=g.useState(""),h=d.trim().toLowerCase(),p=h?e.filter(x=>Cwe(x).toLowerCase().includes(h)||(oH(x)??"").toLowerCase().includes(h)||(x.traceId??"").toLowerCase().includes(h)||(x.feedbackSource??"").toLowerCase().includes(h)):e,{containerRef:m,getRowProps:v}=ll({count:p.length,global:!0}),{inView:y,setRef:b}=Yy({root:m});return g.useEffect(()=>{y&&r&&!s&&a()},[y,r,s,a]),t?o.jsx(Uo,{columns:Lrt}):n?o.jsx(Fs,{title:"Failed to load feedback",message:n.message}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(qc,{onSearch:f,label:"Filter feedback",placeholder:"Filter loaded feedback by text, author, trace or source"})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(be,{columns:Lrt,fit:"container",scrollRef:m,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Feedback"}),o.jsx(be.TopCell,{children:"Author"}),o.jsx(be.TopCell,{children:"Source"}),o.jsx(be.TopCell,{children:"Trace"}),o.jsx(be.TopCell,{children:"Date"}),o.jsx(be.TopCell,{children:" "})]}),p.length===0?o.jsx(be.NoMatch,{message:h?"No feedback matches your search":"No feedback needs review"}):p.map((x,w)=>{const k=x.feedbackId,O=oH(x);return o.jsxs(be.RowWrapper,{...v(w),onSelectRow:x.traceId?()=>c(x):void 0,children:[o.jsxs(be.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,tabIndex:-1,onClick:_=>{_.stopPropagation(),c(x)},children:[o.jsx(be.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:Cwe(x)})}),o.jsx(be.Cell,{className:"flex gap-2",children:O&&o.jsxs(o.Fragment,{children:[o.jsx(Ly,{name:O,src:x.author?.avatarUrl,size:"sm"}),o.jsx("span",{className:"truncate",children:O})]})}),o.jsx(be.Cell,{children:o.jsx(xt,{size:"sm",children:x.feedbackSource})}),o.jsx(be.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(be.TextCell,{children:xr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(be.ActionsCell,{className:"pl-2",onClick:_ks,children:k?o.jsx(ie,{icon:o.jsx(l0,{}),variant:"ghost",size:"sm",onClick:()=>i(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(be.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function Tks({feedback:e,traceId:t,initialSpanId:n,onClose:r,onPrevious:s,onNext:a,onMarkReviewed:i,isMarkingReviewed:l}){const[c,u]=g.useState(n),{spans:d,isLoading:f}=MZt({traceId:t,anchorSpanId:null,listMode:"traces"}),h=oH(e)??e.feedbackUserId;return o.jsx(rK,{label:`Review feedback for trace ${t}`,wide:!!c,children:o.jsxs("div",{className:"[&>*]:bg-surface3 grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-4 p-3 [&>*]:rounded-lg [&>*]:shadow-lg",children:[o.jsxs(bn,{className:"max-h-[33vh]",children:[o.jsxs(bn.Header,{className:"items-start",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(bn.Heading,{children:"Feedback"}),o.jsx(xt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(xt,{variant:"neutral",emphasis:"muted",children:e.feedbackSource})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[h&&o.jsxs(o.Fragment,{children:[o.jsx(Ly,{name:h,src:e.author?.avatarUrl,size:"sm"}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral5 truncate",children:h}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3",children:"·"})]}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3",children:xr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss")})]})]}),o.jsx(Wr,{className:"ml-auto shrink-0",children:o.jsx(ie,{variant:"primary",size:"sm",onClick:i,disabled:l,icon:o.jsx(Fn,{}),children:"Mark as reviewed"})})]}),o.jsx(bn.Content,{children:o.jsx(ge,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:Cwe(e)})})]}),o.jsx("section",{className:"min-h-0 overflow-hidden",children:o.jsx(OPe,{className:"h-full rounded-none border-0 bg-transparent",spanPanelClassName:"rounded-none border-0 bg-transparent",traceId:t,spans:d,isLoadingSpans:f,selectedSpanId:c??null,initialSpanId:n,onSpanSelect:u,onClose:r,onPrevious:s,onNext:a,traceHref:`/traces?traceId=${encodeURIComponent(t)}`,feedbackTabSlot:({traceId:p})=>o.jsx(k3,{traceId:p}),spanFeedbackTabSlot:({traceId:p,spanId:m})=>p&&m?o.jsx(dPe,{traceId:p,spanId:m},`${p}:${m}`):null})})]})})}const yGt=100;async function jks(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:yGt});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function Nks(e,t,n){const r=[];let s=0,a=!0;for(;a;){const i=await e.listDatasetExperimentResults(t,n,{page:s,perPage:yGt});r.push(...i.results),a=i.pagination.hasMore,s+=1}return r}function Iks(){const e=Ge();return mt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await jks(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await Nks(e,s,r.id)).filter(i=>i.status==="needs-review").map(i=>({id:i.id,datasetId:s,experimentId:r.id,itemId:i.itemId,traceId:i.traceId??void 0,input:i.input,output:i.output,error:i.error,status:i.status,tags:i.tags})):[]}))).flat()},refetchInterval:3e3,refetchOnWindowFocus:!1})}function Aks({enabled:e}){const t=Ge();return mt({queryKey:["inbox-dataset-review-count"],queryFn:async()=>{const{counts:n}=await t.getExperimentReviewSummary();return n.reduce((r,s)=>r+s.needsReview,0)},enabled:e,refetchInterval:3e3})}function Rks(e){return e==="dataset"||e==="feedback"}function Pks(){const[e,t]=da(),n=e.get("tab"),r=Rks(n)?n:"feedback",s=pgs({reviewStatus:"needs-review"}),a=uPe(),i=Iks(),l=i.data??[],c=s.total??0,u=!s.isLoading&&!i.isLoading&&!s.error&&!i.error&&s.items.length===0&&l.length===0,d=e.get("feedbackId")??void 0,f=e.get("traceId")??void 0,h=e.get("spanId")??void 0,p=T=>{t(E=>{const N=new URLSearchParams(E);for(const I of["feedbackId","traceId","spanId"]){const A=T[I];A?N.set(I,A):N.delete(I)}return N},{replace:!0})},m=()=>p({}),v=T=>p({feedbackId:T.feedbackId??void 0,traceId:T.traceId??void 0,spanId:T.spanId??void 0}),y=s.items.findIndex(T=>T.feedbackId===d),b=y>=0?s.items[y]:void 0,x=y>0?s.items[y-1]:void 0,w=y>=0&&y<s.items.length-1?s.items[y+1]:void 0,k=!!f&&!!d,O=T=>{a.mutate({feedbackId:T,reviewStatus:"reviewed"},{onSuccess:()=>T===d&&m()})},_=T=>{t(E=>{const N=new URLSearchParams(E);return N.set("tab",T),N},{replace:!0})};return o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsx(Bt,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsx(Bt.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(Cks,{}):o.jsxs(kl,{defaultTab:"feedback",value:r,onValueChange:_,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(Sl,{variant:"pill-ghost",children:[o.jsxs(kr,{value:"feedback",children:[o.jsx(st,{size:"sm",children:o.jsx(R3,{})}),o.jsx(ge,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(xt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(kr,{value:"dataset",children:[o.jsx(st,{size:"sm",children:o.jsx(l0,{})}),o.jsx(ge,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(xt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(Hr,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(Eks,{items:s.items,isLoading:s.isLoading,error:s.error??void 0,hasNextPage:s.hasNextPage,isFetchingNextPage:s.isFetchingNextPage,fetchNextPage:s.fetchNextPage,onMarkReviewed:O,pendingFeedbackId:a.isPending?a.variables?.feedbackId:void 0,onSelect:v,selectedFeedbackId:d})}),o.jsx(Hr,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(Oks,{items:l,isLoading:i.isLoading,error:i.error??void 0})})]})})}),k&&f&&b&&o.jsx(Tks,{feedback:b,traceId:f,initialSpanId:h,onClose:m,onPrevious:x?()=>v(x):void 0,onNext:w?()=>v(w):void 0,onMarkReviewed:()=>d&&O(d),isMarkingReviewed:a.isPending},`${d}:${f}`)]})}function $ks({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsxs("li",{className:"flex items-center justify-between border-b py-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"font-mono text-ui-sm",children:e.connectionId}),o.jsxs("div",{className:"text-ui-sm text-gray-500",children:[e.label??"(no label)"," · ",e.status,e.scope?` · ${e.scope}`:"",t&&e.authorId?` · author: ${e.authorId}`:""]})]}),o.jsx("button",{type:"button",className:"text-red-600 underline disabled:opacity-50",onClick:r,disabled:n,children:"Disconnect"})]})}function bGt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx($ks,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Mks({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("div",{className:"space-y-4",children:e.map(([s,a])=>o.jsxs("div",{children:[o.jsx("h3",{className:"text-ui-md font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(bGt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function Dks({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:a,error:i,disconnectPending:l,disconnectError:c,onDisconnect:u}){return o.jsxs("div",{className:"space-y-2 border rounded p-4",children:[o.jsx("h2",{className:"text-header-sm font-semibold",children:"Existing connections"}),!e||!t?o.jsx("p",{className:"text-gray-500",children:"Pick a provider and toolkit to list connections."}):a?o.jsx("p",{className:"text-gray-500",children:"Loading…"}):i?o.jsx("p",{className:"text-red-600",children:String(i)}):n.length===0?o.jsx("p",{className:"text-gray-500",children:"No connections."}):r?o.jsx(Mks,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(bGt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Lks({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:a,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:h,onToolkitChange:p,onLabelChange:m,onConnect:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>h(y.target.value),disabled:a,children:[o.jsx("option",{value:"",children:"— select provider —"}),e.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName??y.name," (",y.id,")"]},y.id))]}),a&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),i?o.jsx("span",{className:"text-red-600",children:String(i)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>p(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const Frt=e=>e.authorId?.trim()||"shared",Fks=(e,t)=>{if(!t||new Set(e.map(Frt)).size<=1)return null;const r=new Map;for(const a of e){const i=Frt(a);r.set(i,[...r.get(i)??[],a])}const s=Array.from(r.entries());return s.sort(([a],[i])=>a==="shared"?1:i==="shared"?-1:a.localeCompare(i)),s},zks=["*","tool-providers:*","tool-providers:admin"];function Bks(){const{data:e}=zm();return e?.permissions?.some(t=>zks.includes(t))??!1}function Uks(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=CA(),l=aQ(e||null),c=k5t(e||null,n||null),u=S5t(),d=b5t(),f=Bks(),h=i.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>Fks(m,f),[m,f]),y=w=>{t(w),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{a(""),c.refetch()}})},x=w=>{d.mutate({providerId:e,connectionId:w})};return o.jsxs("div",{className:"p-4 max-w-3xl space-y-6 text-ui-md",children:[o.jsx("h1",{className:"text-header-md font-semibold",children:"Integrations"}),o.jsx("p",{className:"text-gray-500",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),o.jsx(Lks,{providers:h,toolkits:p,providerId:e,toolkit:n,label:s,providersLoading:i.isLoading,providersError:i.error,toolkitsLoading:l.isLoading,toolkitsError:l.error,authorizePending:u.isPending,authorizeError:u.error,authorizedConnection:u.data,onProviderChange:y,onToolkitChange:r,onLabelChange:a,onConnect:b}),o.jsx(Dks,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})}function qks({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsxs("div",{className:"w-full max-w-sm space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[o.jsx(um,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-header-md font-semibold",children:e})]}),t,n,r]})})}function xGt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=fc(),{mutate:i,isPending:l,error:c}=X4r(),{mutate:u,isPending:d,error:f}=e5r(),{mutate:h,isPending:p}=mLt(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,O]=g.useState("");if(a)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:_}=s,T=_.type==="sso"||_.type==="both",E=_.type==="credentials"||_.type==="both",N=_.sso,I=_.signUpEnabled!==!1,A=m==="signin"||!I,$=A?l:d,z=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=cQ("/")},q=L=>{L.preventDefault(),A?i({email:x,password:k},{onSuccess:D}):u({email:x,password:k,name:y||void 0},{onSuccess:D})},H=()=>{h({redirectUri:e},{onSuccess:L=>{window.location.href=L.url}})},V=()=>{v(A?"signup":"signin")},B=_.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(qd,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-ui-md",children:_.description})]}):null,W=r?o.jsx("div",{className:"text-ui-md rounded-md bg-red-500/10 p-3 text-red-400",children:r}):null;return o.jsxs(qks,{title:A?"Sign in to Mastra Studio":"Create your account",description:B,errorBanner:W,children:[E&&o.jsxs("form",{onSubmit:q,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"text-neutral4 text-ui-md block",children:"Name"}),o.jsx(In,{id:"name",type:"text",value:y,onChange:L=>b(L.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"email",className:"text-neutral4 text-ui-md block",children:"Email"}),o.jsx(In,{id:"email",type:"email",value:x,onChange:L=>w(L.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"password",className:"text-neutral4 text-ui-md block",children:"Password"}),o.jsx(In,{id:"password",type:"password",value:k,onChange:L=>O(L.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),z&&o.jsx("div",{className:"text-ui-md rounded-md bg-red-500/10 p-3 text-red-400",children:z.message}),o.jsx(ie,{icon:o.jsx(E7,{}),type:"submit",disabled:$,className:"w-full",size:"lg",children:$?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-ui-md text-center",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:V,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),T&&E&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"border-border1 w-full border-t"})}),o.jsx("div",{className:"text-ui-md relative flex justify-center",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),T&&N&&o.jsxs(ie,{onClick:H,disabled:p,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),p?"Redirecting...":N.text||"Sign in"]})]})}function Vks(){const[e]=da(),t=zr(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",a=e.get("error_description")||e.get("error")||null,i=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(xGt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const wh=ja.KeyValueList;function Hks(e){return e instanceof Date?e:new Date(e)}function Wks({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,h=Hks(e.timestamp),p=e.traceId,m=e.spanId;return o.jsxs(ja,{collapsed:d,children:[o.jsxs(ja.Header,{children:[o.jsxs(ja.Heading,{children:["Log ",o.jsx("b",{children:xr(h,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Wr,{className:"ml-auto shrink-0",children:[l&&o.jsx(ie,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(T3,{}):o.jsx(vH,{})}),o.jsxs(Wr,{spacing:"close",children:[o.jsx(ie,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(o0,{})}),o.jsx(ie,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(E3,{})})]}),o.jsx(ja.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(ja.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(p||m)&&o.jsxs("div",{className:K("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[p&&o.jsxs(Wr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ie,{size:"md",className:"min-w-0 flex-1 overflow-hidden",icon:o.jsx(Df,{}),onClick:()=>n?.(p),children:[o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",p]})]}),o.jsx(Pa,{content:p,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Wr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ie,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!p||!r,onClick:()=>p&&r?.(p,m),icon:o.jsx(Df,{}),children:[o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(Pa,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(wh,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(wh.Key,{children:"Entity Type"}),o.jsx(wh.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(wh.Key,{children:"Entity Name"}),o.jsx(wh.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(wh.Key,{children:"Service"}),o.jsx(wh.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(wh.Key,{children:"Environment"}),o.jsx(wh.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(wh.Key,{children:"Source"}),o.jsx(wh.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(wh.Key,{children:v}),o.jsx(wh.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(ja.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function Zks({error:e,resource:t,errorTitle:n}){if(ms(e))return o.jsx(zs,{});if(gs(e))return o.jsx(Ts,{resource:t});if(x4(e))return o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(b4(e,"logs"))return o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(Fs,{title:n,message:r??"Unknown error"})}function Gks({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:K("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:K("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const Qks={debug:{label:"DEBUG",color:"#71717a"},info:{label:"INFO",color:"#60a5fa"},warn:{label:"WARN",color:"#facc15"},error:{label:"ERROR",color:"#f87171"},fatal:{label:"FATAL",color:"#dc2626"}};function Yks({level:e}){const t=Qks[e];return o.jsx(co,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Kks({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Pi,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(hc,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Xd,{className:n,"aria-hidden":!0});default:return null}}function Xks({entityType:e,entityName:t}){const n=e??"";return o.jsxs(co,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(Kks,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function Jks({message:e}){return o.jsx(co,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function eOs({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(co,{children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return o.jsx(xje,{font:"mono",children:t})}const Jl=Object.assign(g4,{Top:y4,TopCell:C0,TopCellWithTooltip:WG,TopCellSmart:Z2t,RowWrapper:Oje,RowButton:v4,RowLink:kje,Spacer:Cje,NoMatch:HG,DateCell:V2t,TimeCell:H2t,LevelCell:Yks,EntityCell:Xks,MessageCell:Jks,DataCell:eOs,NextPageLoading:VG}),zrt="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",tOs=36,nOs=8;function rOs({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=$Zt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>tOs,overscan:nOs}),{getRowProps:d}=ll({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y),global:!0}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Uo,{columns:zrt});const h=u.getVirtualItems(),p=u.getTotalSize(),m=h[0]?.start??0,v=h.length>0?Math.max(0,p-(h[h.length-1]?.end??0)):0;return o.jsxs(Jl,{columns:zrt,scrollRef:c,className:"min-w-0",children:[o.jsxs(Jl.Top,{children:[o.jsx(Jl.TopCell,{children:"Date"}),o.jsx(Jl.TopCell,{children:"Time"}),o.jsx(Jl.TopCell,{children:"Level"}),o.jsx(Jl.TopCell,{children:"Entity"}),o.jsx(Jl.TopCell,{children:"Message"}),o.jsx(Jl.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Jl.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Jl.Spacer,{height:m}),h.map(y=>{const b=e[y.index];if(!b)return null;const x=a.get(b);if(!x)return null;const w=x===i;return o.jsxs(Jl.RowButton,{ref:u.measureElement,"data-index":y.index,...d(y.index),onClick:()=>l(b),featured:w,variant:b.level==="error"||b.level==="fatal"?"error":"default",children:[o.jsx(Jl.DateCell,{timestamp:b.timestamp}),o.jsx(Jl.TimeCell,{timestamp:b.timestamp}),o.jsx(Jl.LevelCell,{level:b.level}),o.jsx(Jl.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(Jl.MessageCell,{message:b.message}),o.jsx(Jl.DataCell,{data:b.data})]},x)}),o.jsx(Jl.Spacer,{height:v})]}),o.jsx(Jl.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function sOs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>aOs(f,a));return u?o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(APe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(NPe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function aOs(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}const iOs={"last-24h":"the last 24 hours","last-3d":"the last 3 days","last-7d":"the last 7 days","last-14d":"the last 14 days","last-30d":"the last 30 days"},ile="MMM d, yyyy HH:mm",ole="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function oOs({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${iOs[e]}`,description:ole}:t&&n?{title:`No logs between ${xr(t,ile)} and ${xr(n,ile)}`,description:ole}:t?{title:`No logs since ${xr(t,ile)}`,description:ole}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const lOs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=oOs({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsx(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",icon:o.jsx(Cs,{}),children:"Logging Documentation"})})})},cOs=20,uOs=1e4;function dOs(e,t,n){if(e?.pagination?.hasMore)return n+1}function fOs(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function hOs(e){return b4(e.state.error,"logs")||x4(e.state.error)?!1:uOs}const pOs=({filters:e}={})=>{const t=Ge(),{inView:n,setRef:r}=Yy(),s=ev({queryKey:["logs",e],queryFn:({pageParam:h})=>t.listLogsVNext({pagination:{page:h,perPage:cOs},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:dOs,select:fOs,retry:!1,refetchInterval:hOs}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},U8={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},wGt=[{label:"Agent",entityType:U8.AGENT},{label:"Workflow",entityType:U8.WORKFLOW},{label:"Scorer",entityType:U8.SCORER},{label:"Ingest",entityType:U8.INGEST}],mOs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],i0="rootEntityType",lx="datePreset",cx="dateFrom",ux="dateTo",gOs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Al={level:"filterLevel",tags:"filterTags",entityName:"filterEntityName",traceId:"filterTraceId",spanId:"filterSpanId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},E5=Object.keys(Al),ZPe=new Set(["tags"]),GPe="mastra:logs:saved-filters";function vOs(e,t=GPe){const n=SOs(e),r=e.get(lx);r&&n.set(lx,r);const s=e.get(cx);s&&n.set(cx,s);const a=e.get(ux);a&&n.set(ux,a);try{localStorage.setItem(t,n.toString())}catch{}}function yOs(e=GPe){try{localStorage.removeItem(e)}catch{}}function Brt(e=GPe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function bOs(e){if(e.has(lx)||e.has(cx)||e.has(ux)||e.has(i0))return!0;for(const t of E5)if(e.has(Al[t]))return!0;return!1}function xOs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:wGt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"level",label:"Level",kind:"pick-multi",searchable:!1,options:mOs.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function wOs(e){const t=[],n=new Map([[i0,"rootEntityType"]]);for(const s of E5)n.set(Al[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),ZPe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function SOs(e){const t=new URLSearchParams,n=e.get(i0);n&&t.set(i0,n);for(const r of E5){const s=Al[r];if(ZPe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function kOs(e,t){e.delete(i0);for(const n of E5)e.delete(Al[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(i0,n.value);continue}const r=Al[n.fieldId];if(r){if(ZPe.has(n.fieldId)&&Array.isArray(n.value)){if(n.value.length===0)e.append(r,"");else for(const s of n.value)e.append(r,s);continue}typeof n.value=="string"&&e.set(r,n.value.trim())}}}function OOs({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function COs(e,t){return t.map(n=>{const r=e.find(s=>s.id===n.fieldId);return r?r.kind==="text"?{fieldId:n.fieldId,value:""}:r.kind==="pick-multi"?r.multi?{fieldId:n.fieldId,value:[]}:{fieldId:n.fieldId,value:"Any"}:n:n})}const _Os="Filters setting for Logs saved",EOs="Filters setting for Logs cleared up";function TOs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Brt(r)!==null),c=g.useCallback(()=>{vOs(e,r),l(!0);const f=s?.saved??_Os;f!==!1&&Be.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{yOs(r),l(!1);const f=s?.cleared??EOs;f!==!1&&Be.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,bOs(e)))return;const f=Brt(r);f&&t(h=>{const p=new URLSearchParams(h);for(const[m,v]of f)p.append(m,v);return p},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function jOs(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function NOs(e){const t=new Map;for(const n of e){if(n.logId){t.set(n,n.logId);continue}const r=n.timestamp instanceof Date?n.timestamp.toISOString():n.timestamp;t.set(n,jOs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function IOs(e,t,n,r){const s=g.useMemo(()=>NOs(e),[e]),a=g.useMemo(()=>{const p=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&p.set(y,{log:v,idx:m})}return p},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(p=>s.get(p),[s]),d=g.useCallback(p=>{const m=s.get(p);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const p=e[l-1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0,h=l>=0&&l<e.length-1?()=>{const p=e[l+1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:h}}const _we="logId",Ewe="traceId",Twe="spanId",s$=1440*60*1e3,AOs={"last-24h":s$,"last-3d":3*s$,"last-7d":7*s$,"last-14d":14*s$,"last-30d":30*s$};function q8(e){e.delete(_we),e.delete(Ewe),e.delete(Twe)}function ROs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const O=e.get(lx);return O&&gOs.has(O)?O:"last-24h"},[e]),a=e.get(cx),i=e.get(ux),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const _=new Date(a);return Number.isNaN(_.getTime())?void 0:_}if(s==="all")return;const O=AOs[s];return O?new Date(Date.now()-O):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const O=new Date(i);return Number.isNaN(O.getTime())?void 0:O},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(_we),f=e.get(Ewe),h=e.get(Twe),p=g.useMemo(()=>wGt.find(O=>O.entityType===e.get(i0)),[e]),m=g.useMemo(()=>wOs(e),[e]),v=g.useCallback(O=>{t(_=>{const T=new URLSearchParams(_);for(const[E,N]of Object.entries(O)){const I=E==="logId"?_we:E==="traceId"?Ewe:Twe;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(O=>{t(_=>{const T=new URLSearchParams(_);return kOs(T,O),q8(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((O,_)=>{if(u.current!=="custom")return;const T=_==="from"?cx:ux;t(E=>{const N=new URLSearchParams(E);return O?N.set(T,O.toISOString()):N.delete(T),q8(N),N},{replace:!0})},[t]),w=g.useCallback(O=>{u.current=O,t(_=>{const T=new URLSearchParams(_);return O==="last-24h"?(T.delete(lx),T.delete(cx),T.delete(ux)):O==="custom"?T.set(lx,"custom"):(T.set(lx,O),T.delete(cx),T.delete(ux)),q8(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(O=>{const _=new URLSearchParams(O);_.delete(i0);for(const T of E5)_.delete(Al[T]);return _.delete(lx),_.delete(cx),_.delete(ux),q8(_),_},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:h,selectedEntityOption:p,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:w,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,h,p,m,v,b,x,w,k,y])}const lle=ja.KeyValueList;function POs({spanId:e,span:t,isLoading:n,onClose:r}){return o.jsxs(ja,{children:[o.jsxs(ja.Header,{children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsxs(ja.Heading,{className:"items-center",children:["Span",o.jsx(AY,{id:e})]}),t&&o.jsx(mWt,{span:t})]}),o.jsx(ja.CloseButton,{onClick:r})]}),n?o.jsx(ja.LoadingData,{children:"Loading span..."}):t?o.jsxs(ja.Content,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsxs(lle,{children:[o.jsx(lle.Key,{children:"Type"}),o.jsx(lle.Value,{children:t.spanType})]}),o.jsx("br",{})]}),o.jsx(ja.CodeSection,{title:"Input",icon:o.jsx(zO,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(ja.CodeSection,{title:"Output",icon:o.jsx(xy,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(ja.CodeSection,{title:"Metadata",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(ja.CodeSection,{title:"Attributes",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(ja.NoData,{children:"Span not found."})]})}function $Os({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>b5(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(PY(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(ja,{children:[o.jsxs(ja.Header,{children:[o.jsxs(ja.Heading,{className:"items-center",children:["Trace",o.jsx(AY,{id:e})]}),o.jsx(ja.CloseButton,{onClick:r})]}),n?o.jsx(ja.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(ja.NoData,{children:"No spans found for this trace."}):o.jsx(ja.Content,{children:o.jsx(fPe,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function MOs(){const[e,t]=da(),n=ROs(e,t),r=TOs(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=FPe(),{data:d=[],isPending:f}=MPe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:p}=DPe(),{data:m=[],isPending:v}=LPe(),y=g.useMemo(()=>xOs({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:h,loading:{tags:u,entityNames:f,serviceNames:v,environments:p}}),[c,d,m,h,u,f,v,p]),b=g.useMemo(()=>OOs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:w,error:k,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:T}=pOs({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:$}=IOs(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:z,isLoading:D}=MA(n.featuredTraceId??null),{data:q,isLoading:H}=RY(n.featuredTraceId??"",n.featuredSpanId??""),V=g.useCallback(()=>n.applyFilterTokens(COs(y,n.filterTokens)),[y,n]),B=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),W=g.useCallback(Q=>n.handleFeaturedChange({traceId:Q,spanId:null}),[n]),L=g.useCallback((Q,te)=>n.handleFeaturedChange({traceId:Q,spanId:te}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),M=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),R=g.useCallback(Q=>n.handleFeaturedChange({spanId:Q??null}),[n]),F=o.jsxs(Bt.TopArea,{children:[o.jsx(Bt.Row,{children:o.jsxs(Bt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(w4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:w,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(RPe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:a})]})}),o.jsx(sOs,{isLoading:w,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:V,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Bt,{width:"wide",height:"full",children:[F,o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(Zks,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const U=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!w&&!U?o.jsxs(Bt,{width:"wide",height:"full",children:[F,o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(lOs,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Bt,{width:"wide",height:"full",children:[F,o.jsx(Gks,{logCollapsed:i,listSlot:o.jsx(rOs,{logs:x,isLoading:w,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Wks,{log:N,onClose:B,onTraceClick:W,onSpanClick:L,onPrevious:A,onNext:$,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx($Os,{traceId:n.featuredTraceId,spans:z?.spans,isLoading:D,onClose:G,onSpanSelect:R,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(POs,{spanId:n.featuredSpanId,span:q?.span,isLoading:H,onClose:M}):null})]})}function DOs({server:e,rowProps:t}){const{paths:n,Link:r}=ln(),a=Ge().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=Zqt(e),c=Object.values(l||{}),u=c.length,d=c.filter(p=>p.toolType==="agent").length,f=c.filter(p=>p.toolType==="workflow").length,h=Vf(e.name,50);return o.jsxs(be.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(be.NameCell,{children:h}),o.jsx(be.DescriptionCell,{children:i}),o.jsx(be.TextCell,{className:"text-center",children:d||""}),o.jsx(be.TextCell,{className:"text-center",children:u||""}),o.jsx(be.TextCell,{className:"text-center",children:f||""})]})}function LOs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const i=n.toLowerCase();return e.filter(l=>l.name?.toLowerCase().includes(i)||l.id?.toLowerCase().includes(i))},[e,n]),{containerRef:s,getRowProps:a}=ll({count:r.length,global:!0});return t?o.jsx(Uo,{columns:"auto 1fr auto auto auto"}):o.jsxs(be,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Name"}),o.jsx(be.TopCell,{children:"URL"}),o.jsx(be.TopCellSmart,{long:"Agents",short:o.jsx(Pi,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(be.TopCellSmart,{long:"Tools",short:o.jsx(Xd,{}),tooltip:"Tools",className:"text-center"}),o.jsx(be.TopCellSmart,{long:"Workflows",short:o.jsx(hc,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(be.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(DOs,{server:i,rowProps:a(l)},i.id))]})}const FOs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsx(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",icon:o.jsx(Cs,{}),children:"MCP Documentation"})})}),zOs=()=>{const{data:e=[],isLoading:t,error:n}=d5(),[r,s]=g.useState("");return n&&ms(n)?o.jsx(Qn,{children:o.jsx(zs,{})}):n&&gs(n)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"MCP servers"})}):n?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Qn,{children:o.jsx(FOs,{})}):o.jsxs(Bt,{height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(qc,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(LOs,{mcpServers:e,isLoading:t,search:r})]})},BOs=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function UOs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=ln(),i=g.useMemo(()=>BOs(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=ll({count:l.length,global:!0});return n?o.jsx(Uo,{columns:"auto 1fr auto"}):o.jsxs(be,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Name"}),o.jsx(be.TopCell,{children:"Description"}),o.jsx(be.TopCellSmart,{long:"Agents",short:o.jsx(Pi,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(be.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const h=Vf(d.id,50),p=Vf(d.description??"",200),m=d.agents.length;return o.jsxs(be.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(be.NameCell,{children:h}),o.jsx(be.DescriptionCell,{children:p}),o.jsx(be.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const qOs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsx(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",icon:o.jsx(Cs,{}),children:"Tools Documentation"})})}),VOs=()=>{const e=Ge();return wn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new e_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Be.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},HOs=({toolId:e})=>{const{canExecute:t}=Wo(),n=t("tools"),{data:r={}}=Yf(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=f4r(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=VOs(),{requestContext:h}=vs();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Be.error(`Error loading tool: ${v}`)}},[l]);const p=async(v,y)=>{if(!c)return;const b={...h??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?xm(zx(c?.inputSchema)):ws({});return i?o.jsxs("div",{className:"p-4",children:[o.jsx(Et,{className:"mb-4 h-8 w-48"}),o.jsx(Et,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(HRe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:p,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function WOs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=SA(),{data:v={},isLoading:y,isError:b,error:x}=Yf(),{navigate:w,paths:k}=ln();g.useEffect(()=>{if(p){const E=m instanceof Error?m.message:"Failed to load tools";Be.error(`Error loading tools: ${E}`)}},[p,m]),g.useEffect(()=>{if(b){const E=x instanceof Error?x.message:"Failed to load agents";Be.error(`Error loading agents: ${E}`)}},[b,x]);const O=new Map;Object.values(v).forEach(E=>{E.tools&&Object.values(E.tools).forEach(N=>{O.has(N.id)||O.set(N.id,N)})}),Object.values(f).forEach(E=>{O.has(E.id)||O.set(E.id,E)});const _=Array.from(O.values()).map(E=>({label:E.id,value:E.id})),T=E=>{t?t(E):E&&E!==e&&w(k.toolLink(E))};return o.jsx(Co,{options:_,value:e,onValueChange:T,placeholder:h||y?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||h||y||p||b,variant:l,size:c,"aria-label":u,align:d})}const ZOs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(jx,{children:o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(jx,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-5 py-8",children:[o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-4",children:[o.jsx(xt,{icon:o.jsx(yWt,{}),size:"sm",children:"Version"}),o.jsx(xt,{size:"sm",children:t.version_detail.version})]}),o.jsx(ge,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ge,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ge,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ge,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ge,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ge,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ge,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(GOs,{server:t})})]})},GOs=({server:e})=>{const{data:t={},isLoading:n}=Zqt(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(st,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(Z_,{})}),o.jsx(ge,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-4",children:r.map(s=>{const a=t[s];return o.jsx(YOs,{tool:a,serverId:e.id},s)})})]})};function QOs(e){if(!e)return!1;const t=e.ui;return!!(typeof t?.resourceUri=="string"&&t.resourceUri.startsWith("ui://")||typeof e["ui/resourceUri"]=="string"&&e["ui/resourceUri"].startsWith("ui://"))}const YOs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=ln(),a=WVt[e.toolType||"tool"],i=QOs(e._meta);return o.jsxs(Kf,{onClick:()=>n.current?.click(),children:[o.jsx(w5t,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Jf,{children:[o.jsx(Xf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(xt,{size:"xs",children:"App"})]})}),o.jsx(dp,{children:e.description})]})]})},KOs=()=>{const{serverId:e}=tr(),{data:t=[],isLoading:n}=d5(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(ZOs,{isLoading:n,server:r})})};function XOs(e){if(!e)return;const t=e.ui;if(t?.resourceUri)return t.resourceUri;const n=e["ui/resourceUri"];if(typeof n=="string")return n}const JOs=({toolId:e,serverId:t})=>{const{canExecute:n}=Wo(),r=n("tools"),s=Ge(),{data:a,isLoading:i,error:l}=IRe(t,e),{mutateAsync:c,isPending:u,data:d}=Nos(t,e),f=a?XOs(a._meta):void 0,{data:h}=mt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),p=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Be.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-4",children:[o.jsx(Et,{className:"mb-4 h-8 w-48"}),o.jsx(Et,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=xm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Be.error("Failed to process tool input schema."),v=ws({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[h&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(Wqt,{html:h,toolName:a.name??a.id,onToolCall:p})}),o.jsx(HRe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},eCs=()=>{const{serverId:e,toolId:t}=tr(),{data:n,isLoading:r}=IRe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(JOs,{toolId:t,serverId:e})})},SGt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],vI="rootEntityType",yI={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId",provider:"filterProvider",model:"filterModel"},sK=Object.keys(yI),QPe="mastra:metrics:saved-filters";function tCs(e){const t=iCs(e);try{localStorage.setItem(QPe,t.toString())}catch{}}function nCs(){try{localStorage.removeItem(QPe)}catch{}}function kGt(){try{const e=localStorage.getItem(QPe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function rCs(e){if(e.has(vI))return!0;for(const t of sK)if(e.has(yI[t]))return!0;return!1}function sCs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:SGt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function aCs(e){const t=[],n=new Map([[vI,"rootEntityType"]]);for(const s of sK)n.set(yI[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function iCs(e){const t=new URLSearchParams,n=e.getAll(vI);for(const r of n)t.append(vI,r);for(const r of sK){const s=yI[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function oCs(e,t){e.delete(vI);for(const n of sK)e.delete(yI[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?vI:yI[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const lCs="Any";function Urt(e){const t=e.trim();return t===""||t===lCs}const cCs=new Set(SGt.map(e=>e.entityType));function qrt(e){const t=e.trim();return cCs.has(t)?t:void 0}function uCs(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!Urt(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?qrt(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Urt(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=qrt(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const OGt=[{label:"Last 24 hours",value:"24h"},{label:"Last 3 days",value:"3d"},{label:"Last 7 days",value:"7d"},{label:"Last 14 days",value:"14d"},{label:"Last 30 days",value:"30d"}],dCs=new Set(OGt.map(e=>e.value));function fCs(e){return typeof e=="string"&&(dCs.has(e)||e==="custom")}const CGt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function aK(){return g.useContext(CGt)}function hCs(e,t){return e!=="custom"?OGt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${xr(t.from,"MMM d, yyyy")} – ${xr(t.to,"MMM d, yyyy")}`:xr(t.from,"MMM d, yyyy"):"Custom range"}function pCs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>uCs(d),[d]),h=g.useMemo(()=>JSON.stringify(f),[f]),p=hCs(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:p,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:h,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,p,d,s,f,h,l,c]);return o.jsx(CGt.Provider,{value:m,children:e})}const mCs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function gCs(e){switch(e){case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return"last-24h"}}function vCs(e){switch(e){case"last-3d":return"3d";case"last-7d":return"7d";case"last-14d":return"14d";case"last-30d":return"30d";case"custom":return"custom";default:return"24h"}}function yCs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=aK(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(w4,{preset:gCs(e),onPresetChange:i=>{const l=vCs(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:mCs})}const jwe=1440*60*1e3,bCs={"24h":jwe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function xCs(e,t,n){if(e!=="custom"){const r=bCs[e]??jwe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-jwe),end:t?.to??new Date(n)}}function Hm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=aK(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>xCs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function _Gt(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function T5({href:e,LinkComponent:t="a"}){return o.jsx(ie,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(Ui,{})})}function wCs({href:e,LinkComponent:t="a"}){return o.jsx(ie,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(onn,{})})}function SCs(e){return e==="agents"||e==="workflows"||e==="tools"}function Vrt(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const a=s[t];return r+(typeof a=="number"&&Number.isFinite(a)?a:0)},0);return`${Math.round(n/e.length)}`}function kCs(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const OCs=[{dataKey:"p50",label:"p50",color:Xh.blue,aggregate:e=>({value:Vrt(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Xh.yellow,aggregate:e=>({value:Vrt(e,"p95"),suffix:"avg ms"})}];function cle({data:e,onPointClick:t}){return e.length===0?o.jsx(Wt.NoData,{message:"No latency data yet"}):o.jsx(y3,{data:e,series:OCs,onPointClick:t?n=>kCs(n)?t(n):void 0:void 0})}function CCs({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),h=c[d]?d:u,p=typeof s=="function"?s(h):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Wt.Summary,{value:y,label:"Avg p50"}),p?o.jsx(Wt.Actions,{children:p}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load latency data"}):o.jsx(Wt.Content,{children:m?o.jsxs(kl,{value:h,onValueChange:b=>{SCs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Sl,{children:[o.jsx(kr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(kr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(kr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Hr,{value:"agents",children:o.jsx(cle,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Hr,{value:"workflows",children:o.jsx(cle,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Hr,{value:"tools",children:o.jsx(cle,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Wt.NoData,{message:"No latency data yet"})})]})}function _Cs(e){switch(e){case"24h":return"last-24h";case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return}}function ECs(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function EGt(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=_Cs(s);l&&e.set(t,l)}function $o(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function TGt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function Hrt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(tS,"branches"),EGt(a,nS,sj,aj,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(s0,i),r.status&&a.set(a0,r.status),$o(a,Il.entityName,r.entityName??n.entityName),$o(a,Il.threadId,r.threadId??n.threadId),$o(a,Il.resourceId,r.resourceId??n.resourceId),$o(a,Il.entityId,n.entityId),$o(a,Il.runId,n.runId),$o(a,Il.sessionId,n.sessionId),$o(a,Il.requestId,n.requestId),$o(a,Il.userId,n.userId),$o(a,Il.organizationId,n.organizationId),$o(a,Il.experimentId,n.experimentId),$o(a,Il.serviceName,n.serviceName),$o(a,Il.environment,n.environment),TGt(a,Il.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function TCs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;EGt(a,lx,cx,ux,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(i0,i),$o(a,Al.entityName,r.entityName??n.entityName),$o(a,Al.threadId,r.threadId??n.threadId),$o(a,Al.resourceId,r.resourceId??n.resourceId),$o(a,Al.runId,n.runId),$o(a,Al.sessionId,n.sessionId),$o(a,Al.requestId,n.requestId),$o(a,Al.userId,n.userId),$o(a,Al.organizationId,n.organizationId),$o(a,Al.experimentId,n.experimentId),$o(a,Al.serviceName,n.serviceName),$o(a,Al.environment,n.environment),TGt(a,Al.tags,n.tags),r.status==="error"&&a.append(Al.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function WA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=aK(),a=g.useCallback((c={})=>Hrt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>TCs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=ECs(u,d);return Hrt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const jGt="1h";async function ule(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:jGt,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function jCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([ule(e,"mastra_agent_duration_ms",t),ule(e,"mastra_workflow_duration_ms",t),ule(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:jGt}}})}const Wrt={agents:Qu.AGENT,workflows:Qu.WORKFLOW_RUN,tools:Qu.TOOL};function NCs(){const{data:e,isLoading:t,isError:n}=jCs(),{getTracesHref:r,getBucketTracesHref:s}=WA(),{Link:a}=ln(),i=zr();return o.jsx(CCs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Wrt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(T5,{href:r({rootEntityType:Wrt[l]}),LinkComponent:a})})}function ICs(e){return e==="threads"||e==="resources"}function dle(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function ACs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,h=e.data?.reduce((y,b)=>y+b.runs,0)??0,p=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Wt.Summary,{value:h.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Wt.Summary,{value:p.toLocaleString(),label:"Total threads"}),v?o.jsx(Wt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Wt.Loading,{}):m.isError?o.jsx(Wt.Error,{message:"Failed to load memory data"}):o.jsx(Wt.Content,{children:o.jsxs(kl,{defaultTab:"threads",value:i,onValueChange:y=>{ICs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Sl,{children:[o.jsx(kr,{value:"threads",children:"Threads"}),o.jsx(kr,{value:"resources",children:"Resources"})]}),o.jsx(Hr,{value:"threads",children:d?o.jsxs(be,{columns:"auto auto auto auto auto",...dwe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:dle(y.threadId)}),o.jsx(be.NumberCell,{children:y.resourceId?dle(y.resourceId):"—"}),o.jsx(be.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(be.NumberCell,{children:y.tokens>0?ao(y.tokens):"—"}),o.jsx(be.NumberCell,{children:y.cost!=null?Ud(y.cost,y.costUnit):"—"})]});return b?o.jsx(be.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(be.RowStatic,{children:x},y.key)})]}):o.jsx(Wt.NoData,{message:"No thread activity yet"})}),o.jsx(Hr,{value:"resources",children:f?o.jsxs(be,{columns:"auto auto auto auto",...dwe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:dle(y.resourceId)}),o.jsx(be.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(be.NumberCell,{children:y.tokens>0?ao(y.tokens):"—"}),o.jsx(be.NumberCell,{children:y.cost!=null?Ud(y.cost,y.costUnit):"—"})]});return b?o.jsx(be.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(be.RowStatic,{children:x},y.key)})]}):o.jsx(Wt.NoData,{message:"No resource activity yet"})})]})})]})}const fle=20;function RCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:fle}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:fle}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:fle})]),l=new Map,c=d=>DA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.threadId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,h=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}const hle=20;function PCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:hle}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:hle}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:hle})]),l=new Map,c=d=>DA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.resourceId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,h=l.get(f);return{resourceId:f,threadCount:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}function $Cs(){const e=RCs(),t=PCs(),{getTracesHref:n}=WA(),{Link:r}=ln();return o.jsx(ACs,{threads:{data:e.data,isLoading:e.isLoading,isError:e.isError},resources:{data:t.data,isLoading:t.isLoading,isError:t.isError},LinkComponent:r,getThreadRowHref:s=>n({threadId:s.threadId,...s.resourceId?{resourceId:s.resourceId}:{}}),getResourceRowHref:s=>n({resourceId:s.resourceId})})}function j5({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:e}),o.jsx(Jr.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(Jr.Error,{}):s?o.jsx(Jr.Loading,{}):i?r!=null?o.jsx(Jr.Change,{changePct:r,prevValue:n}):o.jsx(Jr.NoChange,{}):o.jsx(Jr.NoData,{})]})}function MCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function DCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function LCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function FCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function zCs(){const{data:e,isLoading:t,isError:n}=_Gt();return o.jsx(j5,{label:"Total Agent Runs",value:e?.value!=null?e.value.toLocaleString():null,prevValue:e?.previousValue!=null?e.previousValue.toLocaleString():void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function BCs(){const{data:e,isLoading:t,isError:n}=LCs();return o.jsx(j5,{label:"Total Model Cost",value:e?.cost!=null?Ud(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Ud(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function UCs(){const{data:e,isLoading:t,isError:n}=FCs();return o.jsx(j5,{label:"Total Tokens",value:e?.value!=null?ao(e.value):null,prevValue:e?.previousValue!=null?ao(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function qCs(){const{data:e,isLoading:t,isError:n}=DCs();return o.jsx(j5,{label:"Total Threads",value:e?.value!=null?ao(e.value):null,prevValue:e?.previousValue!=null?ao(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function VCs(){const{data:e,isLoading:t,isError:n}=MCs();return o.jsx(j5,{label:"Total Resources",value:e?.value!=null?ao(e.value):null,prevValue:e?.previousValue!=null?ao(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function HCs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>WCs(f,a));return u?o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(APe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(NPe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function WCs(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}function ZCs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Ud(l):"—":c.size===1?u=l>0?Ud(l,[...c][0]):"—":u="Mixed",o.jsx(Wt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Wt.Actions,{children:s}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load model usage data"}):o.jsx(Wt.Content,{children:i?o.jsxs(be,{columns:"auto auto auto auto auto auto",...dwe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Model"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(be.NumberCell,{children:l.input}),o.jsx(be.NumberCell,{children:l.output}),o.jsx(be.NumberCell,{children:l.cacheRead}),o.jsx(be.NumberCell,{children:l.cacheWrite}),o.jsx(be.NumberCell,{highlight:!0,children:l.cost!=null?Ud(l.cost,l.costUnit):"—"})]});return c?o.jsx(be.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(be.RowStatic,{children:u},l.model)})]}):o.jsx(Wt.NoData,{message:"No model usage data yet"})})]})}function GCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>DA(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",h=c(f);h.input=d.value,u(h,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",h=c(f);h.output=d.value,u(h,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:ao(f.input),output:ao(f.output),cacheRead:ao(f.cacheRead),cacheWrite:ao(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function QCs(){const{data:e,isLoading:t,isError:n}=GCs(),{getTracesHref:r}=WA(),{Link:s}=ln();return o.jsx(ZCs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Qu.AGENT}),actions:o.jsx(T5,{href:r({rootEntityType:Qu.AGENT}),LinkComponent:s})})}function YCs(e){return e==="tokens"||e==="cost"}function KCs({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),h=new Set(f.map(b=>b.costUnit??"usd")),p=h.size<=1,m=p?[...h][0]??"usd":null,v=p?f.reduce((b,x)=>b+(x.cost??0),0):0,y=p&&v>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Wt.Summary,{value:Ud(v,m),label:"Total cost"}):o.jsx(Wt.Summary,{value:ao(d),label:"Total tokens"})),u&&s?o.jsx(Wt.Actions,{children:s}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load token usage data"}):o.jsx(Wt.Content,{children:u?o.jsxs(kl,{defaultTab:"tokens",value:i,onValueChange:b=>{YCs(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Sl,{children:[o.jsx(kr,{value:"tokens",children:"Tokens"}),o.jsx(kr,{value:"cost",children:"Cost"})]}),o.jsx(Hr,{value:"tokens",children:o.jsx(gI,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Xh.blueDark},{label:"Output",color:Xh.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:ao})}),o.jsx(Hr,{value:"cost",children:y?o.jsx(gI,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Xh.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Ud(b,m)}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function XCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>DA(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function JCs(){const{data:e,isLoading:t,isError:n}=XCs(),{getTracesHref:r}=WA(),{Link:s}=ln();return o.jsx(KCs,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Qu.AGENT,entityName:a.name}),actions:o.jsx(T5,{href:r({rootEntityType:Qu.AGENT}),LinkComponent:s})})}function Nwe(e,t=ao){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const e_s=[{dataKey:"input",label:"Input tokens",color:Xh.blue,aggregate:Nwe("input")},{dataKey:"output",label:"Output tokens",color:Xh.yellow,aggregate:Nwe("output")}];function t_s(e){return e==="tokens"||e==="cost"}function n_s({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,O)=>k+O.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),h=f.map(k=>({...k})),p=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=p.size===1&&f.every(k=>k.costUnit!=null),v=m?[...p][0]??null:null,y=m?f.reduce((k,O)=>k+(O.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",w=[{dataKey:"cost",label:"Cost",color:Xh.purple,aggregate:Nwe("cost",k=>Ud(k,v))}];return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Wt.Summary,{value:Ud(y,v),label:"Total cost"}):o.jsx(Wt.Summary,{value:ao(d),label:"Total tokens"})),u&&s?o.jsx(Wt.Actions,{children:s}):null]}),n?o.jsx(Wt.Loading,{}):r?o.jsx(Wt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Wt.Content,{children:u?o.jsxs(kl,{defaultTab:"tokens",value:a,onValueChange:k=>{t_s(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Sl,{children:[o.jsx(kr,{value:"tokens",children:"Tokens"}),o.jsx(kr,{value:"cost",children:"Cost"})]}),o.jsx(Hr,{value:"tokens",children:o.jsx(y3,{data:c,series:e_s})}),o.jsx(Hr,{value:"cost",children:b?o.jsx(y3,{data:h,series:w}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function r_s(e){return e==="24h"?"1h":"1d"}function s_s(e,t){return t==="1h"?e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):e.toLocaleDateString("en-US",{month:"short",day:"2-digit"})}function Zrt(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function a_s(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function i_s(){const e=Ge(),{datePreset:t,filters:n,filterKey:r}=Hm(),s=r_s(t);return mt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return Zrt(l,a.series[0],"input"),Zrt(l,i.series[0],"output"),{data:Array.from(l.values()).sort((u,d)=>u.tsMs-d.tsMs).map(u=>{const d=new Date(u.tsMs);return{time:s_s(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:a_s(u)}}),interval:s}}})}function o_s(){const{data:e,isLoading:t,isError:n}=i_s(),{getTracesHref:r}=WA(),{Link:s}=ln();return o.jsx(n_s,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(T5,{href:r(),LinkComponent:s})})}function ple({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(gI,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:Xh.blueDark},{label:"Errors",color:Xh.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:ao})}function l_s({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,h=m=>r?v=>r(m,v):void 0,p=m=>s?v=>s(m,v):void 0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Wt.Summary,{value:ao(f),label:"Total runs"}),u?o.jsx(Wt.Actions,{children:u}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load trace volume data"}):o.jsx(Wt.Content,{children:d?o.jsxs(kl,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Sl,{children:[o.jsx(kr,{value:"agents",children:"Agents"}),o.jsx(kr,{value:"workflows",children:"Workflows"}),o.jsx(kr,{value:"tools",children:"Tools"})]}),o.jsx(Hr,{value:"agents",children:e.agentData.length>0?o.jsx(ple,{data:e.agentData,rowHrefs:h("agents"),errorHrefs:p("agents"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No agent data yet"})}),o.jsx(Hr,{value:"workflows",children:e.workflowData.length>0?o.jsx(ple,{data:e.workflowData,rowHrefs:h("workflows"),errorHrefs:p("workflows"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No workflow data yet"})}),o.jsx(Hr,{value:"tools",children:e.toolData.length>0?o.jsx(ple,{data:e.toolData,rowHrefs:h("tools"),errorHrefs:p("tools"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No tool data yet"})})]}):o.jsx(Wt.NoData,{message:"No trace volume data yet"})})]})}async function mle(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=DA(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function c_s(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([mle(e,"mastra_agent_duration_ms",t),mle(e,"mastra_workflow_duration_ms",t),mle(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const V8={agents:Qu.AGENT,workflows:Qu.WORKFLOW_RUN,tools:Qu.TOOL};function u_s(){const{data:e,isLoading:t,isError:n}=c_s(),{getTracesHref:r,getLogsHref:s}=WA(),{Link:a}=ln();return o.jsx(l_s,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:V8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:V8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(T5,{href:r({rootEntityType:V8[i]}),LinkComponent:a}),o.jsx(wCs,{href:s({rootEntityType:V8[i],status:"error"}),LinkComponent:a})]})})}const gle="period",H8="dateFrom",W8="dateTo";function d_s(){const[e,t]=da(),n=e.get(gle),r=fCs(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=p=>{if(!p)return;const m=new Date(p);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(H8)),h=d(e.get(W8));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),a=g.useMemo(()=>aCs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(gle):h.set(gle,d),d!=="custom"&&(h.delete(H8),h.delete(W8)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(H8,d.from.toISOString()):h.delete(H8),d?.to?h.set(W8,d.to.toISOString()):h.delete(W8),h},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return oCs(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,rCs(e)))return;const d=kGt();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),o.jsx(pCs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(f_s,{})})}function f_s(){const[e]=da(),{error:t,isLoading:n}=_Gt(),{filterTokens:r,setFilterTokens:s}=aK(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=NY(),{data:d,isLoading:f}=FPe(),{data:h,isLoading:p}=MPe(),{data:m,isLoading:v}=LPe(),{data:y,isLoading:b}=DPe(),x=g.useMemo(()=>sCs({availableTags:d??[],availableEntityNames:h??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:p,serviceNames:v,environments:b}}),[d,h,m,y,f,p,v,b]),[w,k]=g.useState(()=>kGt()!==null),O=g.useCallback(()=>{tCs(e),k(!0),Be.success("Filters setting for Metrics saved")},[e]),_=g.useCallback(()=>{nCs(),k(!1),Be.success("Filters setting for Metrics cleared up")},[]),T=g.useCallback(()=>{s([])},[s]),E=g.useCallback(()=>{const N=r.map(I=>{const A=x.find($=>$.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&ms(t)?o.jsx(Qn,{children:o.jsx(zs,{})}):t&&gs(t)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"metrics"})}):t?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Bt,{width:"wide",height:"full",children:[o.jsxs(Bt.TopArea,{children:[o.jsx(Bt.Row,{children:o.jsxs(Bt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(yCs,{}),o.jsx(RPe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(HCs,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:E,onRemoveAll:T,onSave:O,onRemoveSaved:w?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-4 pb-6",children:[c&&o.jsx(Nn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Nn.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(Owe,{children:[o.jsx(zCs,{}),o.jsx(BCs,{}),o.jsx(UCs,{}),o.jsx(qCs,{}),o.jsx(VCs,{})]}),o.jsxs(Owe,{children:[o.jsx(QCs,{}),o.jsx(JCs,{}),o.jsx(o_s,{}),o.jsx($Cs,{}),o.jsx(u_s,{}),o.jsx(NCs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsx(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",icon:o.jsx(Cs,{}),children:"Metrics Documentation"})})})]})}function Grt(){const{isCmsAvailable:e}=ob(),{Link:t,paths:n}=ln();return e?o.jsx(nv,{owner:"prompt-block-list",children:o.jsx(Fx,{as:t,to:n.cmsPromptBlockCreateLink(),tooltip:"Create a prompt",variant:"ghost",size:"sm",children:"New prompt"})}):null}const h_s=50;function p_s(){const[e,t]=g.useState(""),[n,r]=g.useState(0),{data:s,isLoading:a,error:i,isPlaceholderData:l}=KVt({page:n,perPage:h_s}),c=s?.promptBlocks??[],u=s?.hasMore??!1,d=g.useCallback(()=>{l||r(p=>p+1)},[l]),f=g.useCallback(()=>{l||r(p=>Math.max(0,p-1))},[l]),h=g.useCallback(p=>{t(p),r(0)},[]);return i&&ms(i)?o.jsx(Qn,{children:o.jsx(zs,{})}):i&&gs(i)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"prompt blocks"})}):i?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load prompt blocks",message:i.message})}):c.length===0&&!a&&n===0?o.jsxs(Qn,{children:[o.jsx(Grt,{}),o.jsx(Jfs,{})]}):o.jsxs(Bt,{height:"full",children:[o.jsx(Grt,{}),o.jsx(Bt.TopArea,{children:o.jsx(Bt.Row,{align:"center",stack:"responsive",children:o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(qc,{onSearch:h,label:"Filter prompts",placeholder:"Filter by name or description"})})})}),o.jsx(Xfs,{promptBlocks:c,isLoading:a,search:e,currentPage:n,hasMore:u,onNextPage:d,onPrevPage:f})]})}function m_s(){return o.jsx(Bt,{width:"narrow",children:o.jsx(Bt.MainArea,{children:o.jsx(ils,{children:o.jsx(q0e,{})})})})}const g_s=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:jen,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:Rdt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Cs,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:R3,href:"https://discord.gg/mastra-ai",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:Mdt,href:"https://mastra.ai/cloud",external:!0},{title:"Talk to our Sales team",description:"Get a custom demo, discuss on-prem deployments, and how we can help you accelerate getting agents into production.",icon:Pdt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function v_s(){return o.jsx(Bt,{width:"narrow",children:o.jsx(Bt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:g_s.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group border-border1 bg-surface2 hover:border-accent1 hover:bg-surface3 flex flex-col gap-3 rounded-lg border p-5 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"text-icon3 group-hover:text-accent1 h-5 w-5 transition-colors"}),o.jsx("span",{className:"text-ui-md text-text1 font-medium",children:e.title}),e.external&&o.jsx(Cs,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3",children:e.description})]},e.href))})})})}function Qrt(){const{isCmsAvailable:e}=ob(),{Link:t,paths:n}=ln();return e?o.jsx(nv,{owner:"scorer-list",children:o.jsx(Fx,{as:t,to:n.cmsScorersCreateLink(),tooltip:"Create a scorer",variant:"ghost",size:"sm",children:"New scorer"})}):null}function y_s(){const{data:e={},isLoading:t,error:n}=tf(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&ms(n))return o.jsx(Qn,{children:o.jsx(zs,{})});if(n&&gs(n))return o.jsx(Qn,{children:o.jsx(Ts,{resource:"scorers"})});if(n)return o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsxs(Qn,{children:[o.jsx(Qrt,{}),o.jsx(nus,{})]});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Bt,{height:"full",children:[o.jsx(Qrt,{}),o.jsx(Bt.TopArea,{children:o.jsx(sus,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(tus,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}const NGt=["input","entity"],b_s={input:"Input",entity:"Entity"};function x_s(e){const t=["auto","auto","minmax(0, 10rem)"];return e.has("entity")&&t.push("minmax(0, 14rem)"),e.has("input")&&t.push("minmax(0, 40rem)"),t.join(" ")}function w_s(){const[e,t]=g.useState(new Set),n=g.useMemo(()=>new Set(NGt.filter(a=>!e.has(a))),[e]),r=g.useMemo(()=>x_s(n),[n]),s=g.useCallback(a=>{t(i=>{const l=new Set(i);return l.has(a)?l.delete(a):l.add(a),l})},[]);return{visibleColumns:n,columns:r,toggleColumn:s}}function S_s({visibleColumns:e,toggleColumn:t}){return o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{icon:o.jsx(ime,{}),children:"Columns"})}),o.jsxs(ot.Content,{align:"end",children:[o.jsx(ot.Label,{children:"Toggle columns"}),NGt.map(n=>o.jsx(ot.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:b_s[n]},n))]})]})}function k_s(){const{scorerId:e}=tr(),[t,n]=da(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=zr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=$cs(e),p=w_s(),{data:m={},isLoading:v,error:y}=Yf(),{isLoading:b,error:x}=Bm(),{data:w=[],isLoading:k,error:O,isFetchingNextPage:_,hasNextPage:T,setEndOfListElement:E}=Pcs({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),N=g.useMemo(()=>f?.agentIds?.filter(U=>m[U]).map(U=>({value:U,label:m[U].name,type:"AGENT"}))||[],[f?.agentIds,m]),I=g.useMemo(()=>f?.workflowIds?.map(U=>({value:U,label:U,type:"WORKFLOW"}))||[],[f?.workflowIds]),A=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...N,...I],[N,I]),$=t.get("entity")??"all",z=A.find(U=>U.value===$);z&&z.value!==u?.value&&d(z),g.useEffect(()=>{if(h){const U=h instanceof Error?h.message:"Failed to load scorer";Be.error(`Error loading scorer: ${U}`)}},[h]),g.useEffect(()=>{if(y){const U=y instanceof Error?y.message:"Failed to load agents";Be.error(`Error loading agents: ${U}`)}},[y]),g.useEffect(()=>{if(x){const U=x instanceof Error?x.message:"Failed to load workflows";Be.error(`Error loading workflows: ${U}`)}},[x]);const D=U=>{U?.value&&n(Q=>{const te=new URLSearchParams(Q);return te.set("entity",U.value),te})};g.useEffect(()=>{const U=t.get("scoreId")??void 0;if(U===s)return;if(!U){a(void 0);return}w.find(te=>te.id===U)&&a(U)},[t,w]);const q=g.useCallback(U=>{a(U||void 0),n(Q=>{const te=new URLSearchParams(Q);return U?te.set("scoreId",U):te.delete("scoreId"),te})},[n]);if(!f)return null;const H=ms(h)||ms(y)||ms(x),V=h&&gs(h),B=!H&&!V&&(h||y||x),W=!k&&w.length===0,L=u?.value!=="all",G=f?.scorer?.source==="stored",M=e?o.jsx(nK,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:U=>{c(`/experiments/${U}`)}}):null,R=G?o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{size:"lg","aria-label":"Scorer actions menu",children:o.jsx(d1,{})})}),o.jsx(ot.Content,{align:"end",className:"w-48",children:o.jsxs(ot.Item,{onSelect:()=>{c(`/cms/scorers/${e}/edit`)},children:[o.jsx(Yu,{})," Edit Scorer"]})})]}):null;if(H||V||B||W&&!L){const U=(h instanceof Error?h.message:void 0)??(y instanceof Error?y.message:void 0)??(x instanceof Error?x.message:void 0)??"An unexpected error occurred",Q=H||V||B;return o.jsxs(Bt,{width:"wide",height:"full",className:Q||!R?"grid-rows-[1fr]":void 0,children:[!Q&&R&&o.jsx(Bt.TopArea,{children:o.jsx(Wr,{className:"ml-auto",children:R})}),o.jsx(Bt.MainArea,{isCentered:!0,children:H?o.jsx(zs,{}):V?o.jsx(Ts,{resource:"scorers"}):B?o.jsx(Fs,{title:"Failed to load scorer",message:U}):o.jsx(Ecs,{onRunExperiment:()=>l(!0)})}),M]})}return o.jsxs(Bt,{width:"wide",height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(Tcs,{selectedEntity:u,entityOptions:A,onEntityChange:D,onReset:()=>{n(U=>{const Q=new URLSearchParams(U);return Q.set("entity","all"),Q})},isLoading:k||v||b}),o.jsxs(Wr,{children:[o.jsx(S_s,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),o.jsx(ie,{variant:"primary",onClick:()=>l(!0),icon:o.jsx(oc,{}),children:"Run Experiment"}),R]})]})}),o.jsx(_cs,{scores:w,isLoading:k,selectedScoreId:s,isFetchingNextPage:_,hasNextPage:T,setEndOfListElement:E,onScoreClick:q,errorMsg:O?.message,columnsState:p}),M]})}const O_s=[{value:"system",label:"System",icon:o.jsx(Kdt,{})},{value:"light",label:"Light",icon:o.jsx(Yrn,{})},{value:"dark",label:"Dark",icon:o.jsx(Onn,{})}],C_s={md:{itemGap:2,itemWidth:28,root:"gap-0.5 p-0.5",indicator:"inset-y-0.5 left-0.5",item:"h-6 [&_svg]:size-3.5"},xs:{itemGap:1,itemWidth:20,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-4 [&_svg]:h-icon-sm [&_svg]:w-icon-sm"},sm:{itemGap:1,itemWidth:24,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-5 [&_svg]:h-icon-sm [&_svg]:w-icon-sm"}},__s=({value:e,onChange:t,options:n=O_s,size:r="md",className:s,"aria-label":a="Theme",...i})=>{const{theme:l,setTheme:c}=b_(),u=e??l,d=t??c,f=n.some(y=>y.value===u)?u:n[0]?.value??"system",h=y=>{const b=n.find(x=>x.value===y);b&&d(b.value)},p=Math.max(0,n.findIndex(y=>y.value===f)),m=C_s[r],v=p*(m.itemWidth+m.itemGap);return o.jsxs(EVt,{...i,value:f,onValueChange:h,"aria-label":a,className:K("relative inline-flex w-fit items-center rounded-full border border-border1 bg-surface3",m.root,s),children:[o.jsx("span",{"aria-hidden":"true",className:K("pointer-events-none absolute rounded-full bg-surface5 motion-reduce:transition-none",ts.transform,m.indicator),style:{width:m.itemWidth,transform:`translateX(${v}px)`}}),n.map(y=>o.jsx(_Vt,{value:y.value,"aria-label":y.label,style:{width:m.itemWidth},className:K("relative inline-flex cursor-pointer items-center justify-center rounded-full","text-icon3 hover:text-icon6 data-[checked]:text-icon6",m.item,"focus-visible:outline-hidden","active:scale-90 motion-reduce:transition-none",ts.colors,ts.transform),children:o.jsx("span",{"aria-hidden":"true",className:"pointer-events-none inline-flex items-center justify-center",children:y.icon})},y.value))]})},E_s=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=kW();return o.jsx(Bt,{className:"p-0",children:o.jsx(Rus,{children:o.jsxs("div",{className:"mx-auto flex max-w-4xl flex-col gap-8",children:[o.jsxs(rtt,{children:[o.jsxs(stt,{children:[o.jsx(att,{children:"General"}),o.jsx(itt,{children:"Stored in this browser."})]}),o.jsx(vVt,{children:o.jsx(Q0e,{label:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(__s,{})})})]}),o.jsxs(rtt,{children:[o.jsxs(stt,{children:[o.jsx(att,{children:"Mastra Connection"}),o.jsx(itt,{children:"Configure the Mastra instance URL, API prefix, and request headers used by the studio."})]}),o.jsx($Vt,{variant:"factory",initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})]})]})})})};function T_s(){const[e]=da(),t=zr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(xGt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function j_s(e){return e.replace(/\/$/,"").split("/").pop()}function iK({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-5 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function N_s({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:K("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:K("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:K("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:K("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:K("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:K("grid py-3 px-4 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-md text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:K("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Pi,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Xd,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Xdt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(NI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(Z_,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:K("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(lQ,{})," ",j_s(a.githubUrl)]})})]},a.slug)})})}function I_s({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:K("h-[6.5rem] flex items-center gap-5","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:K("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-5",u),children:[o.jsx(QD,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(ad,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(ad,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsx(ie,{onClick:c,icon:o.jsx(qt,{}),children:"Reset"})]})}function A_s(){const{data:e,isLoading:t}=Ocr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const h=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{h.push({value:x,label:x})});const p=(x,w)=>{w==="tag"?i(x):w==="provider"&&c(x)},m=x=>{d(x)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(oa,{children:[o.jsx(vL,{children:o.jsxs(X0t,{children:[o.jsx(st,{children:o.jsx(gx,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-5 pb-12 z-10"),children:[o.jsx(I_s,{selectedTag:a,onTagChange:x=>p(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>p(x,"provider"),providerOptions:h,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(N_s,{templates:y,linkComponent:xo,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const R_s="1.67.0-alpha.6";function P_s({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(Ic,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(Uen,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(iK,{className:"text-neutral3 mb-5 content-center space-y-4",children:[o.jsxs("div",{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-ui-sm",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"text-ui-sm mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"text-ui-sm mt-1 font-mono wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-ui-sm",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"text-ui-sm mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}const $_s=g.createContext(null);function M_s(){const e=g.useContext($_s);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const IGt=({defaultProvider:e,defaultModel:t,updateModel:n,resetModel:r})=>{const[s]=g.useState(e),[a]=g.useState(t),[i,l]=g.useState(t),[c,u]=g.useState(e||""),[d,f]=g.useState(!1),[h,p]=g.useState(!1),[m,v]=g.useState(!1),{data:y,isLoading:b}=k4(),x=h0(),{models:w}=_0(),k=g.useMemo(()=>y?.providers||[],[y]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const O=Ra(c),T=Uj(k,O)?.id||O,E=async D=>{if(l(D),D&&T){f(!0);try{const q=await n({provider:T,modelId:D});console.info("Model updated:",q)}catch(q){console.error("Failed to update model:",q)}finally{f(!1)}}},N=D=>{const q=Ra(D);u(q),q!==O&&(l(""),v(!0))},{registerResetFn:I}=M_s();if(g.useEffect(()=>(I(()=>{if(h||m)return;if(O&&O!==s&&(!i||i==="")){u(Ra(s)),l(a);const B=Uj(k,s)?.id||s;B&&a&&n({provider:B,modelId:a}).catch(W=>{console.error("Failed to reset model:",W)})}}),()=>{I(null)}),[I,O,i,s,a,n,h,m,k]),b)return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Zt,{}),o.jsx("span",{className:"text-ui-md text-gray-500",children:"Loading providers..."})]});const A=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(D){console.error("Failed to reset model:",D)}finally{f(!1)}},$=Uj(k,O);if(x.active&&x.pickerVisible===!1){const D=x.default&&x.default.provider&&x.default.modelId?`${x.default.provider}/${x.default.modelId}`:c&&i?`${c}/${i}`:"Locked by admin";return o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center gap-2 rounded-md border px-3 py-2","data-testid":"agent-metadata-model-locked",children:[o.jsx(qd,{className:"text-neutral3 h-4 w-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral6 truncate",children:D}),o.jsx("span",{className:"text-ui-xs text-neutral3 ml-auto shrink-0",children:"Set by admin"})]})}const z=!!(O&&i)&&x.active&&x.allowed!==void 0&&!w.some(D=>Ra(D.provider)===O&&D.model===i);return o.jsxs("div",{className:"@container",children:[o.jsxs("div",{className:"flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center",children:[o.jsx("div",{className:"w-full @xs:w-2/5",children:o.jsx(sb,{value:O,onValueChange:N,open:h,onOpenChange:p})}),o.jsx("div",{className:"w-full @xs:w-3/5",children:o.jsx(ab,{llmId:O,value:i,onValueChange:E,open:m,onOpenChange:v})}),o.jsx(ie,{variant:"default",size:"md",onClick:A,disabled:d,className:"text-ui-sm flex items-center gap-1.5 border-0! whitespace-nowrap",title:"Reset to original model",children:o.jsx(f1,{className:"h-3.5 w-3.5"})})]}),z&&o.jsx("div",{className:"p-2 pt-2","data-testid":"agent-metadata-model-stale-warning",children:o.jsx(Nn,{variant:"warning",title:"Model not allowed",children:o.jsxs(Nn.Message,{children:[o.jsxs("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:[c,"/",i]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})})}),$&&!$.connected&&o.jsx("div",{className:"p-2 pt-2",children:o.jsx(Nn,{variant:"warning",title:"Provider not connected",children:o.jsxs(Nn.Message,{children:["Set the"," ",o.jsx("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:Array.isArray($.envVar)?$.envVar.join(", "):$.envVar})," ","environment"," ",Array.isArray($.envVar)&&$.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function D_s({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(iK,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5",children:[o.jsxs("h2",{className:K("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(Jdt,{})]}),o.jsx(ad,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:K("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(Zt,{})," Loading variables..."]}):Object.entries(r).map(([h,p])=>o.jsxs(g.Fragment,{children:[o.jsx(bm,{name:`env-${h}`,labelIsHidden:!0,label:"Key",value:h,disabled:!0,className:"w-full"}),o.jsx(bm,{name:h,labelIsHidden:!0,label:"Value",value:p,onChange:i,errorMsg:s.includes(h)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},h))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-md",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-5",children:"This model will be used by the workflow to process and install the template"}),o.jsx(IGt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ie,{className:K("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(Zt,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Df,{})]})})]})})}function L_s({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:K("grid mt-5 items-center"),children:o.jsxs("div",{className:K("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(gx,{}),o.jsx("h2",{className:K({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:K("mb-4 text-ui-md text-neutral4 mt-2",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:K("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(_m,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Wwe,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 text-ui-sm rounded px-1.5 py-0.5 font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(lQ,{}),n?.split("/")?.pop()]})]}),s&&o.jsx($Re,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Yrt(e){switch(e){case"running":return o.jsx(Zt,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Fn,{"aria-hidden":!0});case"failed":return o.jsx(qt,{"aria-hidden":!0});default:return null}}function F_s(){return o.jsx("svg",{viewBox:"0 0 24 24",className:"text-neutral2","aria-hidden":!0,children:o.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function z_s({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",ts.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(F_s,{}):Yrt(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",ts.colors,ts.transform,ts.shadow,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-neutral2":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark shadow-glow-accent1":e==="success","bg-accent2Dark shadow-glow-accent2":e==="failed","scale-110":e==="success"||e==="failed"}),children:Yrt(e)})}function B_s({step:e,isActive:t,position:n,variant:r="default"}){return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",ts.colors,{"border border-transparent":r==="default","border-dashed border-neutral2 bg-surface3":t&&r==="default"}),children:[o.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:K("flex min-w-6 justify-end text-ui-md",ts.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:[n,"."]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:K("text-ui-md",ts.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:e.title}),e.description&&o.jsx("p",{className:K("-mt-0.5 text-ui-md text-neutral2",{truncate:r==="plain"}),children:e.description})]})]}),o.jsx(z_s,{status:e.status,variant:r})]})}function U_s({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(B_s,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function q_s({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:K("relative flex h-8 items-center justify-end",ts.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:K("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3 motion-reduce:transition-none",ts.colors,ts.transform,ts.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Zt,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-ui-sm text-neutral3",ts.colors),children:[n," of ",t," steps completed"]})]})}function V_s({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),h=f.length,p=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(iK,{className:"text-neutral3 mb-5 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-header-sm font-semibold",children:p()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&h>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-4",children:o.jsx(q_s,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-4 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(Dnn,{}),l||"Something went wrong"]}),u&&o.jsx(U_s,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 text-ui-md grid justify-items-center gap-4 text-center",children:[o.jsx(Zt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function H_s({name:e,installedEntities:t}){return o.jsxs(iK,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Jdt,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-neutral3 text-center",children:["The ",o.jsx("b",{className:"text-neutral4",children:e})," template has been successfully installed.",t&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&o.jsx($Re,{data:t})]})}function W_s(){const{templateSlug:e}=tr(),[t,n]=da(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,h]=g.useState([]),[p,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[w,k]=g.useState(!1),[O,_]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=Ccr({repoOrSlug:e,owner:"mastra-ai"}),$=R_s?.includes("beta")??!1?"beta":"main",{data:z,isLoading:D}=_cr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:$}),{data:q,isLoading:H}=Ecr(),{mutateAsync:V,isPending:B}=Tcr(),{mutateAsync:W}=jcr(),{streamInstall:L,streamResult:G,isStreaming:M}=Icr(q),{observeInstall:R,streamResult:F,isStreaming:U}=Acr(q);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!p&&!M&&!U&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),W({runId:ne}).then(se=>{const ce=se.snapshot;if(ce?.status==="success"&&ce?.result?.success)y(!0);else if(ce?.result?.success===!1)if(ce?.result?.validationResults&&!ce?.result?.validationResults?.valid&&ce?.result?.validationResults?.remainingErrors>0){const{remainingErrors:ve,errors:ye}=ce.result.validationResults,Te=`Template installation completed but ${ve} validation issue${ve>1?"s":""} remain unresolved.`;m(Te),E(ye||[])}else{const ve=ce?.result?.message||ce?.result?.error||"Template installation failed";m(typeof ve=="string"?ve:String(ve))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,p,M,U,W]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),ce=t.get("provider");if(ne&&se==="true"&&ce&&!M&&!U&&!w&&!O&&q){x(ne),k(!0);try{W({runId:ne}).then(le=>{if(le.snapshot?.status==="running")return R.mutateAsync({runId:ne})}).then(()=>{n(le=>{const ve=new URLSearchParams(le);return ve.delete("resume"),ve})}).catch(le=>{console.error("❌ Failed to resume template installation:",le),le.message?.includes("404")||le.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(le){console.error("❌ Auto-resume failed with error:",le),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,M,U,w,O,q,W,R,n]);const Q=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],te=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Xd,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Pi,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(NI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(ny,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(TI,{})}],J=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{z&&d(z)},[z]),g.useEffect(()=>{const ne=G||F;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,F?.phase,F?.error]);const ee=ne=>{s(ne)},re=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),ae=async()=>{const ne=Object.entries(u).reduce((se,[ce,le])=>(le===""&&se.push(ce),se),[]);if(ne.length>0){h(ne);return}if(N){m(null),y(!1),x(""),_(!0);try{const ce={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:$,slug:N.slug,variables:u},{runId:le}=await V({});x(le),n(ve=>{const ye=new URLSearchParams(ve);return ye.set("runId",le),ye.set("resume","true"),ye.set("provider",r||"openai"),ye}),await L.mutateAsync({inputData:ce,selectedModel:{provider:a,modelId:l},runId:le})}catch(se){_(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=ne=>{const{name:se,value:ce}=ne.target;ce.trim()===""?h(le=>[...le,se]):h(le=>le.filter(ve=>ve!==se)),d(le=>({...le,[se]:ce}))};return o.jsx(oa,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-4",children:[o.jsx(L_s,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(M||U)&&o.jsx(V_s,{name:N.title,streamResult:U?F:G,runId:b,workflowInfo:q}),v&&o.jsx(H_s,{name:N.title,installedEntities:J,linkComponent:xo}),p&&o.jsx(P_s,{errorMsg:p,validationErrors:T.length>0?T:G?.validationResults?.errors||F?.validationResults?.errors}),!M&&!U&&!v&&!p&&o.jsx(D_s,{providerOptions:Q,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:h,handleInstallTemplate:ae,handleVariableChange:X,isLoadingEnvVars:D||H,isInstalling:B,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const Z_s=()=>{const{toolId:e,agentId:t}=tr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(tfs,{toolId:e,agentId:t})})},G_s=()=>{const{toolId:e}=tr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(HOs,{toolId:e})})};function Q_s(){const{data:e,isLoading:t,error:n}=Bm(),[r,s]=g.useState("");return n&&ms(n)?o.jsx(Qn,{children:o.jsx(zs,{})}):n&&gs(n)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"workflows"})}):n?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Qn,{children:o.jsx(SKr,{})}):o.jsxs(Bt,{height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsxs(Bt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(qc,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsx(ie,{as:xo,to:"/workflows/schedules",variant:"primary",className:"shrink-0",icon:o.jsx(WC,{}),children:"Schedules"})]})}),o.jsx(wKr,{workflows:e||{},isLoading:t,search:r})]})}const Y_s={active:"bg-accent1",paused:"bg-accent3"},K_s={active:"text-accent1",paused:"text-accent3"},AGt=({status:e})=>o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Y_s[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${K_s[e]}`,children:e})]}),Wj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),zM=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function RGt({status:e}){const{icon:t,color:n}=X_s(e);return o.jsxs("span",{className:`text-ui-sm inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function X_s(e){switch(e){case"success":return{icon:o.jsx(Fn,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(qt,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Zt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(yH,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Os,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(xS,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const Krt="auto auto auto auto 1fr";function J_s(e){if(e===void 0)return"—";if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}m ${n}s`}function eEs(e){const t=Math.abs(e),n=e<0?"-":"";return t<1e3?`${n}${t}ms`:t<6e4?`${n}${(t/1e3).toFixed(1)}s`:t<36e5?`${n}${(t/6e4).toFixed(1)}m`:`${n}${(t/36e5).toFixed(1)}h`}const tEs=3e4,nEs=5*6e4;function rEs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=ln(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=ll({count:u});let h=-1;return t?o.jsx(Uo,{columns:Krt}):e.length===0?o.jsx(ge,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(be,{columns:Krt,className:"min-w-0",scrollRef:d,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Run"}),o.jsx(be.TopCell,{children:"Status"}),o.jsx(be.TopCell,{children:"Started"}),o.jsx(be.TopCell,{children:"Duration"}),o.jsx(be.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=eEs(m),y=`Scheduled ${Wj(p.scheduledFireAt)} — published ${Wj(p.actualFireAt)} (drift ${v})`,b=p.outcome==="failed",x=b?p.error:p.run?.error,w=Math.abs(m),k=!b&&w>tEs&&w<=nEs,O=`${p.scheduleId}-${p.runId}-${p.actualFireAt}`,_=c(p);_&&(h+=1);const T=o.jsx("span",{className:_?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:p.runId}),E=o.jsxs(o.Fragment,{children:[o.jsx(be.Cell,{children:T}),o.jsx(be.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[b?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(Ic,{size:14}),"publish failed"]}):p.run?o.jsx(RGt,{status:p.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Ic,{size:14})})}),o.jsx(pn,{children:x})]}):null]})}),o.jsx(be.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:zM(p.actualFireAt)}),k?o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Ic,{size:14})})}),o.jsxs(pn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(be.Cell,{children:p.run?o.jsx("span",{children:J_s(p.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(be.Cell,{children:" "})]});return _?o.jsx(be.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:i,...f(h),children:E},O):o.jsx(be.RowStatic,{children:E},O)}),o.jsx(be.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const sEs=e=>{const t=Ge();return mt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},Xrt=25,aEs=e=>{const t=Ge(),{inView:n,setRef:r}=Yy(),s=ev({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:Xrt,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<Xrt))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(h=>h.triggers)??[]).some(h=>h.run?h.run.status==="pending"||h.run.status==="running"||h.run.status==="waiting":h.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},iEs=e=>{const t=Ge(),n=Cr();return wn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),Be.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Be.error(r.message)}})};function Z8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function oEs(){const{scheduleId:e}=tr(),{paths:t}=ln(),{data:n,error:r}=sEs(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=aEs(e),d=iEs(e);if(r&&ms(r))return o.jsx(Qn,{children:o.jsx(zs,{})});if(r&&gs(r))return o.jsx(Qn,{children:o.jsx(Ts,{resource:"schedules"})});if(r)return o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,h=n?.agentId;return o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsx(Bt.Row,{className:"justify-end",children:o.jsxs(Bt.Column,{className:"flex justify-end gap-2",children:[o.jsx(ie,{as:xo,to:t.schedulesLink(),variant:"ghost",icon:o.jsx(Lc,{}),children:"Back to schedules"}),f?o.jsx(ie,{icon:o.jsx(hc,{}),as:xo,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ie,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx(OH,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(oc,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(Z8,{label:h?"Agent":"Workflow",children:f?o.jsx(xo,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):h?o.jsx(xo,{to:t.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),o.jsxs(Z8,{label:"Cron",children:[o.jsx("code",{className:"text-ui-md font-mono",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 text-ui-sm ml-2",children:n.timezone}):null]}),o.jsx(Z8,{label:"Status",children:o.jsx(AGt,{status:n.status})}),o.jsx(Z8,{label:"Next fire",children:o.jsx("span",{title:Wj(n.nextFireAt),children:zM(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ge,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Fs,{title:"Failed to load trigger history",message:i.message}):o.jsx(rEs,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const Jrt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function lEs({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=ln(),a=g.useMemo(()=>{const c=n.toLowerCase();return c?e.filter(u=>u.id.toLowerCase().includes(c)||(u.workflowId??u.agentId??"").toLowerCase().includes(c)):e},[e,n]),{containerRef:i,getRowProps:l}=ll({count:a.length,global:!0});return t?o.jsx(Uo,{columns:Jrt}):o.jsxs(be,{columns:Jrt,className:"min-w-0",scrollRef:i,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Target"}),o.jsx(be.TopCell,{children:"Schedule ID"}),o.jsx(be.TopCell,{children:"Cron"}),o.jsx(be.TopCell,{children:"Status"}),o.jsx(be.TopCell,{children:"Next fire"}),o.jsx(be.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(be.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(be.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(be.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(be.NameCell,{children:c.workflowId??c.agentId}),o.jsx(be.Cell,{className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:c.id,children:c.id})}),o.jsx(be.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:c.cron}),c.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:c.timezone}):null]})}),o.jsx(be.Cell,{children:o.jsx(AGt,{status:c.status})}),o.jsx(be.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:Wj(c.nextFireAt),children:zM(c.nextFireAt)})}),o.jsx(be.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(RGt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Wj(c.lastFireAt),children:c.lastFireAt?zM(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Wj(c.lastFireAt),children:zM(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function cEs({workflowId:e}={}){const{data:t,isLoading:n,error:r}=qke(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Fs,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(qc,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(lEs,{schedules:t??[],isLoading:n,search:s})})]})}function uEs(){const[e]=da(),t=e.get("workflowId")??void 0,{error:n}=qke(t?{workflowId:t}:{});return n&&ms(n)?o.jsx(Qn,{children:o.jsx(zs,{})}):n&&gs(n)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"schedules"})}):o.jsx(Bt,{children:o.jsx("div",{className:"h-full",children:o.jsx(cEs,{workflowId:t})})})}function dEs({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=k_e({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=CTt(r),[d]=_Tt(s),{edgeTypes:f,nodeTypes:h,styledEdges:p}=RFt({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsx(kjt,{variant:"nested",nodes:l,edges:p,edgeTypes:f,nodeTypes:h,onNodesChange:u}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Zt,{})})})}function est(){const{stepDetail:e,closeStepDetail:t}=AZ();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(wS,{className:"h-4 w-4",style:{color:Pu.map}}),e.type==="nested-graph"&&o.jsx(hc,{className:"h-4 w-4",style:{color:Pu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ge,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(qt,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(yM,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(m_e,{children:o.jsx(dEs,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function fEs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function hEs(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);if(n.length===1)return n[0]}return t}function pEs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ge,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(st,{children:o.jsx(yH,{})}),"Step suspended"]}),o.jsx(xt,{variant:"yellow",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?xm(zx(i.resumeSchema)):vf(dr(),Ef());return o.jsx(mEs,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function mEs({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ge,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ge,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ge,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(st,{children:o.jsx(_nn,{})}),"The step is asking"]}),o.jsxs(cc,{open:a,onOpenChange:i,children:[o.jsxs(ql,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(st,{children:o.jsx(wr,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ge,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:hEs(e.suspendPayload,e.stepId)})]}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:fEs(e.suspendPayload)})]}),o.jsx(Vl,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Vr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ge,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(st,{children:o.jsx(Nnn,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(sq,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(oc,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function gEs(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Zl),{runId:a}=tr(),i=Tjt(e,r??""),l=nor(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(pEs,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const vEs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),yEs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),bEs=e=>e.includes("."),xEs=e=>e==="input"||e.endsWith(".input"),wEs=1;function SEs(e){return`${Number((e/1e3).toPrecision(3))}s`}function kEs(e,t){const n=Object.entries(e).filter(([i])=>!xEs(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,h=Math.max(d/a*100,wEs);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:h,durationMs:d,isRunning:c,isNestedEntry:bEs(i)}})}const OEs=({status:e})=>o.jsxs(st,{children:[e==="success"&&o.jsx(vEs,{className:"text-accent1"}),e==="failed"&&o.jsx(yEs,{className:"text-accent2"}),e==="suspended"&&o.jsx(yH,{className:"text-accent3"}),e==="waiting"&&o.jsx(cme,{className:"text-accent5"}),e==="skipped"&&o.jsx(cme,{className:"text-icon3"}),e==="running"&&o.jsx(Hs,{className:"text-accent6 animate-spin"})]}),CEs={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function PGt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const tst=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},_Es=e=>{const t=e;return xjt({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},EEs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=_Es(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:K("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(OEs,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(Vrn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(nq,{indicators:c,className:"shrink-0"})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:PGt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${CEs[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(Urn,{})})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:SEs(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function TEs(){const{steps:e}=I4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=DW(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);dwt(f,{enabled:!l});const h=kEs(e,a),p=h.some(m=>m.isRunning);return g.useEffect(()=>{if(!p)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[p]),g.useEffect(()=>{if(l||h.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,h.length]),h.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ge,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Ps,{className:K("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:h.map((m,v)=>o.jsx(EEs,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:tst(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:tst(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(Njt,{data:u.data,title:`${PGt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const jEs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=AZ(),s=XI(),a=o.jsx("div",{className:"flex h-full min-h-0 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(PFt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(gEs,{}),o.jsx(TEs,{})]})});return s?r?o.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:o.jsx(est,{})}):a:o.jsxs(_D,{className:"h-full min-h-0 w-full min-w-0",children:[o.jsx(Yx,{id:"workflow-graph",className:"min-w-0",children:a}),r?o.jsxs(o.Fragment,{children:[o.jsx(AN,{}),o.jsx(Yx,{id:"workflow-step-detail",minSize:300,maxSize:"60%",defaultSize:420,className:"min-w-0",children:o.jsx("div",{className:"border-border1 h-full min-h-0 overflow-hidden border-l",children:o.jsx(est,{})})})]}):null]})},nst=()=>{const{workflowId:e}=tr(),{data:t,isLoading:n,error:r}=HL(e);return r&&ms(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zs,{})}):r&&gs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{resource:"workflows"})}):o.jsx(U_e,{children:o.jsx(jEs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function NEs(e,t){if(e==null)return{};var n,r,s=BCt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function Iwe(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function IEs(e){if(Array.isArray(e))return Iwe(e)}function AEs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function REs(e,t){if(e){if(typeof e=="string")return Iwe(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Iwe(e,t):void 0}}function PEs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
694
|
+
]`,brt="flex min-h-0 flex-1 flex-col py-0";function vSs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:a,onPastedTextChange:i,validation:l,isImporting:c}){return o.jsxs(kl,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[o.jsxs(Sl,{variant:"pill",children:[o.jsx(kr,{value:"upload",children:"Upload file"}),o.jsx(kr,{value:"paste",children:"Paste JSON"})]}),o.jsx(Hr,{value:"upload",className:brt,children:n?o.jsx(wSs,{file:n,validation:l,onReplace:s,isImporting:c}):o.jsx(ySs,{onFileSelect:r,disabled:c})}),o.jsx(Hr,{value:"paste",className:brt,children:o.jsx(Bo,{"aria-label":"JSON items",className:"text-ui-sm min-h-[200px] flex-1 resize-none font-mono",placeholder:gSs,spellCheck:!1,value:a,onChange:u=>i(u.target.value),disabled:c})})]})}function ySs({onFileSelect:e,disabled:t}){const[n,r]=g.useState(!1),s=g.useCallback(c=>{const u=c.target.files?.[0];u&&e(u),c.target.value=""},[e]),a=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!0)},[]),i=g.useCallback(c=>{c.preventDefault(),c.stopPropagation(),r(!1)},[]),l=g.useCallback(c=>{if(c.preventDefault(),c.stopPropagation(),r(!1),t)return;const u=c.dataTransfer.files?.[0];u&&e(u)},[t,e]);return o.jsxs("div",{"data-testid":"json-dropzone",onDragOver:a,onDragLeave:i,onDrop:l,className:K("border-border1 bg-surface3 relative flex flex-1 flex-col items-center justify-center gap-3 rounded-lg border border-dashed px-4 py-6 text-center transition-colors","hover:border-accent1/50 hover:bg-accent1/5",n&&"border-accent1/50 bg-accent1/5",t&&"cursor-wait opacity-60"),children:[o.jsx("input",{type:"file",accept:".json,application/json","aria-label":"Choose a JSON file",onChange:s,disabled:t,className:"absolute inset-0 cursor-pointer opacity-0"}),o.jsx("div",{className:"border-border1 bg-surface2 text-neutral4 flex size-9 items-center justify-center rounded-md border",children:o.jsx(jI,{className:"size-4"})}),o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx("p",{className:"text-ui-md text-neutral6",children:"Drop a JSON file here"}),o.jsxs("p",{className:"text-ui-sm text-neutral4",children:["or ",o.jsx("span",{className:"underline",children:"choose a file"})," from your computer"]})]}),o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[".json · an array of items · up to ",zPe]})]})}function bSs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function xSs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function wSs({file:e,validation:t,onReplace:n,isImporting:r}){const s="rows"in t?t.rows:[],a="total"in t?t.total:0,i=s.slice(0,Goe);return o.jsxs("div",{"data-testid":"json-file-card",className:"border-border1 rounded-lg border",children:[o.jsxs("div",{className:"flex items-center gap-2 px-3 py-2",children:[o.jsx(OI,{className:"text-neutral4 size-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral6 min-w-0 flex-1 truncate font-mono",children:e.name}),o.jsx("span",{className:"text-ui-xs text-neutral3 shrink-0",children:bSs(e.size)}),o.jsx(ie,{icon:o.jsx(Ax,{}),variant:"ghost",size:"xs",onClick:n,disabled:r,children:"Replace"})]}),i.map(l=>o.jsxs("div",{className:"border-border1 grid grid-cols-[2rem_1fr_auto] items-center gap-2 border-t px-3 py-1.5",children:[o.jsx("span",{className:"text-ui-xs text-neutral3",children:l.index}),o.jsx("span",{className:"text-ui-sm text-neutral5 truncate font-mono",children:xSs(l.input)}),l.hasInput?l.hasGroundTruth?null:o.jsx(xt,{variant:"yellow",size:"xs",children:"no groundTruth"}):o.jsx(xt,{variant:"red",size:"xs",children:"no input"})]},l.index)),a>Goe&&o.jsxs("div",{className:"border-border1 text-ui-xs text-neutral3 border-t px-3 py-1.5",children:["+ ",a-Goe," more"]})]})}const SSs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function kSs({datasetId:e,datasetName:t,open:n,onOpenChange:r,onSuccess:s}){const[a,i]=g.useState("upload"),[l,c]=g.useState(null),[u,d]=g.useState(""),[f,h]=g.useState(null),[p,m]=g.useState(""),[v,y]=g.useState(!1),b=g.useRef(0),{batchInsertItems:x}=za(),w=a==="upload"?u:p,k=g.useMemo(()=>a==="upload"&&f?{status:"error",kind:"parse",message:f}:cws(w),[a,f,w]),O=g.useCallback(async I=>{const A=++b.current;if(!I.name.toLowerCase().endsWith(".json")){h("Only .json files are supported");return}if(I.size>BZt){h(`File is larger than ${zPe}`);return}try{const $=await SSs(I);if(A!==b.current)return;c({name:I.name,size:I.size}),d($),h(null)}catch{if(A!==b.current)return;h("Could not read the file")}},[]),_=g.useCallback(()=>{b.current++,c(null),d(""),h(null)},[]),T=g.useCallback(()=>{b.current++,i("upload"),c(null),d(""),h(null),m("")},[]),E=g.useCallback(()=>{v||(r(!1),setTimeout(T,150))},[v,r,T]),N=g.useCallback(async()=>{if(k.status==="ready"){y(!0);try{await x.mutateAsync({datasetId:e,items:k.items}),Be.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(T,150)}catch(I){Be.error(I instanceof Error?I.message:"Failed to import items")}finally{y(!1)}}},[k,x,e,s,r,T]);return o.jsx(vr,{open:n,onOpenChange:E,children:o.jsxs(yr,{className:"flex max-h-[90vh] w-[960px] max-w-[calc(100vw-2rem)] flex-col gap-0 p-0",children:[o.jsxs(br,{className:"border-border1 border-b px-4 py-4",children:[o.jsx(hr,{children:"Import into dataset"}),o.jsxs(Ms,{className:"text-ui-sm text-neutral3 not-sr-only",children:["Add items to"," ",t?o.jsx("code",{className:"bg-surface3 text-ui-xs text-neutral6 rounded px-1 font-mono",children:t}):"this dataset"," ","from a JSON file or paste them directly."]})]}),o.jsx(Mr,{className:"max-h-none min-h-0 flex-1 overflow-y-auto p-0",children:o.jsxs("div",{className:"divide-border1 grid divide-y md:grid-cols-[1.15fr_1fr] md:divide-x md:divide-y-0",children:[o.jsx("div",{className:"flex min-h-[360px] flex-col p-4",children:o.jsx(vSs,{tab:a,onTabChange:i,file:l,onFileSelect:O,onReplace:_,pastedText:p,onPastedTextChange:m,validation:k,isImporting:v})}),o.jsx("div",{className:"p-4",children:o.jsx(mSs,{})})]})}),o.jsxs(Bl,{className:"border-border1 items-center border-t px-4 py-3 sm:justify-between",children:[o.jsx(OSs,{validation:k}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(ie,{icon:o.jsx(qt,{}),onClick:E,disabled:v,children:"Cancel"}),o.jsxs(ie,{variant:"primary",onClick:N,disabled:k.status!=="ready"||v,children:[v&&o.jsx(Zt,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})]})})}function OSs({validation:e}){const t=K("size-1.5 shrink-0 rounded-full",e.status==="idle"&&"bg-neutral3",e.status==="ready"&&"bg-accent1",e.status==="error"&&"bg-accent2");let n;switch(e.status){case"idle":n="No items yet";break;case"ready":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.total})," item",e.total!==1?"s":""," ready",e.missingGroundTruthCount>0&&` · ${e.missingGroundTruthCount} without groundTruth`]});break;case"error":switch(e.kind){case"parse":n=`Not valid JSON — ${e.message}`;break;case"not-array":n="Top level must be an array of items";break;case"empty":n="The array has no items";break;case"too-large":n=`JSON is larger than ${zPe}`;break;case"missing-input":n=o.jsxs(o.Fragment,{children:[o.jsx("b",{className:"text-neutral6 font-medium",children:e.missingInputCount})," of ",e.total," item",e.total!==1?"s":""," ",e.missingInputCount!==1?"have":"has"," no"," ",o.jsx("code",{className:"font-mono",children:"input"})]});break}break}return o.jsxs("div",{role:"status",className:"text-ui-sm text-neutral4 flex min-w-0 items-center gap-2",children:[o.jsx("span",{className:t}),o.jsx("span",{className:"truncate",children:n})]})}function CSs(e){if(!(e instanceof HTMLElement))return!1;if(e.isContentEditable)return!0;const t=e.tagName;return t==="INPUT"||t==="TEXTAREA"||t==="SELECT"?!0:!!e.closest('[role="dialog"]:not([data-item-panel])')}function YZt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=a=>{a.defaultPrevented||CSs(a.target)||(a.key==="PageUp"?(a.preventDefault(),t?.()):a.key==="PageDown"?(a.preventDefault(),n?.()):a.key==="Escape"&&(a.preventDefault(),r()))};return window.addEventListener("keydown",s),()=>window.removeEventListener("keydown",s)},[e,t,n,r])}const KZt=g.createContext(null);function _Ss({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=zr(),i=xbt("/datasets/:datasetId/items/:itemId")?.params.itemId,l=g.useCallback(p=>{s(`/datasets/${e}/items/${encodeURIComponent(p)}`)},[s,e]),c=g.useCallback(()=>{s(`/datasets/${e}`)},[s,e]),u=g.useMemo(()=>i?t.findIndex(p=>p.id===i):-1,[t,i]),d=g.useMemo(()=>{if(u<=0)return;const p=t[u-1].id;return()=>l(p)},[u,t,l]),f=g.useMemo(()=>{if(u<0||u>=t.length-1)return;const p=t[u+1].id;return()=>l(p)},[u,t,l]);YZt({active:!!i,onPrevious:d,onNext:f,onClose:c});const h=g.useMemo(()=>({datasetId:e,items:t,isLoadingItems:n,currentItemId:i,openItem:l,close:c,goToPreviousItem:d,goToNextItem:f}),[e,t,n,i,l,c,d,f]);return o.jsx(KZt.Provider,{value:h,children:r})}function XZt(){const e=g.useContext(KZt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function ESs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:a}){const[i,l]=da(),{activeVersion:c}=UPe(i,l),[u,d]=g.useState(!1),[f,h]=g.useState(!1),[p,m]=g.useState(!1),[v,y]=g.useState([]),[b,x]=g.useState(!1),[w,k]=g.useState([]),[O,_]=g.useState(!1),[T,E]=g.useState([]),[N,I]=g.useState(0),[A,$]=g.useState(""),[z]=vOe(A,300),{data:D}=tv(e),{data:q=[],isLoading:H,setEndOfListElement:V,isFetchingNextPage:B,hasNextPage:W}=VC(e,z||void 0,c),{deleteItems:L}=za(),{currentItemId:G,openItem:M,close:R}=XZt(),F=X=>{G===X?R():M(X)},U=X=>{y(X),m(!0)},Q=X=>{k(X),x(!0)},te=X=>{x(X),X||(k([]),I(ne=>ne+1))},J=X=>{E(X),_(!0)},ee=async()=>{await L.mutateAsync({datasetId:e,itemIds:T}),Be.success(`Deleted ${T.length} items`),_(!1),E([]),I(X=>X+1)},re=X=>{m(!1),y([]),I(ne=>ne+1),n?.(X)},ae=X=>{m(X),X||(y([]),I(ne=>ne+1))};return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"grid h-full overflow-auto",children:o.jsx(fSs,{items:q,leftSlot:r,rightSlot:s,belowToolbarSlot:a,isLoading:H,onItemClick:F,featuredItemId:G,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>h(!0),onBulkDeleteClick:J,onCreateDatasetClick:U,onAddToDatasetClick:Q,datasetName:D?.name,clearSelectionTrigger:N,setEndOfListElement:V,isFetchingNextPage:B,hasNextPage:W,searchQuery:A,activeSearchQuery:z,onSearchChange:$,currentDatasetVersion:D?.version})}),o.jsx(iSs,{datasetId:e,open:u,onOpenChange:d}),o.jsx(kSs,{datasetId:e,datasetName:D?.name,open:f,onOpenChange:h}),o.jsx(Bws,{open:p,onOpenChange:ae,items:v,onSuccess:re}),o.jsx(Uws,{open:b,onOpenChange:te,items:w,currentDatasetId:e}),o.jsx(At,{open:O,onOpenChange:_,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Items"}),o.jsxs(At.Description,{children:["Are you sure you want to delete ",T.length," item",T.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:ee,children:L.isPending?"Deleting...":"Delete"})]})]})})]})}const xrt="__create_tag__";function TSs({datasetId:e}){const{data:t}=tv(e),{data:n}=Pm(),{updateDataset:r}=za(),[s,a]=g.useState(""),i=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>UZt(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const h=l.map(v=>({label:v,value:v,end:i.includes(v)?o.jsx(Fn,{"data-testid":"tag-applied",className:"size-3.5"}):void 0})),p=s.trim();return p.length>0&&!l.includes(p)&&!i.includes(p)?[{label:`Create "${p}"`,value:xrt},...h]:h},[l,i,s]),u=h=>{r.mutate({datasetId:e,tags:h},{onError:()=>Be.error("Failed to update tags")})},d=h=>{const p=h===xrt?s.trim():h;!p||i.includes(p)||u([...i,p])},f=h=>{u(i.filter(p=>p!==h))};return o.jsxs("div",{"data-testid":"dataset-tags-editor",className:"flex flex-wrap items-center gap-2",children:[i.map(h=>o.jsxs(IY,{value:h,size:"md",className:"gap-1 pr-1",children:[h,o.jsx("button",{type:"button","aria-label":`Remove tag ${h}`,disabled:r.isPending,onClick:()=>f(h),className:"cursor-pointer rounded-sm hover:opacity-70 disabled:opacity-50",children:o.jsx(qt,{className:"size-3"})})]},h)),o.jsx(Co,{options:c,value:void 0,onValueChange:d,onInputValueChange:a,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(TI,{className:"size-3.5"}),"Add tag"]}),searchPlaceholder:"Search or create tag...",emptyText:"Type to create a tag",variant:"ghost",size:"xs",className:"w-auto min-w-0",disabled:r.isPending})]})}function JZt({overrideEnabled:e,onOverrideEnabledChange:t,selectedScorerIds:n,onSelectedScorerIdsChange:r,disabled:s=!1}){return o.jsxs("div",{className:"grid gap-3",children:[o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx(bl,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),o.jsx(Dt,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),o.jsx("p",{className:"text-muted-foreground text-ui-sm",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?o.jsx(tK,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function jSs(e){if(!(e instanceof Error))return null;const t=e.message.match(/- ({.*})$/);if(!t)return null;try{const n=JSON.parse(t[1]);if(n.field&&Array.isArray(n.errors))return{field:n.field,errors:n.errors}}catch{}return null}function Qoe({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-ui-sm",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function NSs({datasetId:e,open:t,onOpenChange:n,onSuccess:r}){const[s,a]=g.useState("{}"),[i,l]=g.useState(""),[c,u]=g.useState(""),[d,f]=g.useState(""),[h,p]=g.useState(!1),[m,v]=g.useState([]),[y,b]=g.useState(""),[x,w]=g.useState(null),{addItem:k}=za(),O=()=>{a("{}"),l(""),u(""),f(""),p(!1),v([]),b(""),w(null)},_=$=>{O(),n($)},T=async $=>{$.preventDefault();let z;try{z=JSON.parse(s)}catch{Be.error("Input must be valid JSON");return}let D;if(i.trim())try{D=JSON.parse(i)}catch{Be.error("Ground Truth must be valid JSON");return}let q;if(c.trim())try{q=JSON.parse(c)}catch{Be.error("Expected Trajectory must be valid JSON");return}let H;if(d.trim())try{const B=JSON.parse(d);if(!Array.isArray(B)){Be.error("Tool Mocks must be a JSON array");return}H=B}catch{Be.error("Tool Mocks must be valid JSON");return}let V;if(y.trim())try{V=JSON.parse(y)}catch{Be.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:z,groundTruth:D,expectedTrajectory:q,toolMocks:H,scorerIds:h?m:void 0,requestContext:V}),Be.success("Item added successfully"),_(!1),r?.()}catch(B){const W=jSs(B);W?w(W):Be.error(`Failed to add item: ${B instanceof Error?B.message:"Unknown error"}`)}},E=$=>{a($),x?.field==="input"&&w(null)},N=$=>{l($),x?.field==="groundTruth"&&w(null)},I=$=>{f($),x?.field==="toolMocks"&&w(null)},A=()=>{_(!1)};return o.jsxs(_i,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(_i.Top,{children:"Add Item"}),o.jsxs(_i.Content,{children:[o.jsx(_i.Header,{children:o.jsx(_i.Heading,{children:"Add Item"})}),o.jsxs("form",{onSubmit:T,className:"grid gap-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Vr,{value:s,onChange:E,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(Qoe,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-ground-truth",children:"Ground Truth (JSON, optional)"}),o.jsx(Vr,{value:i,onChange:N,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="groundTruth"&&o.jsx(Qoe,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-trajectory",children:"Expected Trajectory (JSON, optional)"}),o.jsx(Vr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-tool-mocks",children:"Tool Mocks (JSON array, optional)"}),o.jsx(Vr,{value:d,onChange:I,showCopyButton:!1,className:"min-h-[200px]"}),x?.field==="toolMocks"&&o.jsx(Qoe,{field:"toolMocks",errors:x.errors})]}),o.jsx(JZt,{overrideEnabled:h,onOverrideEnabledChange:p,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"item-request-context",children:"Request Context (JSON, optional)"}),o.jsx(Vr,{value:y,onChange:b,showCopyButton:!1,className:"min-h-[200px]"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ie,{icon:o.jsx(qt,{}),type:"button",onClick:A,children:"Cancel"}),o.jsx(ie,{icon:o.jsx(Zr,{}),type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}const Pk=e=>JSON.stringify(e??null,null,2),ISs=[{key:"input",title:"Input",icon:o.jsx(zO,{}),value:e=>Pk(e.input)},{key:"groundTruth",title:"Ground Truth",icon:o.jsx(xy,{}),value:e=>Pk(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:o.jsx(eft,{}),value:e=>e.expectedTrajectory!=null?Pk(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:o.jsx(Vd,{}),value:e=>Pk(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:o.jsx(kH,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":Pk(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:o.jsx(nc,{}),value:e=>e.requestContext!=null?Pk(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:o.jsx(TI,{}),value:e=>Pk(e.metadata)}];function kwe({item:e,diff:t}){return o.jsxs(o.Fragment,{children:[o.jsxs(Bn,{children:[o.jsx(Bn.Key,{children:"Dataset Id"}),o.jsx(Bn.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),o.jsx(Bn.Key,{children:"Version"}),o.jsxs(Bn.Value,{children:["v",e.datasetVersion]}),o.jsx(Bn.Key,{children:"Created"}),o.jsx(Bn.Value,{children:xr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")}),o.jsx(Bn.Key,{children:"Updated"}),o.jsx(Bn.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?xr(new Date(e.updatedAt),"MMM d, yyyy h:mm aaa"):"n/a"})]}),o.jsx("div",{className:"mt-3 grid gap-3",children:ISs.map(n=>{const r=n.value(e),s=t?n.value(t.against):void 0;return r===void 0&&s===void 0?null:o.jsx(bn.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function Yoe({field:e,errors:t}){return t.length?o.jsx("div",{className:"mt-2 space-y-1",children:t.map((n,r)=>o.jsxs("p",{className:"text-destructive text-ui-sm",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function ASs({inputValue:e,setInputValue:t,groundTruthValue:n,setGroundTruthValue:r,metadataValue:s,setMetadataValue:a,trajectoryValue:i,setTrajectoryValue:l,toolMocksValue:c,setToolMocksValue:u,scorerOverrideEnabled:d,setScorerOverrideEnabled:f,selectedScorerIds:h,setSelectedScorerIds:p,requestContextValue:m,setRequestContextValue:v,validationErrors:y,onSave:b,onCancel:x,isSaving:w}){return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:"mb-4",children:o.jsxs("h3",{className:"text-header-sm flex items-center gap-2 font-medium",children:[o.jsx(Yu,{className:"h-5 w-5"})," Edit Item"]})}),o.jsxs("div",{className:"space-y-6",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Input (JSON) *"}),o.jsx(Vr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(Yoe,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Vr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(Yoe,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Expected Trajectory (JSON, optional)"}),o.jsx(Vr,{value:i,onChange:l,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Tool Mocks (JSON array, optional)"}),o.jsxs("p",{className:"text-muted-foreground text-ui-sm",children:["Ordered static mocks served in place of executing the tool. Each entry is"," ",o.jsx("code",{children:'{ "toolName", "args", "output" }'}),". Calling a mocked tool with non-matching args fails the item; unmocked tools run live."]}),o.jsx(Vr,{value:c,onChange:u,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="toolMocks"&&o.jsx(Yoe,{field:"toolMocks",errors:y.errors})]}),o.jsx(JZt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:h,onSelectedScorerIdsChange:p,disabled:w}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context (JSON, optional)"}),o.jsx(Vr,{value:m,onChange:v,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Metadata (JSON, optional)"}),o.jsx(Vr,{value:s,onChange:a,showCopyButton:!1,className:"min-h-[80px]"})]}),o.jsxs("div",{className:"flex gap-2 pt-4",children:[o.jsx(ie,{icon:o.jsx(Fn,{}),variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),o.jsx(ie,{icon:o.jsx(qt,{}),onClick:x,disabled:w,children:"Cancel"})]})]})]})}const RSs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function PSs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=Yf(),{data:l,isLoading:c}=Bm(),{data:u,isLoading:d}=tf(),f=e==="agent"?Object.entries(a??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="workflow"?Object.entries(l??{}).map(([v,y])=>({value:v,label:y.name??v})):e==="scorer"?Object.entries(u??{}).map(([v,y])=>({value:v,label:y.scorer?.config?.name??v})):[],h=e==="agent"&&i||e==="workflow"&&c||e==="scorer"&&d,p=v=>{t(v),r("")},m=e==="agent"?"Agent":e==="workflow"?"Workflow":"Scorer";return o.jsxs("div",{className:"grid grid-cols-2 gap-3",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Target Type"}),o.jsx(Co,{options:RSs,value:e,onValueChange:p,placeholder:"Select target type",searchPlaceholder:"Search types...",emptyText:"No types available",container:s})]}),e&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:m}),o.jsx(Co,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:h,container:s})]})]})}const $Ss=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function MSs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return xm(e)}catch(r){return console.error("Failed to parse requestContextSchema:",r),null}},[e]);return n?o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{children:"Request Context"}),o.jsx(_L,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-ui-md",children:"Failed to parse request context schema"})}function Koe({index:e,done:t,isLast:n,children:r}){return o.jsxs("li",{className:"flex gap-4",children:[o.jsxs("div",{className:"flex flex-col items-center",children:[o.jsx("span",{"aria-hidden":"true",className:K("flex size-6 shrink-0 items-center justify-center rounded-full border text-ui-xs font-medium",t?"border-accent1 bg-accent1 text-white":"border-border1 text-neutral3"),children:e}),!n&&o.jsx("span",{"aria-hidden":"true",className:"bg-border1 mt-2 w-px flex-1"})]}),o.jsx("div",{className:K("min-w-0 flex-1 space-y-3",!n&&"pb-4"),children:r})]})}function nK({initialDatasetId:e,initialDatasetVersion:t,initialScorerIds:n,initialTargetType:r,initialTargetId:s,initialName:a,initialDescription:i,open:l,onOpenChange:c,onSuccess:u}){const d=g.useRef(null),[f,h]=g.useState(a??""),[p,m]=g.useState(i??""),[v,y]=g.useState(e??""),[b,x]=g.useState(t??null),[w,k]=g.useState(r??""),[O,_]=g.useState(s??""),[T,E]=g.useState(n??null),[N,I]=g.useState({}),[A,$]=g.useState(""),{triggerExperiment:z}=za(),{data:D}=tv(v),{total:q}=VC(v,void 0,b),H=D?.requestContextSchema,V=D?.scorerIds??[],B=T===null&&V.length>0,W=T??V,L=!!(H&&Object.keys(H).length>0),G=!!(v&&w&&O&&f.trim()),M=z.isPending,R=[!f.trim()&&"name",!v&&"dataset",!O&&"target"].filter(Boolean),F=L?Object.values(N).some(ae=>ae!==void 0&&ae!==""):A.trim().length>0,U=ae=>{y(ae),x(null),E(n??null),I({})},Q=()=>{h(a??""),m(i??""),y(e??""),x(t??null),k(r??""),_(s??""),E(n??null),I({}),$("")},te=()=>{if(L){const ae=Object.entries(N).filter(([,X])=>X!==void 0&&X!=="");return ae.length>0?Object.fromEntries(ae):void 0}if(A.trim()){let ae;try{ae=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!ae||typeof ae!="object"||Array.isArray(ae))throw new Error("Request Context must be a JSON object");return ae}},J=async()=>{if(!v||!w||!O||!f.trim())return;let ae;try{ae=te()}catch(X){const ne=X instanceof Error?X.message:"Request Context must be valid JSON";fu.error(ne);return}try{const X=await z.mutateAsync({datasetId:v,name:f.trim(),description:p.trim()||void 0,targetType:w,targetId:O,scorerIds:W.length>0?W:void 0,version:b??void 0,requestContext:ae});fu.success("Experiment triggered successfully"),c(!1),u?.(X.experimentId),Q()}catch(X){const ne=X instanceof Error?X.message:"Failed to trigger experiment";fu.error(ne)}},ee=()=>{M||(c(!1),Q())},re=ae=>{(ae.metaKey||ae.ctrlKey)&&ae.key==="Enter"&&G&&!M&&(ae.preventDefault(),J())};return o.jsx(vr,{open:l,onOpenChange:ee,children:o.jsxs(yr,{ref:d,className:"w-[640px] max-w-[calc(100vw-2rem)] gap-0 p-0",onKeyDown:re,children:[o.jsxs(br,{className:"border-border1 border-b px-4 py-4",children:[o.jsx(hr,{children:"Run experiment"}),o.jsx(Ms,{className:"text-ui-sm text-neutral3 not-sr-only",children:"Pick a dataset, choose what to run it against, and optionally score the results."})]}),o.jsxs(Mr,{className:"max-h-[70vh] space-y-6 overflow-y-auto px-4 py-5",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"experiment-name",children:"Name *"}),o.jsx(In,{id:"experiment-name",value:f,onChange:ae=>h(ae.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:M})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{htmlFor:"experiment-description",children:"Description"}),o.jsx(Bo,{id:"experiment-description",value:p,onChange:ae=>m(ae.target.value),placeholder:"Enter experiment description (optional)",disabled:M,rows:2})]})]}),o.jsxs("ol",{className:"list-none",children:[o.jsxs(Koe,{index:1,done:!!v,children:[o.jsxs("div",{className:"grid grid-cols-[1fr_140px] gap-3",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Dataset"}),o.jsx(Q0t,{value:v,onValueChange:U,container:d})]}),v&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Dt,{children:"Version"}),o.jsx(QZt,{datasetId:v,value:b,onValueChange:x,container:d})]})]}),v&&q!==void 0&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[q," ",q===1?"item":"items"]})]}),o.jsxs(Koe,{index:2,done:!!O,children:[o.jsx(PSs,{targetType:w,setTargetType:k,targetId:O,setTargetId:_,container:d}),w&&!O&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:["Choose ",w==="agent"?"an":"a"," ",w," to run"]})]}),o.jsx(Koe,{index:3,done:W.length>0,isLast:!0,children:o.jsx(tK,{selectedScorers:W,setSelectedScorers:E,disabled:M,container:d,helperText:B?"Pre-filled from the dataset's default scorers.":"Scores are computed after each item runs."})})]}),o.jsxs(cc,{children:[o.jsxs(ql,{className:"text-ui-sm flex items-center gap-2",children:[o.jsx(wr,{className:"size-4"}),"Request Context (JSON, optional)",F&&o.jsx(xt,{size:"xs",variant:"blue",children:"set"})]}),o.jsx(Vl,{className:"pt-3",children:L?o.jsx(MSs,{requestContextSchema:H,onChange:I}):o.jsx(Vr,{value:A,onChange:$,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),o.jsxs(Bl,{className:"border-border1 items-center border-t px-4 py-4 sm:justify-between",children:[o.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"flex items-center gap-2",children:R.length===0?o.jsxs(o.Fragment,{children:[o.jsx(xt,{variant:"green",indicator:"dot",children:"Ready"}),o.jsxs("span",{className:"text-ui-xs text-neutral3",children:[q??0," items · ",w," · ",W.length," scorers"]})]}):o.jsxs(xt,{variant:"neutral",indicator:"dot",children:["Missing ",R.join(", ")]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ie,{icon:o.jsx(qt,{}),onClick:ee,disabled:M,children:"Cancel"}),o.jsx(ie,{variant:"primary",onClick:J,disabled:!G||M,children:M?o.jsxs(o.Fragment,{children:[o.jsx(Zt,{className:"h-4 w-4"}),"Running..."]}):o.jsxs(o.Fragment,{children:["Run",o.jsxs("span",{className:"ml-1 inline-flex gap-0.5","aria-hidden":"true",children:[o.jsx(Tg,{size:"xs",children:$Ss?"⌘":"Ctrl"}),o.jsx(Tg,{size:"xs",children:"↵"})]})]})})]})]})]})})}const eGt=g.createContext(null);function DSs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,children:i}){const l=zr(),u=xbt("/experiments/:experimentId/items/:itemId")?.params.itemId,d=g.useCallback(y=>{l(`/experiments/${e}/items/${encodeURIComponent(y)}`)},[l,e]),f=g.useCallback(()=>{l(`/experiments/${e}`)},[l,e]),h=g.useMemo(()=>u?r.findIndex(y=>y.itemId===u):-1,[r,u]),p=g.useMemo(()=>{if(h<=0)return;const y=r[h-1].itemId;return()=>d(y)},[h,r,d]),m=g.useMemo(()=>{if(h<0||h>=r.length-1)return;const y=r[h+1].itemId;return()=>d(y)},[h,r,d]);YZt({active:!!u,onPrevious:p,onNext:m,onClose:f});const v=g.useMemo(()=>({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,currentItemId:u,openItem:d,close:f,goToPreviousItem:p,goToNextItem:m}),[e,t,n,r,s,a,u,d,f,p,m]);return o.jsx(eGt.Provider,{value:v,children:i})}function tGt(){const e=g.useContext(eGt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function LSs({experimentId:e,experimentStatus:t,results:n,isLoading:r,setEndOfListElement:s,isFetchingNextPage:a,hasNextPage:i,selectedIds:l,onToggleSelect:c}){const{currentItemId:u,openItem:d,close:f}=tGt(),h=g.useMemo(()=>u?n.find(b=>b.itemId===u)?.id??null:null,[n,u]),{data:p}=Fy(e,t),m=g.useMemo(()=>{if(!p)return[];const b=new Set;for(const x of Object.values(p))for(const w of x)b.add(w.scorerId);return[...b].sort()},[p]),v=g.useCallback(b=>{const x=n.find(w=>w.id===b);x&&(x.itemId===u?f():d(x.itemId))},[n,u,f,d]),y=g.useMemo(()=>[{name:"itemId",label:"Item ID",size:"auto"},{name:"status",label:"Status",size:"auto"},{name:"input",label:"Input",size:"1fr"},{name:"tags",label:"Tags",size:"auto"},...m.map(b=>({name:b,label:b,size:"auto"}))],[m]);return o.jsx("div",{className:"h-full min-h-0 min-w-0 overflow-y-auto",children:o.jsx(KY,{results:n,isLoading:r,featuredResultId:h,onResultClick:v,columns:y,scoresByItemId:p,scorerIds:m,setEndOfListElement:s,isFetchingNextPage:a,hasNextPage:i,selectedIds:l,onToggleSelect:c})})}function FSs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${xr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function zSs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=sPe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${FSs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(tl.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(ad,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(ad,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}function nGt({children:e,className:t}){return o.jsx("div",{className:K("",t),children:e})}function BSs({date:e,className:t,withTime:n=!1}){const r=e?eSt(new Date(e)):!1,s=e?bL(new Date(e))?"Today":xr(new Date(e),"MMM dd"):"",a=e&&!r?xr(new Date(e),"yyyy"):"",i=e&&n?`${xr(new Date(e),"'at' h:mm aaa")}`:"";return o.jsxs("div",{className:K("truncate text-ui-md text-neutral2",t),children:[s," ",a," ",i]})}function qPe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function USs({columns:e,isSelectionActive:t,children:n}){return o.jsx("div",{className:K("sticky top-0 z-10 mb-2 rounded-lg bg-surface3 px-3"),children:o.jsx("div",{className:K("grid items-center gap-3 text-left text-ui-xs tracking-widest text-neutral3 uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:qPe(e)},children:n})})}function qSs({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function VSs({id:e,className:t,isShortened:n=!0}){const r=n?e.slice(0,8):e;return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral2",t),children:r})}function HSs({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function WSs({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function ZSs({children:e,className:t}){return o.jsx("label",{className:K("flex h-full w-14 items-center justify-center rounded-lg hover:bg-surface5",t),children:e})}function GSs({children:e,href:t,className:n,LinkComponent:r,tooltip:s}){const a=o.jsx(r,{href:t,className:K("flex w-full items-center justify-center gap-4 rounded-lg px-3 py-2 text-left","hover:bg-surface4",ts.colors,zI.visible,n),children:e});return s==null?a:o.jsxs(gn,{children:[o.jsx(hn,{render:a}),o.jsx(pn,{children:s})]})}function QSs({children:e,message:t,className:n,type:r}){return!e&&!t?null:o.jsx("div",{className:K("grid border-t border-border1",n),children:t?o.jsxs("p",{className:K("grid justify-center justify-items-center gap-2 p-5 text-center text-ui-md text-neutral3","[&>svg]:size-[1.5em] [&>svg]:opacity-75",{"[&>svg]:text-red-500":r==="error"}),children:[r==="error"?o.jsx(Ic,{}):o.jsx(_m,{})," ",t]}):e})}function YSs({isLoading:e,hasMore:t,setEndOfListElement:n,loadingText:r="Loading more data...",noMoreDataText:s="No more data to load"}){return n?o.jsxs("div",{ref:n,className:"text-ui-md text-neutral3 mt-4 flex justify-center opacity-50",children:[e&&r,!t&&!e&&s]}):null}function KSs({currentPage:e,hasMore:t,onNextPage:n,onPrevPage:r}){const s=typeof e=="number"&&e>0||t;return o.jsxs("div",{className:K("flex items-center justify-center gap-4 pt-4 text-ui-md text-neutral3"),children:[o.jsxs("span",{children:["Page ",o.jsx("b",{children:e?e+1:"1"})]}),s&&o.jsxs("div",{className:K("flex gap-4","[&>button]:flex [&>button]:items-center [&>button]:gap-2 [&>button]:rounded-md [&>button]:border [&>button]:border-border1 [&>button]:p-1 [&>button]:px-2 [&>button]:text-neutral4 [&>button]:transition-colors [&>button:hover]:text-neutral5","[&_svg]:size-[1em] [&_svg]:text-neutral3"),children:[typeof e=="number"&&e>0&&o.jsxs("button",{onClick:r,children:[o.jsx(Lc,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(Df,{})]})]})]})}function XSs({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function JSs({isSelected:e,children:t,columns:n}){return o.jsx("li",{className:K("flex overflow-hidden rounded-lg border border-transparent border-t-border1 py-[3px] pb-[2px] text-ui-md text-neutral5 first:border-t-transparent","[&:last-child>button]:rounded-b-lg","[&.selected-row]:border [&.selected-row]:border-dashed [&.selected-row]:border-white/50 [&.selected-row]:pr-[3px] [&.selected-row]:first:border-t","[&:has(+.selected-row)]:rounded-b-none [&:has(+.selected-row)]:border-b-transparent","[.selected-row+&]:rounded-t-none",ts.colors,{"selected-row":e,"grid px-3 gap-3":n}),style:{gridTemplateColumns:qPe(n)},children:t})}function e1s({item:e,isFeatured:t,onClick:n,children:r,columns:s,className:a,disabled:i,tooltip:l,...c}){const u=()=>{n?.(e?.id)},d=o.jsx("button",{...c,onClick:u,className:K("grid w-full items-center gap-3 rounded-lg px-3 text-left",ts.colors,zI.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!i},a),style:{gridTemplateColumns:qPe(s)},disabled:i,children:r});return l==null?d:o.jsxs(gn,{children:[o.jsx(hn,{render:d}),o.jsx(pn,{children:l})]})}function t1s(e){return e.charAt(0).toUpperCase()+e.slice(1)}function n1s({status:e}){return e?o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx("div",{className:K("relative flex h-full w-10 items-center justify-center bg-transparent"),children:o.jsx("div",{className:K("size-2 rounded-full",{"bg-green-600":["success","completed"].includes(e),"bg-red-700":["error","failed"].includes(e),"bg-yellow-500":["pending","running"].includes(e)})})})}),o.jsx(pn,{children:t1s(e)})]}):null}function r1s({children:e,isLoading:t,className:n}){return o.jsx("div",{className:K("truncate py-[0.6rem] text-ui-md text-neutral4",n),children:t?o.jsx("div",{className:"bg-surface4 h-4 animate-pulse rounded-md text-transparent select-none"}):e})}const wrt={latest:"Latest version",deleted:"Deleted in this version"};function s1s({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(nGt,{className:K("grid grid-cols-[1fr_auto] pl-1"),children:[o.jsxs("div",{className:K("grid gap-1 leading-none text-neutral3",{"text-neutral4":n}),children:[o.jsxs("strong",{className:"font-normal",children:["v. ",e]}),o.jsx("em",{className:K("text-ui-sm","font-normal","text-neutral2"),children:t?xr(new Date(t),"MMM d, yyyy HH:mm"):null})]}),(n||r)&&o.jsxs("div",{className:"flex items-center gap-1",children:[n&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":wrt.latest,children:o.jsx(xt,{variant:"blue",size:"sm",icon:o.jsx(xS,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":wrt.deleted,children:o.jsx(xt,{variant:"red",size:"sm",icon:o.jsx(zwe,{})})})]})]})}const Pp=Object.assign(XSs,{Header:USs,HeaderCol:qSs,Items:HSs,Scroller:WSs,Row:JSs,RowButton:e1s,Message:QSs,NextPageLoading:YSs,Pagination:KSs,Cell:nGt,TextCell:r1s,StatusCell:n1s,VersionCell:s1s,IdCell:VSs,DateCell:BSs,LinkCell:GSs,LabelCell:ZSs}),a1s=[{name:"id",label:"ID",size:"1fr"},{name:"versionA",label:"Version A",size:"1fr"},{name:"versionB",label:"Version B",size:"1fr"},{name:"compare",label:"Compare",size:"10rem"}],b7={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(Zr,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(Qnn,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(Fdt,{}),tooltip:"Same in both versions"}};function Xoe({red:e=!1,tooltip:t}){return o.jsxs(gn,{children:[o.jsx(hn,{render:o.jsx("span",{}),role:"img",tabIndex:0,"aria-label":t,className:"focus-visible:outline-neutral5/55 rounded focus-visible:outline-1 focus-visible:outline-offset-2 focus-visible:outline-solid",children:o.jsx(zwe,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(pn,{children:t})]})}function Joe({variant:e,version:t}){if(!e)return o.jsxs("span",{className:"text-ui-md text-neutral4",children:["v. ",t]});const{badgeVariant:n,icon:r,tooltip:s}=b7[e];return o.jsxs("div",{className:"grid grid-cols-[1fr_auto]",children:[t!==void 0&&o.jsxs("span",{className:"text-ui-md text-neutral4 flex min-w-16 justify-end pr-3",children:["v. ",t]}),o.jsx("span",{className:"inline-flex",role:"img","aria-label":s,children:o.jsx(xt,{variant:n,size:"xs",icon:r})})]})}function i1s(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function Srt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function o1s({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=ln(),l=t>n;return o.jsx(Pp,{children:o.jsx(Pp.Scroller,{children:o.jsx(Pp.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=i1s(u,d),h=Srt({otherVersionExists:d!==void 0,status:f,isNewer:l}),p=Srt({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(Pp.Row,{columns:a1s,children:[o.jsx(Pp.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(Pp.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?b7[h].tooltip:void 0,children:o.jsx(Joe,{variant:h,version:u.datasetVersion})}):o.jsx(Pp.Cell,{className:"flex items-center justify-center",children:o.jsx(Xoe,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(Pp.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?b7[p].tooltip:void 0,children:o.jsx(Joe,{variant:p,version:d.datasetVersion})}):o.jsx(Pp.Cell,{className:"flex items-center justify-center",children:o.jsx(Xoe,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(Pp.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:b7.same.tooltip,children:o.jsx(Joe,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(Pp.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?version=${u?.datasetVersion}&compare=${d?.datasetVersion}`,children:"Compare"}):o.jsx(Pp.Cell,{children:o.jsx(Xoe,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}const x7="targetType",Z$="targetId";function VPe({resetParams:e=[]}={}){const[t,n]=da(),r=e.join(","),s=t.get(x7),a=VZt(s)?s:"",i=a?t.get(Z$)??"":"",l=g.useCallback(d=>{n(f=>{const h=new URLSearchParams(f);d?h.set(x7,d):h.delete(x7),h.delete(Z$);for(const p of r.split(","))p&&h.delete(p);return h},{replace:!0})},[n,r]),c=g.useCallback(d=>{n(f=>{const h=new URLSearchParams(f);d?h.set(Z$,d):h.delete(Z$);for(const p of r.split(","))p&&h.delete(p);return h},{replace:!0})},[n,r]),u=g.useCallback(()=>l(""),[l]);return{targetType:a,targetId:i,setTargetType:l,setTargetId:c,clear:u}}function l1s(){const e=zr(),[t,n]=g.useState(""),[r,s]=g.useState("all"),[a,i]=g.useState("all"),{targetType:l,targetId:c,setTargetType:u,setTargetId:d,clear:f}=VPe(),{data:h=[],isLoading:p,error:m,isFetchingNextPage:v,hasNextPage:y,setEndOfListElement:b}=R2n({targetType:l,targetId:c}),{data:x,isLoading:w,error:k}=RW(),O=g.useMemo(()=>x?.experiments??[],[x?.experiments]),_=g.useMemo(()=>yws(h),[h]),T=p||w,E=m||k,N=()=>{e("/datasets/new")},I=o.jsx(nv,{owner:"dataset-list",children:o.jsx(Fx,{onClick:N,tooltip:"Create a dataset",variant:"ghost",size:"sm",children:"New dataset"})});if(E&&ms(E))return o.jsx(Qn,{children:o.jsx(zs,{})});if(E&&gs(E))return o.jsx(Qn,{children:o.jsx(Ts,{resource:"datasets"})});if(E)return o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load datasets",message:E.message})});if(h.length===0&&!T&&!l)return o.jsxs(Qn,{children:[I,o.jsx(bws,{onCreateClick:N})]});const A=r!=="all"||a!=="all"||t!==""||l!=="",$=()=>{n(""),s("all"),i("all"),f()};return o.jsxs(Bt,{height:"full",children:[I,o.jsx(Bt.TopArea,{children:o.jsx(Tws,{search:t,onSearchChange:n,experimentFilter:r,onExperimentFilterChange:s,tagFilter:a,onTagFilterChange:i,tagOptions:_,targetType:l,onTargetTypeChange:u,targetId:c,onTargetIdChange:d,onReset:$,hasActiveFilters:A})}),o.jsx(gws,{datasets:h,experiments:O,isLoading:T,search:t,experimentFilter:r,tagFilter:a,isFetchingNextPage:v,hasNextPage:y,setEndOfListElement:b})]})}function L8({children:e}){return o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:e})]})}function c1s(){const{datasetId:e}=tr(),t=zr(),[n,r]=da(),{activeVersion:s,handleVersionChange:a}=UPe(n,r),[i,l]=g.useState(!1),[c,u]=g.useState(!1),[d,f]=g.useState(!1),[h,p]=g.useState(!1),{data:m,error:v,isLoading:y}=tv(e),{data:b=[],isLoading:x}=VC(e,void 0,s),w=!x&&b.length===0;if(y)return null;if(v&&ms(v))return o.jsx(L8,{children:o.jsx(zs,{})});if(v&&gs(v))return o.jsx(L8,{children:o.jsx(Ts,{resource:"datasets"})});if(v&&R1(v)||!y&&!v&&!m)return o.jsx(L8,{children:o.jsx(mr,{iconSlot:o.jsx(Fg,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsx(ie,{as:xo,to:"/datasets",icon:o.jsx(Lc,{}),children:"Back to Datasets"})})});if(v)return o.jsx(L8,{children:o.jsx(Fs,{title:"Failed to load dataset",message:v instanceof Error?v.message:"An unexpected error occurred. Please try again."})});const k=_=>{t(`/experiments/${_}`)},O=()=>{t("/datasets")};return o.jsxs(_Ss,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"h-full",children:[o.jsx(Bt,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Bt.MainArea,{children:o.jsx(ESs,{datasetId:e,onAddItemClick:()=>u(!0),belowToolbarSlot:o.jsx(TSs,{datasetId:e}),leftSlot:o.jsx("span",{className:"text-ui-sm text-neutral3 mr-3 whitespace-nowrap",children:m?.createdAt?`Created ${xr(new Date(m.createdAt),"MMM d")}`:""}),rightSlot:o.jsxs(Wr,{children:[o.jsx(ie,{as:xo,to:`/experiments?dataset=${e}`,icon:o.jsx(Hwe,{}),children:"View experiments"}),o.jsx(QZt,{datasetId:e,value:s,onValueChange:a,currentVersion:m?.version,className:"w-36"}),w?o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx("span",{className:"cursor-not-allowed",children:o.jsx("div",{className:"pointer-events-none opacity-50",inert:!0,"aria-disabled":"true",children:o.jsx(ie,{variant:"primary",icon:o.jsx(oc,{}),children:"Run Experiment"})})})}),o.jsx(pn,{children:"Add items to the dataset before running an experiment"})]}):o.jsx(ie,{variant:"primary",onClick:()=>l(!0),icon:o.jsx(oc,{}),children:"Run Experiment"}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(d1,{})})}),o.jsxs(ot.Content,{align:"end",className:"w-48",children:[o.jsxs(ot.Item,{onSelect:()=>{t(`/datasets/${e}/edit`)},children:[o.jsx(Yu,{})," Edit Dataset"]}),o.jsxs(ot.Item,{onSelect:()=>p(!0),children:[o.jsx(mu,{})," Duplicate Dataset"]}),o.jsxs(ot.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(yi,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(qg,{})]}),o.jsx(nK,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:i,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx(NSs,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(qws,{open:h,onOpenChange:p,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx(Zws,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:O})]})}function ele({children:e}){return o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:e})]})}function u1s(){const{datasetId:e}=tr(),t=zr(),{data:n,error:r,isLoading:s}=tv(e),a=()=>{t(`/datasets/${e}`)};return s?null:r&&ms(r)?o.jsx(ele,{children:o.jsx(zs,{})}):r&&gs(r)?o.jsx(ele,{children:o.jsx(Ts,{resource:"datasets"})}):r||!n?o.jsx(ele,{children:o.jsx(Fs,{title:"Failed to load dataset",message:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[o.jsx(Ph,{className:"mb-6 p-0",children:o.jsxs(Ph.Column,{children:[o.jsxs(Ph.Title,{children:[o.jsx(Fg,{})," Edit dataset"]}),o.jsx(Ph.Description,{children:n.name})]})}),o.jsx(Uf,{className:"p-4",children:o.jsx(Wws,{dataset:{id:n.id,name:n.name,description:n.description||"",inputSchema:n.inputSchema,groundTruthSchema:n.groundTruthSchema,requestContextSchema:n.requestContextSchema,scorerIds:n.scorerIds},onSuccess:a,onCancel:a})})]})})]})}function rK({label:e,wide:t=!1,children:n}){return o.jsxs("div",{className:K("pointer-events-none absolute inset-0 z-50","grid transition-[grid-template-columns] duration-300 ease-in-out",t?"grid-cols-[1fr_4fr]":"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"pointer-events-none"}),o.jsx("div",{role:"dialog","data-item-panel":!0,"aria-label":e,className:"pointer-events-auto h-full min-h-0 min-w-0 overflow-y-auto",children:n})]})}function d1s(e){if(!(e instanceof Error))return null;const t=e.message.match(/- ({.*})$/);if(!t)return null;try{const n=JSON.parse(t[1]);if(n.field&&Array.isArray(n.errors))return{field:n.field,errors:n.errors}}catch{}return null}function f1s({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:a}=ln(),{updateItem:i,deleteItem:l}=za(),[c,u]=g.useState(!1),[d,f]=g.useState(""),[h,p]=g.useState(""),[m,v]=g.useState(""),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,O]=g.useState(t.scorerIds!==void 0),[_,T]=g.useState(t.scorerIds??[]),[E,N]=g.useState(""),[I,A]=g.useState(null),[$,z]=g.useState(!1);g.useEffect(()=>{t&&(f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),O(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),z(!1),A(null))},[t?.id]);const D=n.findIndex(M=>M.id===t.id),q=D>0?()=>r(n[D-1].id):void 0,H=D>=0&&D<n.length-1?()=>r(n[D+1].id):void 0,V=async()=>{let M;try{M=JSON.parse(d)}catch{Be.error("Input must be valid JSON");return}let R;if(h.trim())try{R=JSON.parse(h)}catch{Be.error("Ground Truth must be valid JSON");return}let F;if(m.trim())try{F=JSON.parse(m)}catch{Be.error("Metadata must be valid JSON");return}let U=null;if(y.trim())try{U=JSON.parse(y)}catch{Be.error("Expected Trajectory must be valid JSON");return}let Q;if(x.trim())try{const ee=JSON.parse(x);if(!Array.isArray(ee)){Be.error("Tool Mocks must be a JSON array");return}Q=ee}catch{Be.error("Tool Mocks must be valid JSON");return}else Q=[];let te;if(E.trim())try{te=JSON.parse(E)}catch{Be.error("Request Context must be valid JSON");return}let J;k?J=_:t.scorerIds!==void 0&&(J=null);try{const ee=await i.mutateAsync({datasetId:e,itemId:t.id,input:M,groundTruth:R,metadata:F,expectedTrajectory:U,toolMocks:Q,scorerIds:J,requestContext:te});Be.success("Item updated successfully"),O(ee.scorerIds!==void 0),T(ee.scorerIds??[]),u(!1),A(null)}catch(ee){const re=d1s(ee);re?A(re):Be.error(`Failed to update item: ${ee instanceof Error?ee.message:"Unknown error"}`)}},B=()=>{f(JSON.stringify(t.input,null,2)),p(t.groundTruth?JSON.stringify(t.groundTruth,null,2):""),v(t.metadata?JSON.stringify(t.metadata,null,2):""),b(t.expectedTrajectory?JSON.stringify(t.expectedTrajectory,null,2):""),w(t.toolMocks?.length?JSON.stringify(t.toolMocks,null,2):""),O(t.scorerIds!==void 0),T(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},W=M=>{f(M),I?.field==="input"&&A(null)},L=M=>{p(M),I?.field==="groundTruth"&&A(null)},G=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Be.success("Item deleted successfully"),z(!1),s()}catch(M){Be.error(`Failed to delete item: ${M instanceof Error?M.message:"Unknown error"}`)}};return o.jsxs(o.Fragment,{children:[o.jsxs(bn,{children:[o.jsxs(bn.Header,{children:[o.jsxs(bn.Heading,{children:["Item ",o.jsxs("b",{children:["# ",t.id.length>12?`${t.id.slice(0,12)}…`:t.id]})]}),o.jsxs(Wr,{className:"ml-auto shrink-0",children:[o.jsx(bn.NextPrevNav,{onPrevious:q,onNext:H,previousLabel:"Previous item",nextLabel:"Next item"}),!c&&o.jsxs(o.Fragment,{children:[o.jsx(ie,{as:a,href:`/datasets/${e}/items/${t.id}/versions?version=${t.datasetVersion}`,size:"md",tooltip:"Go to item versions history","aria-label":"Go to item versions history",children:o.jsx(Kwe,{})}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{size:"md","aria-label":"Actions menu",children:o.jsx(d1,{})})}),o.jsxs(ot.Content,{align:"end",className:"w-48",children:[o.jsxs(ot.Item,{onSelect:()=>u(!0),children:[o.jsx(Yu,{}),"Edit"]}),o.jsxs(ot.Item,{onSelect:()=>z(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(yi,{}),"Delete Item"]})]})]})]}),o.jsx(bn.CloseButton,{onClick:s,tooltip:"Close detail panel"})]})]}),o.jsx(bn.Content,{children:c?o.jsx(ASs,{inputValue:d,setInputValue:W,groundTruthValue:h,setGroundTruthValue:L,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:O,selectedScorerIds:_,setSelectedScorerIds:T,requestContextValue:E,setRequestContextValue:N,validationErrors:I,onSave:V,onCancel:B,isSaving:i.isPending}):o.jsx(kwe,{item:t})})]}),o.jsx(At,{open:$,onOpenChange:z,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Item"}),o.jsx(At.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(At.Footer,{children:[o.jsx(At.Cancel,{children:"Cancel"}),o.jsx(At.Action,{onClick:G,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function h1s(){const{itemId:e}=tr(),{datasetId:t,items:n,isLoadingItems:r,openItem:s,close:a}=XZt(),i=g.useMemo(()=>n.find(d=>d.id===e)??null,[n,e]),{data:l,isLoading:c}=HHt(i?"":t,!i&&e?e:""),u=i??l??null;return e?o.jsx(rK,{label:`Dataset item ${e}`,children:u?o.jsx("div",{className:"[&>section]:bg-surface3 flex h-full min-h-0 flex-col p-3 [&>section]:min-h-0 [&>section]:flex-1 [&>section]:rounded-lg [&>section]:shadow-lg",children:o.jsx(f1s,{datasetId:t,item:u,items:n,onItemChange:s,onClose:a})}):r||c?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Zt,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(mr,{iconSlot:o.jsx(Fg,{}),titleSlot:"Item not found",descriptionSlot:`No loaded item "${e}".`,actionSlot:o.jsx(ie,{icon:o.jsx(qt,{}),onClick:a,children:"Close"})})})})}):null}function krt(e,t){return{id:e.id,datasetId:t,datasetVersion:e.datasetVersion,input:e.input,groundTruth:e.groundTruth,expectedTrajectory:e.expectedTrajectory,toolMocks:e.toolMocks,scorerIds:e.scorerIds,requestContext:e.requestContext,metadata:e.metadata,createdAt:e.createdAt,updatedAt:e.updatedAt}}function Ort(e,t){return e.map(n=>{const r=typeof n.updatedAt=="string"?new Date(n.updatedAt):n.updatedAt;return{value:String(n.datasetVersion),label:o.jsxs("span",{className:"flex w-full items-center gap-2",children:[o.jsxs("span",{children:[o.jsxs("b",{children:["v. ",n.datasetVersion]})," · ",xr(r,"MMM d, HH:mm")]}),n.isLatest?o.jsx(xt,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function Crt(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function p1s(){const{datasetId:e,itemId:t}=tr(),[n,r]=da(),s=Crt(n.get("version")),a=Crt(n.get("compare")),i=n.get("view")==="diff",{data:l,error:c}=tv(e??""),{data:u,isLoading:d}=X0s(e??"",t??""),f=(s!=null?u?.find(_=>_.datasetVersion===s):void 0)??u?.[0],h=f?.datasetVersion??null,p=a!=null&&a!==h?a:null,{data:m,isLoading:v}=J0s(e??"",t??"",p??0,l?.version),y=(_,T)=>r(E=>{const N=new URLSearchParams(E);return T==null?N.delete(_):N.set(_,String(T)),N},{replace:!0});if(c&&ms(c))return o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zs,{})})});if(c&&gs(c))return o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{resource:"datasets"})})});if(!e||!t)return o.jsx(oa,{children:o.jsx(jx,{children:o.jsx("div",{className:"text-neutral4 py-5 text-center",children:o.jsx("p",{children:"Item not found."})})})});const b=!!(f&&m),x=i&&b,w=f?krt(f,e):null,k=m?krt(m,e):null,O=(f?.datasetVersion??0)<(m?.datasetVersion??0);return o.jsxs(oa,{children:[o.jsx(nv,{owner:"dataset-item-versions",children:b&&o.jsx(ie,{variant:"outline",onClick:()=>y("view",i?null:"diff"),children:i?o.jsxs(o.Fragment,{children:[o.jsx(qwe,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(btn,{})," Diff View"]})})}),o.jsx(Bt,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-4 md:grid-cols-2",children:[o.jsxs(Uf,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(fbe,{children:o.jsx(_rt,{name:"version",value:h!=null?String(h):"",options:Ort(u??[],p!=null?new Set([p]):void 0),onValueChange:_=>y("version",Number(_))})}),o.jsx(Kx,{className:"grid content-start gap-5 overflow-y-auto",children:d?o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Loading..."}):w?o.jsx(kwe,{item:w,diff:x&&k?{against:k,side:O?"a":"b"}:void 0}):o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Item data not available"})})]}),o.jsxs(Uf,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(fbe,{children:o.jsx(_rt,{name:"compare",value:p!=null?String(p):"",placeholder:"Select a version to compare",options:Ort(u??[],h!=null?new Set([h]):void 0),onValueChange:_=>y("compare",Number(_))})}),o.jsx(Kx,{className:"grid content-start gap-5 overflow-y-auto",children:p==null?o.jsx(mr,{className:"h-full",iconSlot:o.jsx(ome,{className:"text-neutral3 size-8"}),titleSlot:"No version selected",descriptionSlot:"Pick a version above to compare it with the one on the left."}):v?o.jsx("div",{className:"text-neutral4 text-ui-md",children:"Loading..."}):k?o.jsx(kwe,{item:k,diff:x&&w?{against:w,side:O?"b":"a"}:void 0}):o.jsxs("div",{className:"text-neutral4 text-ui-md",children:["Version ",p," not found"]})})]})]})})]})}function _rt({name:e,value:t,options:n,placeholder:r="Select version",onValueChange:s}){return o.jsxs("div",{className:"grid grid-cols-[auto_1fr] items-center gap-4",children:[o.jsx(Kwe,{className:"size-4 opacity-50"}),o.jsxs($a,{name:e,value:t,onValueChange:s,children:[o.jsx(Da,{"aria-label":e==="compare"?"Compare version":"Version",className:"w-full",children:o.jsx(Ma,{placeholder:r,className:"flex-1"})}),o.jsx(La,{children:n.map(a=>o.jsx(Pr,{value:a.value,disabled:a.disabled,children:a.label},a.value))})]})]})}function m1s(){const{datasetId:e}=tr(),[t]=da(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=zr(),{data:s,error:a}=tv(e??""),i=VC(e??"",void 0,n[0]??null),l=VC(e??"",void 0,n[1]??null),c=g.useMemo(()=>i.data??[],[i.data]),u=g.useMemo(()=>l.data??[],[l.data]),d=g.useMemo(()=>{const m=new Map;for(const v of[...c,...u])m.has(v.id)||m.set(v.id,{id:v.id,createdAt:new Date(v.createdAt)});return[...m.values()].sort((v,y)=>y.createdAt.getTime()-v.createdAt.getTime())},[c,u]),f=g.useMemo(()=>new Map(c.map(m=>[m.id,m])),[c]),h=g.useMemo(()=>new Map(u.map(m=>[m.id,m])),[u]);if(a&&ms(a))return o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zs,{})})});if(a&&gs(a))return o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(oa,{children:o.jsx(jx,{children:o.jsx("div",{className:"text-neutral4 py-5 text-center",children:o.jsx("p",{children:"Select at least two versions to compare."})})})});const p=(m,v)=>{r(`/datasets/${e}/versions?ids=${m},${v}`,{replace:!0})};return o.jsx(oa,{children:o.jsx("div",{className:"h-full overflow-hidden px-[3vw] pb-4",children:o.jsxs("div",{className:"mx-auto grid h-full max-w-[140rem] grid-rows-[auto_1fr] gap-4",children:[o.jsxs(Ph,{children:[o.jsxs(Ph.Column,{children:[o.jsxs(Ph.Title,{children:[o.jsx(Crn,{})," Compare Dataset Versions"]}),o.jsx(Ph.Description,{children:o.jsxs(Dd,{children:[o.jsx(Kwe,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(Ph.Column,{children:o.jsx(ie,{as:xo,to:`/datasets/${e}`,icon:o.jsx(Lc,{}),children:"Back to Dataset"})})]}),o.jsx(LM,{children:o.jsxs(tl,{children:[o.jsx(zSs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:p}),o.jsx(o1s,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h})]})})]})})})}function g1s(){const e=zr(),[t]=da(),n=t.get("targetType"),r=VZt(n)?n:void 0,s=t.get("targetIds"),a=r&&s?s.split(",").map(i=>i.trim()).filter(Boolean):void 0;return o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-4 py-5",children:[o.jsx(Ph,{className:"mb-6 p-0",children:o.jsxs(Ph.Column,{children:[o.jsxs(Ph.Title,{children:[o.jsx(Fg,{})," Create new dataset"]}),o.jsx(Ph.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Uf,{className:"p-4",children:o.jsx(zws,{targetType:r,targetIds:a,onSuccess:i=>{e(`/datasets/${i}`)},onCancel:()=>{e(-1)}})})]})})]})}function Owe({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-4",t),children:e})}function v1s(e){if(!e||e.length<2)return null;const t=[...e].sort((i,l)=>new Date(i.createdAt).getTime()-new Date(l.createdAt).getTime()),n=Math.floor(t.length/2),r=n,s=t.length-n;if(r===0)return null;const a=(s-r)/r*100;return{changePct:Math.round(a*10)/10,prevValue:String(r)}}function y1s({scorers:e,datasets:t,experiments:n,avgScore:r,prevAvgScore:s,totalNeedsReview:a,isLoadingScorers:i,isLoadingDatasets:l,isLoadingExperiments:c,isLoadingScores:u,isLoadingReview:d}){const f=e?Object.keys(e).length:void 0,h=t?.length,p=n?.length,m=r!=null&&s!=null&&s!==0?{changePct:Math.round((r-s)/s*100*10)/10,prevValue:String(s)}:null,v=v1s(n);return o.jsxs(o.Fragment,{children:[o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Total Scorers"}),i?o.jsx(Jr.Loading,{}):f!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(f)}),o.jsx(Jr.NoChange,{message:"Static count"})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Total Datasets"}),l?o.jsx(Jr.Loading,{}):h!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(h)}),o.jsx(Jr.NoChange,{message:"Static count"})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Avg Score"}),u?o.jsx(Jr.Loading,{}):r!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(r)}),m?o.jsx(Jr.Change,{changePct:m.changePct,prevValue:m.prevValue}):o.jsx(Jr.NoChange,{})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Total Experiments"}),c?o.jsx(Jr.Loading,{}):p!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(p)}),v?o.jsx(Jr.Change,{changePct:v.changePct,prevValue:v.prevValue}):o.jsx(Jr.NoChange,{})]}):o.jsx(Jr.NoData,{})]}),o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:"Needs Review"}),d?o.jsx(Jr.Loading,{}):a!=null?o.jsxs(o.Fragment,{children:[o.jsx(Jr.Value,{children:String(a)}),a>0?o.jsx(Jr.NoChange,{message:"items pending review"}):o.jsx(Jr.NoChange,{message:"All caught up"})]}):o.jsx(Jr.NoData,{})]})]})}function rGt({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:a}=za(),i=async()=>{try{await a.mutateAsync(n),Be.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Be.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return o.jsx(At,{open:e,onOpenChange:t,children:o.jsxs(At.Content,{children:[o.jsxs(At.Header,{children:[o.jsx(At.Title,{children:"Delete Experiment"}),o.jsxs(At.Description,{children:['Are you sure you want to delete "',r||n,'"? This will permanently delete the experiment, all its results, and the traces it produced, including their spans and any scores, feedback, metrics and logs attached to those traces. This action cannot be undone.']})]}),o.jsxs(At.Footer,{children:[o.jsx(ie,{icon:o.jsx(yi,{}),variant:"primary",size:"lg",onClick:i,disabled:a.isPending,children:a.isPending?"Deleting...":"Delete"}),o.jsx(At.Cancel,{children:"Cancel"})]})]})})}function sGt(e){const t=A0(e.id)??e.id;return e.name||`Experiment #${t}`}const b1s=60;function x1s({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:sGt(e)})}function w1s({experiment:e}){const t=e.description;if(!t)return o.jsx("span",{className:"text-neutral2",children:"—"});const n=o.jsx("span",{className:"text-neutral3 block min-w-0 truncate text-left",children:t});return t.length<=b1s?n:o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:n}),o.jsx(pn,{children:t})]})}function aGt(){const{data:e}=Yf(),{data:t}=Bm(),{data:n}=tf(),{data:r}=HA();return{agents:e,workflows:t,scorers:n,processors:r}}const iGt={agent:Pi,workflow:hc,scorer:D0,processor:nH},oGt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},S1s="External (caller-run)";function lGt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:a,targetId:i}=e;if(!i)return S1s;switch(a){case"agent":return t?.[i]?.name??i;case"workflow":return n?.[i]?.name??i;case"scorer":return r?.[i]?.scorer?.config?.name??i;case"processor":return s?.[i]?.name??i;default:return i}}function k1s({experiment:e,datasetName:t,review:n}){const r=e.status??"pending",s=e.succeededCount??0,a=e.failedCount??0,i=e.totalItems??0;return o.jsxs(o.Fragment,{children:[o.jsx(be.Cell,{children:o.jsx(x1s,{experiment:e})}),o.jsx(be.Cell,{children:o.jsx(w1s,{experiment:e})}),t!==void 0&&o.jsx(be.TextCell,{children:t}),o.jsx(be.Cell,{children:o.jsx(O1s,{experiment:e})}),o.jsx(be.Cell,{children:o.jsx(xt,{variant:VHt[r]??"neutral",indicator:"dot",children:rj[r]??r})}),o.jsx(be.TextCell,{className:"text-center",children:i}),o.jsx(be.TextCell,{className:"text-center",children:s}),o.jsx(be.TextCell,{className:"text-center",children:o.jsx("span",{className:a>0?"text-accent2":"",children:a})}),o.jsx(be.Cell,{className:"text-center",children:o.jsx(C1s,{review:n})}),o.jsx(be.TextCell,{children:Xps(e.createdAt)})]})}function O1s({experiment:e}){const t=aGt(),n=lGt(e,t),r=e.targetId?e.targetType:null,s=r?iGt[r]:null;return o.jsxs("span",{className:"flex min-w-0 items-center gap-1.5 [&_svg]:size-3.5 [&_svg]:shrink-0",children:[s&&o.jsx("span",{className:"text-neutral3 flex",role:"img","aria-label":oGt[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function C1s({review:e}){if(!e)return o.jsx("span",{className:"text-neutral2",children:"—"});const t=e.needsReview+e.complete;return t===0?o.jsx("span",{className:"text-neutral2",children:"—"}):e.needsReview>0?o.jsxs(xt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(xt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const cGt=`${Gps} ${Qps} ${Yps} ${Kps}`,Ert=`${cGt} auto`,_1s=[{label:Av.experiment},{label:Av.description},{label:Av.dataset},{label:Av.target},{label:Av.status},{label:Av.items,className:"text-center"},{label:Av.succeeded,className:"text-center"},{label:Av.failed,className:"text-center"},{label:Av.review,className:"text-center"},{label:Av.date}],uGt=e=>e.stopPropagation();function E1s({experiment:e,rowProps:t,onDelete:n,children:r}){const{paths:s,Link:a}=ln(),i=g.useRef(null);return o.jsxs(be.RowWrapper,{...t,onSelectRow:()=>i.current?.click(),children:[o.jsx(be.RowLink,{ref:i,colEnd:-2,to:s.experimentLink(e.id),LinkComponent:a,tabIndex:-1,onClick:uGt,children:r}),o.jsx(be.ActionsCell,{className:"pl-2",children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-xs",tooltip:"Delete experiment","aria-label":`Delete experiment ${e.name??e.id}`,onClick:l=>{l.stopPropagation(),n()},children:o.jsx(yi,{className:"size-4"})})})]})}function T1s({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all",selection:l,isFetchingNextPage:c,hasNextPage:u,setEndOfListElement:d}){const f=l!==void 0,h=g.useMemo(()=>{const O=new Map;return t?.forEach(_=>O.set(_.id,_.name)),O},[t]),p=g.useMemo(()=>[...e].sort((O,_)=>{const T=O.createdAt?new Date(O.createdAt).getTime():0;return(_.createdAt?new Date(_.createdAt).getTime():0)-T}),[e]),m=g.useMemo(()=>{const O=s.toLowerCase();return p.filter(_=>{const T=_.datasetId?h.get(_.datasetId)??"":"",E=!O||_.id.toLowerCase().includes(O)||(_.name??"").toLowerCase().includes(O)||T.toLowerCase().includes(O)||(_.targetId??"").toLowerCase().includes(O),N=a==="all"||_.status===a,I=i==="all"||_.datasetId===i;return E&&N&&I})},[p,s,h,a,i]),{containerRef:v,getRowProps:y}=ll({count:m.length,global:!0}),[b,x]=g.useState(null);if(r)return o.jsx(Uo,{columns:Ert});const w=f?`auto ${cGt}`:Ert,k=_1s.map(O=>o.jsx(be.TopCell,{className:O.className,children:O.label},O.label));return o.jsxs(be,{columns:w,scrollRef:v,children:[o.jsx(be.Top,{hasLeadingCell:f,children:f?o.jsxs(o.Fragment,{children:[o.jsx(be.TopCell,{children:" "}),o.jsx(be.TopCells,{colStart:2,children:k})]}):o.jsxs(o.Fragment,{children:[k,o.jsx(be.TopCell,{"aria-hidden":!0,children:null})]})}),m.map((O,_)=>{const T=O.datasetId?h.get(O.datasetId)??A0(O.datasetId)??O.datasetId:"—",E=o.jsx(k1s,{experiment:O,datasetName:T,review:n?.get(O.id)});if(!l)return o.jsx(E1s,{experiment:O,rowProps:y(_),onDelete:()=>x(O),children:E},O.id);const N=l.selectedExperimentIds.includes(O.id),I=()=>l.onToggleSelection(O.id);return o.jsxs(be.RowWrapper,{...y(_),onSelectRow:I,children:[o.jsx(be.SelectCell,{checked:N,onToggle:I,"aria-label":`Select experiment ${O.id}`}),o.jsx(be.RowButton,{colStart:2,featured:N,tabIndex:-1,onClick:uGt,children:E})]},O.id)}),o.jsx(be.NextPageLoading,{isLoading:c,hasMore:u,setEndOfListElement:d}),b&&o.jsx(rGt,{open:!0,onOpenChange:O=>{O||x(null)},experimentId:b.id,experimentName:b.name??void 0})]})}const j1s=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function N1s(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const F8={completed:CB.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},I1s=[{label:"Completed",color:F8.completed},{label:"Running",color:F8.running},{label:"Pending",color:F8.pending},{label:"Failed",color:F8.failed}];function A1s({experiments:e,datasets:t,isLoading:n,isError:r}){const{data:s,maxVal:a}=g.useMemo(()=>{if(!e||e.length===0)return{data:[],maxVal:0};const l=new Map;if(t)for(const f of t)l.set(f.id,f.name);const c=new Map;for(const f of e){const h=f.datasetId??"unknown";c.has(h)||c.set(h,{completed:0,running:0,pending:0,failed:0});const p=c.get(h),m=f.status;m in p&&p[m]++}let u=0;return{data:Array.from(c.entries()).map(([f,h])=>{const p=h.completed+h.running+h.pending+h.failed;return p>u&&(u=p),{name:l.get(f)??f.slice(0,12),values:[h.completed,h.running,h.pending,h.failed]}}),maxVal:u}},[e,t]),i=s.length>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(Wt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(Wt.Loading,{}):r?o.jsx(Wt.Error,{message:"Failed to load experiments data"}):o.jsx(Wt.Content,{children:i?o.jsx(gI,{data:s,segments:I1s,maxVal:a,fmt:l=>String(l)}):o.jsx(Wt.NoData,{message:"No experiments have been run yet"})})]})}const R1s=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"No Experiments yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Run an experiment from a dataset to evaluate ",o.jsx("br",{}),"your agents and workflows."]}),actionSlot:o.jsxs("div",{className:"flex flex-col items-center gap-2",children:[e&&o.jsx(ie,{variant:"primary",onClick:e,icon:o.jsx(oc,{}),children:"Run Experiment"}),o.jsx(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer",icon:o.jsx(Cs,{}),children:"Experiments Documentation"})]})})});function P1s({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,targetType:l,onTargetTypeChange:c,targetId:u,onTargetIdChange:d,onReset:f,hasActiveFilters:h,onRunClick:p,runTooltip:m="Run an experiment",onCompareClick:v,selection:y}){const b=y?.selectedCount===2&&!y.compareDisabledReason;return o.jsxs("div",{className:"min-h-form-md flex flex-wrap items-center gap-2",children:[o.jsx("div",{className:"max-w-120 min-w-48 flex-1",children:o.jsx(qc,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),o.jsxs(Wr,{children:[o.jsx(ad,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...j1s],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(ad,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),o.jsx(BPe,{targetType:l,targetId:u,onTargetTypeChange:c,onTargetIdChange:d}),f&&h&&o.jsx(ie,{onClick:f,size:"sm",variant:"default",icon:o.jsx(qt,{}),children:"Reset"})]}),y?o.jsxs(Wr,{className:"ml-auto shrink-0 whitespace-nowrap",children:[o.jsxs(Uh,{className:"gap-2",children:[o.jsxs(xt,{size:"sm",variant:y.selectedCount<2?"red":"green",children:[y.selectedCount," / 2"]}),"selected",y.compareDisabledReason&&o.jsxs("span",{className:"text-accent2",children:["· ",y.compareDisabledReason]})]}),o.jsx(ie,{variant:"primary",disabled:!b,onClick:y.onExecuteCompare,icon:o.jsx(ome,{}),children:"Compare Experiments"}),o.jsx(ie,{icon:o.jsx(qt,{}),onClick:y.onCancelSelection,children:"Cancel"})]}):o.jsxs(Wr,{className:"ml-auto shrink-0",children:[v&&o.jsx(ie,{onClick:v,tooltip:"Select two experiments of the same dataset to compare",icon:o.jsx(ome,{}),children:"Compare"}),p&&o.jsx(ie,{onClick:p,tooltip:m,variant:"primary",icon:o.jsx(oc,{}),children:"Run Experiment"})]})]})}const $1s={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},Trt=e=>e?e instanceof Date?e.toISOString():e:null,jrt=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},Nrt=(e,t,n)=>{if(!e)return $1s;const r=new Map;for(const s of n??[])r.set(s.scorerId,s.reason??null);return{present:!0,output:e.output,metadata:t?.metadata??null,comment:t?.comment??null,error:t?.error??null,startedAt:Trt(t?.startedAt),completedAt:Trt(t?.completedAt),scores:Object.entries(e.scores).map(([s,a])=>({scorerId:s,value:a,reason:r.get(s)??null})).sort((s,a)=>s.scorerId.localeCompare(a.scorerId))}},M1s=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:a,contenderScores:i})=>{if(!e)return[];const l=jrt(r),c=jrt(s);return e.items.map(u=>{const d=Nrt(u.results[t],l.get(u.itemId),a?.[u.itemId]),f=Nrt(u.results[n],c.get(u.itemId),i?.[u.itemId]),h={};for(const p of new Set([...d.scores,...f.scores].map(m=>m.scorerId))){const m=d.scores.find(y=>y.scorerId===p)?.value??null,v=f.scores.find(y=>y.scorerId===p)?.value??null;h[p]=m!=null&&v!=null?v-m:null}return{itemId:u.itemId,input:u.input,groundTruth:u.groundTruth,baseline:d,contender:f,deltas:h}})};function eO({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(cc,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(ql,{className:K("text-ui-md flex items-center gap-1.5 font-semibold [&>svg]:size-4",n==="negative"?"text-negative1":"text-neutral5"),children:[o.jsx(wr,{}),e]}),t]}),o.jsx(Vl,{role:"region","aria-label":e,children:s})]})}function Irt({label:e,value:t}){return t==null?null:o.jsx(eO,{title:e,defaultOpen:!1,children:o.jsx("pre",{className:"text-ui-sm text-neutral4 bg-surface3 max-h-40 overflow-auto rounded-md p-3 whitespace-pre-wrap",children:typeof t=="string"?t:JSON.stringify(t,null,2)})})}function dGt({delta:e}){const t=e>0?"text-positive1":e<0?"text-negative1":"text-neutral3";return o.jsxs("span",{className:K("inline-flex min-w-20 items-center gap-1 font-mono text-ui-md",t),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?o.jsx(Idt,{className:"size-3.5"}):e<0?o.jsx(WXt,{className:"size-3.5"}):null]})}function fGt({scorerId:e,value:t,delta:n,reason:r}){const{Link:s,paths:a}=ln();return o.jsxs("div",{className:"bg-surface2 grid gap-1 rounded-lg px-3 py-2",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4",children:[o.jsxs(s,{href:a.scorerLink(e),"aria-label":`Open ${e}`,className:"text-neutral5 text-ui-md flex min-w-0 items-center gap-1.5 font-medium hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(D0,{}),o.jsx("span",{className:"min-w-0 truncate",children:e})]}),o.jsxs("div",{className:"flex items-center gap-3",children:[o.jsx("span",{className:"text-neutral3 text-ui-md font-mono",children:t!=null?t.toFixed(2):"-"}),n!=null&&o.jsx(dGt,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-ui-md",children:r})]})}function Art(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function D1s(e){if(!e.startedAt||!e.completedAt)return null;const t=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return Number.isFinite(t)?`${(t/1e3).toFixed(2)}s`:null}const L1s="border-border1 bg-surface3 text-ui-md text-neutral4 max-h-[30vh] overflow-y-auto rounded-xl border p-4 font-mono break-all whitespace-pre-wrap dark:border-white/10 dark:bg-black/20";function Rrt({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],a=D1s(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(Zt,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 text-ui-md py-5 text-center",children:"Not present in this experiment"});const i=Art(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[a&&o.jsxs(gn,{children:[o.jsx(hn,{render:o.jsxs("p",{className:"text-neutral3 text-ui-md flex items-center justify-end gap-1.5 [&>svg]:size-3.5",children:[o.jsx(xS,{}),a]})}),o.jsx(pn,{children:"Run duration"})]}),s.error?o.jsx(eO,{title:"Error",tone:"negative",actions:o.jsx(Pa,{content:s.error.message}),children:o.jsx("p",{className:"border-negative1/40 bg-negative1/5 text-ui-md text-neutral4 rounded-xl border p-4 break-words",children:s.error.message})}):o.jsx(eO,{title:"Output",actions:o.jsx(Pa,{content:i}),children:o.jsx("pre",{className:L1s,children:i})}),s.scores.length>0&&o.jsx(eO,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx(fGt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(eO,{title:"Comment",defaultOpen:!1,children:o.jsx("p",{className:"text-neutral3 text-ui-md",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&o.jsx(eO,{title:"Metadata",defaultOpen:!1,children:o.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>o.jsxs("div",{className:"text-ui-md flex items-start justify-between gap-4",children:[o.jsx("dt",{className:"text-neutral3",children:l}),o.jsx("dd",{className:"text-neutral5 font-mono break-all",children:Art(c)})]},l))})})]})}const F1s={baseline:"Baseline",contender:"Contender"},z1s={baseline:"purple",contender:"blue"},B1s="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function Prt({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:a,paths:i}=ln(),l=F1s[e],c=t?A0(t.id)??t.id:null,u=t?.createdAt?new Date(t.createdAt):null,d=n??[];return o.jsxs("div",{className:"grid content-start gap-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(xt,{variant:z1s[e],size:"xs",children:l}),t&&o.jsx(ie,{as:a,size:"xs",href:`/experiments/${t.id}`,"aria-label":`Open experiment ${t.name||c}`,children:o.jsx("span",{className:"min-w-0 truncate",children:t.name||c})})]}),t&&o.jsxs("div",{className:"text-ui-sm text-neutral3 flex flex-wrap gap-x-4 gap-y-1",children:[t.name&&o.jsxs(Dd,{children:[o.jsx(A3,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(a,{href:i.agentLink(t.targetId),className:B1s,children:[o.jsx(Pi,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Dd,{children:[o.jsx(aft,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Dd,{children:[o.jsx(wH,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Dd,{children:[o.jsx(_7,{})," ",xr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(eO,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:h,delta:p})=>o.jsx(fGt,{scorerId:f,value:h,delta:r?p:null},f))})})]})}const oT="min-w-0 px-4 py-3";function U1s({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=ln(),{data:a,isLoading:i,error:l}=ews(e,t,n),{data:c}=w3(e,t),{data:u}=w3(e,n),d=c&&u&&c.datasetVersion!==u.datasetVersion,f=a?.baselineId??t,h=t===f?n:t,p=c?.id===f?c:u,m=c?.id===h?c:u,{data:v,isLoading:y}=S3({datasetId:e,experimentId:f,experimentStatus:p?.status}),{data:b,isLoading:x}=S3({datasetId:e,experimentId:h,experimentStatus:m?.status}),{data:w}=Fy(f,p?.status),{data:k}=Fy(h,m?.status),O=g.useMemo(()=>M1s({comparison:a,baselineId:f,contenderId:h,baselineResults:v,contenderResults:b,baselineScores:w,contenderScores:k}),[a,f,h,v,b,w,k]),_=g.useMemo(()=>[...new Set(O.flatMap(E=>Object.keys(E.deltas)))].sort(),[O]),T=g.useMemo(()=>{const E=(A,$)=>{const z=O.map(D=>D[A].scores.find(q=>q.scorerId===$)?.value).filter(D=>D!=null);return z.length>0?z.reduce((D,q)=>D+q,0)/z.length:null},N=_.map(A=>({scorerId:A,average:E("baseline",A),delta:null})),I=_.map(A=>{const $=E("baseline",A),z=E("contender",A);return{scorerId:A,average:z,delta:$!=null&&z!=null?z-$:null}});return{baseline:N,contender:I}},[O,_]);return i?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Zt,{})}):l?o.jsx(Nn,{variant:"warning",title:"Error loading comparison",children:o.jsx(Nn.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!a||a.items.length===0?o.jsx("div",{className:"text-neutral4 text-ui-md py-5 text-center",children:"No comparison data"}):o.jsx("div",{className:"grid gap-4",children:o.jsxs("div",{role:"table","aria-label":"Experiments comparison",className:"grid",children:[o.jsxs("div",{role:"row",className:"border-border1 grid border-y xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsx("div",{role:"columnheader","aria-label":"Items",className:`${oT} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:oT,children:o.jsx(Prt,{side:"baseline",experiment:p,summary:T.baseline,versionMismatch:d})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:oT,children:o.jsx(Prt,{side:"contender",experiment:m,summary:T.contender,versionMismatch:d,showDeltas:!0})})]}),O.map(E=>{const N=Object.entries(E.deltas).filter(([,I])=>I!=null&&I!==0);return o.jsxs("div",{role:"row","aria-label":E.itemId,className:"border-border1 grid border-b xl:grid-cols-[minmax(20rem,24rem)_1fr_1fr] xl:divide-x xl:divide-[var(--border1)]",children:[o.jsxs("div",{role:"cell",className:`${oT} grid content-start gap-1`,children:[o.jsx(r,{href:s.datasetItemLink(e,E.itemId),"aria-label":`Open item ${E.itemId}`,className:K("text-ui-sm flex items-start gap-1.5 font-mono break-all hover:underline [&>svg]:mt-0.5 [&>svg]:size-3.5 [&>svg]:shrink-0",E.baseline.present&&E.contender.present?"text-neutral4":"text-neutral1"),children:o.jsx("span",{className:"min-w-0",children:E.itemId})}),N.length>0&&o.jsx("span",{className:"flex flex-wrap items-center gap-2",children:N.map(([I,A])=>o.jsx(dGt,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx(Irt,{label:"Input",value:E.input}),o.jsx(Irt,{label:"Ground truth",value:E.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:oT,children:o.jsx(Rrt,{side:"baseline",row:E,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:oT,children:o.jsx(Rrt,{side:"contender",row:E,isLoading:x,showDeltas:!0})})]},E.itemId)})]})})}const q1s=100;function HPe(e,t){const n=Ge(),r={perPage:q1s};return t?.targetType&&(r.targetType=t.targetType),t?.targetId&&(r.targetId=t.targetId),mt({queryKey:["experiments",r],queryFn:()=>n.listExperiments(r)})}const hGt=(e,{experimentId:t,targetType:n,targetId:r})=>{const s=Ge(),{data:a,isLoading:i}=HPe(void 0,{targetType:n,targetId:r}),l=a?.experiments,c=t?l?.filter(d=>d.id===t):l,u=mt({queryKey:["review-items",e,t??"all",n||"all",r||"all",c?.map(d=>d.id)],queryFn:async()=>!c||c.length===0?[]:(await Promise.all(c.map(async f=>{if(!f.datasetId)return[];try{const{results:h}=await s.listDatasetExperimentResults(f.datasetId,f.id);return h.filter(p=>p.status===e).map(p=>({id:p.id,input:p.input,output:p.output,error:p.error,itemId:p.itemId,experimentId:p.experimentId,datasetId:f.datasetId??void 0,traceId:p.traceId??void 0,scores:p.scores?Object.fromEntries(p.scores.map(m=>[m.scorerId,m.score??0])):{},tags:p.tags??[],createdAt:p.createdAt,status:p.status,groundTruth:p.groundTruth,toolMockReport:p.toolMockReport}))}catch{return[]}}))).flat(),enabled:!!l,refetchOnWindowFocus:!1});return{...u,isLoading:u.isLoading||i}},V1s=(e={})=>hGt("needs-review",e),H1s=(e={})=>hGt("complete",e),W1s=[{name:"itemId",label:"Item ID",size:"auto"},{name:"input",label:"Input",size:"minmax(0,1fr)"},{name:"tags",label:"Tags",size:"auto"},{name:"scores",label:"Scores",size:"6rem"}],tle="__untagged__",nle="all",Z1s=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}];function G1s({datasetId:e,experimentId:t,targetType:n,targetId:r,featuredItemId:s,detailPanelVariant:a="inline",toolbarStart:i,toolbarEnd:l}){const c=Ge(),{paths:u}=ln(),{data:d}=tv(e??""),{data:f,isLoading:h}=V1s({experimentId:t,targetType:n,targetId:r}),{data:p,isLoading:m}=H1s({experimentId:t,targetType:n,targetId:r}),{updateExperimentResult:v}=za(),[y,b]=g.useState(s??null);g.useEffect(()=>{s!==void 0&&b(s)},[s]);const[x,w]=g.useState(null),[k,O]=g.useState(new Set),[_,T]=g.useState(!1),[E,N]=g.useState(!1),[I,A]=g.useState(!1),[$,z]=g.useState(""),[D,q]=g.useState(""),[H,V]=g.useState(""),[B,W]=g.useState([]),[L,G]=g.useState(!1),M=g.useMemo(()=>f??[],[f]),R=g.useMemo(()=>{const de=new Set;if(d?.tags)for(const _e of d.tags)de.add(_e);for(const _e of M)for(const Ae of _e.tags)de.add(Ae);return[...de].sort()},[d,M]),F=g.useCallback(de=>{!d||!e||(d.tags??[]).includes(de)},[d,e]),U=g.useMemo(()=>x?x===tle?M.filter(de=>de.tags.length===0):M.filter(de=>de.tags.includes(x)):M,[M,x]),Q=g.useMemo(()=>{const de=new Map;let _e=0;for(const $e of M){$e.tags.length===0&&_e++;for(const me of $e.tags)de.set(me,(de.get(me)??0)+1)}const Ae=[...de.entries()].sort(($e,me)=>me[1]-$e[1]).map(([$e])=>({value:$e,label:$e}));return[{value:nle,label:"All tags"},..._e>0?[{value:tle,label:"Untagged"}]:[],...Ae]},[M]),te=!!x||_,J=g.useCallback(()=>{w(null),T(!1),b(null)},[]),ee=g.useCallback((de,_e)=>{const Ae=M.find($e=>$e.id===de);Ae?.experimentId&&Ae?.datasetId&&v.mutate({datasetId:Ae.datasetId,experimentId:Ae.experimentId,resultId:Ae.id,tags:_e})},[M,v]),re=g.useCallback(de=>{const _e=M.find(Ae=>Ae.id===de);O(Ae=>{const $e=new Set(Ae);return $e.delete(de),$e}),y===de&&b(null),_e?.experimentId&&_e?.datasetId&&v.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,status:null})},[M,v,y]),ae=g.useCallback(de=>{const _e=M.find(Ae=>Ae.id===de);O(Ae=>{const $e=new Set(Ae);return $e.delete(de),$e}),y===de&&b(null),_e?.experimentId&&_e?.datasetId&&v.mutate({datasetId:_e.datasetId,experimentId:_e.experimentId,resultId:_e.id,status:"complete"})},[M,v,y]),X=g.useMemo(()=>{const de=_?p??[]:U;return!_||!x?de:x===tle?de.filter(_e=>_e.tags.length===0):de.filter(_e=>_e.tags.includes(x))},[_,p,U,x]),ne=_?m:!1,se=g.useMemo(()=>new Set(X.map(de=>de.id)),[X]),ce=g.useMemo(()=>[...k].filter(de=>se.has(de)).length,[k,se]),le=X.length>0&&ce===X.length,ve=g.useCallback(de=>{O(_e=>{const Ae=new Set(_e);return Ae.has(de)?Ae.delete(de):Ae.add(de),Ae})},[]),ye=g.useCallback(()=>{O(le?new Set:new Set(X.map(de=>de.id)))},[le,X]),Te=g.useCallback(de=>{for(const _e of k){const Ae=M.find($e=>$e.id===_e);Ae&&!Ae.tags.includes(de)&&ee(_e,[...Ae.tags,de])}},[M,k,ee]),Me=g.useCallback(de=>{for(const _e of k){const Ae=M.find($e=>$e.id===_e);Ae&&Ae.tags.includes(de)&&ee(_e,Ae.tags.filter($e=>$e!==de))}},[M,k,ee]),Ze=g.useCallback(()=>{for(const de of k)ae(de);O(new Set)},[k,ae]),Ve=g.useCallback(()=>{for(const de of k)re(de);O(new Set)},[k,re]),Ue=g.useCallback(()=>{z(""),A(!0)},[]),ke=g.useCallback(async()=>{if(!(!D||!H)){N(!0),A(!1);try{const de=M.filter(Ae=>k.has(Ae.id));if(de.length===0){N(!1);return}const _e=await c.clusterFailures({modelId:`${D}/${H}`,items:de.map(Ae=>({id:Ae.id,input:Ae.input,output:Ae.output??void 0,error:typeof Ae.error=="string"?Ae.error:Ae.error?String(Ae.error):void 0,scores:Ae.scores,existingTags:Ae.tags.length>0?Ae.tags:void 0})),availableTags:R.length>0?R:void 0,prompt:$||void 0});_e.proposedTags&&_e.proposedTags.length>0&&(W(_e.proposedTags.map(Ae=>({...Ae,accepted:!0}))),G(!0))}catch(de){console.error("Analysis failed:",de)}finally{N(!1)}}},[D,H,M,k,c,R,$]),Pe=g.useCallback(()=>{for(const de of B){if(!de.accepted)continue;const _e=M.find(Ae=>Ae.id===de.itemId);if(_e){const Ae=[...new Set([..._e.tags,...de.tags])];ee(_e.id,Ae)}}G(!1)},[B,M,ee]),Se=g.useCallback(de=>{b(_e=>_e===de?null:de)},[]),xe=g.useMemo(()=>y?X.find(de=>de.id===y)??null:null,[y,X]),{data:Ne}=Fy(xe?.experimentId??""),we=y?X.findIndex(de=>de.id===y):-1,Ie=we>0?()=>b(X[we-1].id):void 0,Qe=we>=0&&we<X.length-1?()=>b(X[we+1].id):void 0,qe=!_&&k.size>0,he=o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs(Wr,{children:[i,o.jsx(ad,{label:"Status",labelIsHidden:!0,name:"filter-status",options:Z1s,value:_?"completed":"review",onValueChange:de=>{T(de==="completed"),b(null)},className:"whitespace-nowrap"}),Q.length>1&&o.jsx(ad,{label:"Tags",labelIsHidden:!0,name:"filter-tags",options:Q,value:x??nle,onValueChange:de=>w(de===nle?null:de),className:"whitespace-nowrap"}),te&&o.jsx(ie,{onClick:J,size:"sm",variant:"default",icon:o.jsx(qt,{}),children:"Reset"})]}),(qe||l)&&o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[l,qe&&o.jsxs(o.Fragment,{children:[o.jsx(yZt,{size:"md",selectedCount:k.size,vocabulary:R,onApplyTag:Te,onRemoveTag:Me,onNewTag:de=>Te(de)}),o.jsx(ie,{variant:"primary",onClick:Ze,icon:o.jsx(kI,{}),children:"Mark as reviewed"}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{variant:"outline",disabled:E,"aria-label":"More actions",children:E?o.jsx(Zt,{className:"h-4 w-4"}):o.jsx(Ldt,{})})}),o.jsxs(ot.Content,{align:"end",children:[o.jsxs(ot.Item,{onSelect:Ue,children:[o.jsx(st,{size:"sm",children:o.jsx(SS,{})}),"Analyze"]}),o.jsx(ot.Separator,{}),o.jsxs(ot.Item,{onSelect:Ve,children:[o.jsx(st,{size:"sm",children:o.jsx(yi,{})}),"Remove from queue"]})]})]})]})]})]});if(h)return o.jsxs(o.Fragment,{children:[o.jsx(Bt.TopArea,{children:he}),o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(Zt,{className:"h-6 w-6"})})]});const fe=xe?o.jsx(CPe,{className:"h-full",result:xe,scores:Ne?.[xe.itemId],experimentLink:xe.experimentId?u.experimentItemLink(xe.experimentId,xe.itemId):void 0,tagVocabulary:R,onTagsChange:_?void 0:de=>{ee(xe.id,de);for(const _e of de)R.includes(_e)||F(_e)},onComplete:_?void 0:()=>ae(xe.id),onPrevious:Ie,onNext:Qe,onClose:()=>b(null)}):null;return o.jsxs(o.Fragment,{children:[o.jsx(Bt.TopArea,{children:he}),o.jsx(vr,{open:I,onOpenChange:A,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Analyze Items"}),o.jsx(Ms,{children:"Use an LLM to automatically suggest tags for the selected items."})]}),o.jsxs("div",{className:"space-y-4 py-2",children:[o.jsxs("div",{className:"grid grid-cols-2 gap-2",children:[o.jsxs("div",{children:[o.jsx(Dt,{className:"text-ui-sm mb-1 block",children:"Provider"}),o.jsx(sb,{value:D,onValueChange:q})]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"text-ui-sm mb-1 block",children:"Model"}),o.jsx(ab,{llmId:D,value:H,onValueChange:V})]})]}),o.jsxs(ge,{variant:"ui-xs",className:"text-neutral3",children:[k.size," item",k.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Dt,{className:"text-ui-sm",children:"Instructions (optional)"}),o.jsx(Bo,{value:$,onChange:de=>z(de.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"text-ui-sm mt-1"})]})]}),o.jsxs(Bl,{children:[o.jsx(ie,{icon:o.jsx(qt,{}),variant:"outline",onClick:()=>A(!1),children:"Cancel"}),o.jsxs(ie,{onClick:ke,disabled:!D||!H||E,children:[E?o.jsx(Zt,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(vr,{open:L,onOpenChange:G,children:o.jsxs(yr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(br,{children:[o.jsx(hr,{children:"Review Proposed Tags"}),o.jsxs(Ms,{children:[B.filter(de=>de.accepted).length," of ",B.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:B.map((de,_e)=>{const Ae=M.find($e=>$e.id===de.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!de.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ul,{checked:de.accepted,onCheckedChange:$e=>W(me=>me.map((Ee,De)=>De===_e?{...Ee,accepted:!!$e}:Ee))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 block truncate",children:Ae?typeof Ae.input=="string"?Ae.input.slice(0,100):JSON.stringify(Ae.input).slice(0,100):de.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:de.tags.map(($e,me)=>o.jsx(bZt,{tag:$e,onRename:Ee=>W(De=>De.map((Ke,Ot)=>Ot===_e?{...Ke,tags:Ke.tags.map((Re,Xe)=>Xe===me?Ee:Re)}:Ke)),onRemove:()=>W(Ee=>Ee.map((De,Ke)=>Ke===_e?{...De,tags:De.tags.filter((Ot,Re)=>Re!==me)}:De))},`${$e}-${me}`))}),de.reason&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:de.reason})]})]})},de.itemId)})}),o.jsxs(Bl,{children:[o.jsx(ie,{icon:o.jsx(qt,{}),variant:"outline",onClick:()=>G(!1),children:"Cancel"}),o.jsxs(ie,{icon:o.jsx(Fn,{}),onClick:Pe,disabled:B.filter(de=>de.accepted).length===0,children:["Accept ",B.filter(de=>de.accepted).length," proposals"]})]})]})}),o.jsxs(Bt.MainArea,{className:K("grid h-full min-h-0 w-full grid-cols-1 gap-4",a==="overlay"?"overflow-visible":"overflow-hidden",xe&&a==="inline"&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"min-h-0 w-full overflow-hidden",children:ne?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Zt,{className:"h-6 w-6"})}):X.length===0?o.jsx("div",{className:"flex h-full items-center-safe justify-center-safe overflow-auto py-8",children:o.jsx(mr,{iconSlot:o.jsx(Os,{className:"text-neutral3 h-8 w-8"}),titleSlot:_?"No completed reviews yet":"No items to review",descriptionSlot:_?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})}):o.jsx(KY,{results:X,isLoading:!1,featuredResultId:y,onResultClick:Se,columns:W1s,selectedIds:_?void 0:k,onToggleSelect:_?void 0:ve,onToggleSelectAll:_?void 0:ye})}),fe&&(a==="overlay"?o.jsx(rK,{label:`Review item ${xe?.id??""}`,children:o.jsx("div",{className:"[&>section]:bg-surface3 h-full min-h-0 p-3 [&>section]:rounded-lg [&>section]:shadow-lg",children:fe})}):fe)]})]})}const $rt={needsReview:"#facc15",complete:"#22c55e"},Q1s=[{label:"Needs Review",color:$rt.needsReview},{label:"Reviewed",color:$rt.complete}];function Y1s({reviewSummary:e,experiments:t,datasets:n,isLoading:r,isError:s}){const{data:a,maxVal:i,totalInPipeline:l}=g.useMemo(()=>{if(!e?.counts||!t)return{data:[],maxVal:0,totalInPipeline:0};const u=new Map;for(const m of t)u.set(m.id,m);const d=new Map;if(n)for(const m of n)d.set(m.id,m.name);let f=0,h=0;const p=[];for(const m of e.counts){const v=m.needsReview+m.complete;if(v===0)continue;h+=v,v>f&&(f=v);const y=u.get(m.experimentId),b=y?.datasetId?d.get(y.datasetId):void 0,x=b?`${b} · ${m.experimentId.slice(0,8)}`:m.experimentId.slice(0,8);p.push({name:x,values:[m.needsReview,m.complete]})}return{data:p,maxVal:f,totalInPipeline:h}},[e,t,n]),c=a.length>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(Wt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(Wt.Loading,{}):s?o.jsx(Wt.Error,{message:"Failed to load review data"}):o.jsx(Wt.Content,{children:c?o.jsx(gI,{data:a,segments:Q1s,maxVal:i,fmt:u=>String(u)}):o.jsx(Wt.NoData,{message:"No items have been sent to review yet"})})]})}function pGt(){const e=Ge();return mt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function K1s(e){const t=new Map;if(!e?.counts)return t;for(const n of e.counts)t.set(n.experimentId,{needsReview:n.needsReview,complete:n.complete,total:n.total});return t}function X1s(e){return e?.counts?e.counts.reduce((t,n)=>({needsReview:t.needsReview+n.needsReview,complete:t.complete+n.complete,inPipeline:t.inPipeline+n.needsReview+n.complete}),{needsReview:0,complete:0,inPipeline:0}):{needsReview:0,complete:0,inPipeline:0}}function J1s(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=tf(),{data:l,isLoading:c,error:u}=Pm(),{data:d,isLoading:f,error:h}=RW(),{data:p,isLoading:m,isError:v,error:y}=Eds(n),{data:b,isLoading:x,isError:w,error:k}=pGt(),O=l?.datasets,_=d?.experiments,T=g.useMemo(()=>X1s(b),[b]),E=i||u||h||y||k;return E&&ms(E)?o.jsx(Qn,{children:o.jsx(zs,{})}):E&&gs(E)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"evaluation"})}):E?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load evaluation data",message:E.message})}):o.jsxs(Bt,{width:"wide",height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsx(Bt.Row,{children:o.jsx(Bt.Column,{children:o.jsx(w4,{preset:e,onPresetChange:t,dateFrom:n.start,dateTo:n.end,onDateChange:(N,I)=>r(A=>I==="from"?{...A,start:N}:{...A,end:N})})})})}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsx(Owe,{children:o.jsx(y1s,{scorers:s,datasets:O,experiments:_,avgScore:p?.avgScore??null,prevAvgScore:p?.prevAvgScore??null,totalNeedsReview:T.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(eus,{summaryData:p?.summaryData??[],overTimeData:p?.overTimeData??[],scorerNames:p?.scorerNames??[],avgScore:p?.avgScore??null,isLoading:m,isError:v}),o.jsxs("div",{className:"grid grid-cols-1 gap-4 lg:grid-cols-2",children:[o.jsx(kws,{experiments:_,isLoading:f,isError:!!h}),o.jsx(A1s,{experiments:_,datasets:O,isLoading:f,isError:!!h})]}),o.jsx(Y1s,{reviewSummary:b,experiments:_,datasets:O,isLoading:x,isError:!!w})]})]})}const eks=100;function tks(e,t){const n=Ge(),{inView:r,setRef:s}=Yy(),a=t?.targetType||void 0,i=t?.targetId||void 0,l=ev({queryKey:e?["dataset-experiments",e,"infinite",{targetType:a,targetId:i}]:["experiments","infinite",{targetType:a,targetId:i}],queryFn:({pageParam:c})=>{const u={page:c,perPage:eks};return a&&(u.targetType=a),i&&(u.targetId=i),e?n.listDatasetExperiments(e,u):n.listExperiments(u)},initialPageParam:0,getNextPageParam:(c,u,d)=>{if(!(!c?.experiments?.length||!c.pagination?.hasMore))return d+1},select:c=>c.pages.flatMap(u=>u?.experiments??[])});return g.useEffect(()=>{r&&l.hasNextPage&&!l.isFetchingNextPage&&l.fetchNextPage()},[r,l]),{...l,setEndOfListElement:s}}function nks(){const[e,t]=g.useState(""),[n,r]=g.useState("all"),[s,a]=g.useState(!1),[i,l]=g.useState(!1),[c,u]=g.useState([]),d=zr(),[f,h]=da(),p=f.get("dataset")??"all",m=g.useCallback(J=>{h(ee=>{const re=new URLSearchParams(ee);return J==="all"?re.delete("dataset"):re.set("dataset",J),re},{replace:!0})},[h]),{targetType:v,targetId:y,setTargetType:b,setTargetId:x}=VPe(),{data:w,isLoading:k,error:O}=Pm(),{data:_,isLoading:T,error:E,isFetchingNextPage:N,hasNextPage:I,setEndOfListElement:A}=tks(p==="all"?void 0:p,{targetType:v,targetId:y}),{data:$}=pGt(),z=g.useMemo(()=>w?.datasets??[],[w?.datasets]),D=g.useMemo(()=>_??[],[_]),q=g.useMemo(()=>N1s(z),[z]),H=g.useMemo(()=>K1s($),[$]),V=k||T,B=E||O,W=J=>{u(ee=>ee.includes(J)?ee.filter(re=>re!==J):ee.length>=2?[ee[0],J]:[...ee,J])},L=()=>{u([]),l(!1)},{selectedIds:G,selectedDatasetIds:M}=g.useMemo(()=>{const J=new Map(D.map(re=>[re.id,re.datasetId])),ee=c.filter(re=>J.has(re));return{selectedIds:ee,selectedDatasetIds:new Set(ee.map(re=>J.get(re)))}},[D,c]),R=G.length===2&&M.size!==1?"not the same dataset":void 0,F=()=>{if(G.length!==2||R)return;const[J,ee]=G,[re]=M;if(!re)return;const ae=new URLSearchParams({dataset:re,baseline:J,contender:ee});d(`/experiments/compare?${ae.toString()}`)};if(B&&ms(B))return o.jsx(Qn,{children:o.jsx(zs,{})});if(E&&gs(E))return o.jsx(Qn,{children:o.jsx(Ts,{resource:"experiments"})});if(O&&gs(O))return o.jsx(Qn,{children:o.jsx(Ts,{resource:"datasets"})});if(B)return o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load experiments",message:B.message})});const U=o.jsx(nK,{open:s,onOpenChange:a,onSuccess:J=>{d(`/experiments/${J}`)}});if(D.length===0&&!V&&p==="all"&&!v)return o.jsxs(Qn,{children:[o.jsx(R1s,{onRunExperiment:()=>a(!0)}),U]});const Q=n!=="all"||p!=="all"||e!==""||v!=="",te=()=>{t(""),r("all"),h(J=>{const ee=new URLSearchParams(J);return ee.delete("dataset"),ee.delete(x7),ee.delete(Z$),ee},{replace:!0})};return o.jsxs(Bt,{height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsx(P1s,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:p,onDatasetFilterChange:m,datasetOptions:q,targetType:v,onTargetTypeChange:b,targetId:y,onTargetIdChange:x,onReset:te,hasActiveFilters:Q,onRunClick:()=>a(!0),onCompareClick:()=>l(!0),selection:i?{selectedCount:G.length,onExecuteCompare:F,onCancelSelection:L,compareDisabledReason:R}:void 0})}),o.jsx(T1s,{experiments:D,datasets:z,reviewByExperiment:H,isLoading:V,search:e,statusFilter:n,datasetFilter:p,isFetchingNextPage:N,hasNextPage:I,setEndOfListElement:A,selection:i?{selectedExperimentIds:G,onToggleSelection:W}:void 0}),U]})}function z8({experimentId:e}){const{Link:t,paths:n}=ln();return o.jsx(ie,{as:t,href:n.experimentLink(e),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function rks(){const[e,t]=da(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",a=w3(n,r),i=w3(n,s),l=a.isLoading||i.isLoading,c=a.error??i.error;return c&&ms(c)?o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zs,{})})}):c&&gs(c)?o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{resource:"experiments"})})}):!n||!r||!s?o.jsx(oa,{children:o.jsx(jx,{children:o.jsxs("div",{className:"text-neutral4 py-5 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"text-ui-md mt-2",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):l?null:c&&!R1(c)?o.jsx(oa,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Fs,{title:"Failed to load experiments",message:c.message})})}):c||!a.data||!i.data?o.jsx(oa,{children:o.jsx(jx,{children:o.jsxs("div",{className:"text-neutral4 py-5 text-center",children:[o.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),o.jsxs("p",{className:"text-ui-md mt-2 flex items-center justify-center gap-2",children:["One of",o.jsx(z8,{experimentId:r}),"and",o.jsx(z8,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(oa,{children:o.jsx(jx,{children:o.jsxs("div",{className:"grid w-full content-start",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-4 py-3",children:[o.jsxs("div",{className:"flex min-w-0 items-center gap-3",children:[o.jsx(ge,{as:"h1",variant:"ui-lg",className:"text-neutral6 font-medium",children:"Experiments comparison"}),o.jsxs("p",{className:"text-ui-sm text-neutral4 flex items-center gap-2",children:[o.jsx(z8,{experimentId:r}),"and",o.jsx(z8,{experimentId:s})]})]}),o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx(ie,{onClick:()=>t({dataset:n,baseline:s,contender:r}),icon:o.jsx(Ndt,{}),children:"Swap sides"})}),o.jsx(pn,{children:"Switch baseline and contender"})]})]}),o.jsx(U1s,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}function sks({selection:e}){const{selectedIds:t,selectedResults:n,tagVocabulary:r,isFlagging:s,isTagging:a}=e;if(t.size===0)return null;const i=s||a;return o.jsxs(Wr,{className:"whitespace-nowrap",children:[o.jsxs(ie,{variant:"outline",disabled:i,onClick:e.flagSelectedForReview,icon:o.jsx(l0,{}),children:["Flag ",t.size," to review"]}),o.jsx(QHt,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:i}),o.jsx(ie,{icon:o.jsx(qt,{}),variant:"ghost",onClick:e.clearSelection,children:"Clear"})]})}function mGt(e){const{data:t}=Fy(e.id,e.status);return g.useMemo(()=>{if(e.scorerIds?.length)return e.scorerIds;if(!t)return[];const n=new Set;for(const r of Object.values(t))for(const s of r)n.add(s.scorerId);return[...n].sort()},[e.scorerIds,t])}function rle({icon:e,typeLabel:t,subject:n,description:r,isLast:s=!1}){return o.jsxs("li",{className:"relative grid grid-cols-[auto_1fr] gap-x-2.5 pb-4 last:pb-0",children:[o.jsxs("div",{className:"flex flex-col items-center",children:[o.jsxs(gn,{children:[o.jsx(hn,{render:o.jsx("span",{className:"text-neutral3 flex size-5 shrink-0 items-center justify-center [&_svg]:size-3.5",role:"img","aria-label":t}),children:e}),o.jsx(pn,{children:t})]}),!s&&o.jsx("span",{"aria-hidden":!0,className:"bg-border1 mt-1 w-px flex-1"})]}),o.jsxs("div",{className:"grid min-w-0 gap-0.5",children:[o.jsx("div",{className:"text-ui-sm text-neutral5 flex min-h-5 items-center",children:n}),o.jsx("p",{className:"text-ui-xs text-neutral2",children:r})]})]})}const sle="text-neutral5 inline-flex min-w-0 items-center gap-1.5 hover:underline";function aks({experiment:e,className:t}){const{Link:n,paths:r}=ln(),s=aGt(),{scorers:a}=s,{data:i,isLoading:l}=tv(e.datasetId??""),c=mGt(e),u=e.targetType,d=e.targetId,f=lGt(e,s),h=(()=>{if(!d)return null;switch(u){case"agent":return r.agentLink(d);case"workflow":return r.workflowLink(d);case"scorer":return r.scorerLink(d);default:return null}})(),p=u&&iGt[u]||Pi,m=u&&oGt[u]||"Evaluation target";return o.jsxs("ol",{className:K("grid",t),children:[o.jsx(rle,{icon:o.jsx(eK,{}),typeLabel:"Dataset",description:`Each item will be passed to the ${m.toLowerCase()}`,subject:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:sle,children:[o.jsx("span",{className:"truncate",children:l?o.jsx(Et,{className:"h-4 w-28"}):i?.name??e.datasetId}),e.datasetVersion!=null&&o.jsxs("span",{className:"text-neutral3 shrink-0",children:["(v",e.datasetVersion,")"]})]}):o.jsx("span",{className:"text-neutral3",children:"No dataset"})}),o.jsx(rle,{icon:o.jsx(p,{}),typeLabel:m,description:"Its output is then scored",subject:h?o.jsx(n,{href:h,className:sle,children:o.jsx("span",{className:"truncate",children:f})}):o.jsx("span",{className:"text-neutral3 truncate",children:f})}),o.jsx(rle,{icon:o.jsx(D0,{}),typeLabel:"Scorers",description:"It gives a score by comparing ground truth",isLast:!0,subject:c.length===0?o.jsx("span",{className:"text-neutral3",children:"No scorer has produced a score yet"}):o.jsx("ul",{className:"grid min-w-0 gap-0.5",children:c.map(v=>{const y=a?.[v]?.scorer?.config?.name??v;return o.jsx("li",{className:"min-w-0",children:o.jsx(n,{href:r.scorerLink(v),className:sle,children:o.jsx("span",{className:"truncate",children:y})})},v)})})})]})}function lT({label:e,children:t}){return o.jsxs(o.Fragment,{children:[o.jsx(Bn.Key,{children:e}),o.jsx(Bn.Value,{className:"flex flex-wrap items-baseline justify-end gap-x-1.5 text-right",children:t})]})}function Mrt(e){if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1).replace(/\.0$/,"")}s`;const t=Math.floor(e/6e4),n=Math.round(e%6e4/1e3);if(t<60)return n>0?`${t}m ${n}s`:`${t}m`;const r=Math.floor(t/60),s=t%60;return s>0?`${r}h ${s}m`:`${r}h`}function iks({experiment:e,metrics:t}){const{data:n}=Fy(e.id,e.status),r=e.status==="running"||e.status==="pending",s=g.useMemo(()=>{if(!n)return;const c=Object.values(n).flat();if(c.length!==0)return c.reduce((u,d)=>u+d.score,0)/c.length},[n]),a=e.startedAt??e.createdAt,i=a?new Date(a):null,l=(()=>{if(e.status==="running")return"Running…";if(!e.startedAt||!e.completedAt)return"—";const c=new Date(e.completedAt).getTime()-new Date(e.startedAt).getTime();return c<0?"—":Mrt(c)})();return o.jsxs(Bn,{children:[o.jsx(lT,{label:"Avg score",children:s===void 0?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:s.toFixed(3)}),r&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(lT,{label:"Items",children:r?o.jsxs("span",{className:"text-neutral3",children:[(e.succeededCount??0)+(e.failedCount??0),"/",e.totalItems," items processed"]}):o.jsxs(o.Fragment,{children:[o.jsxs("span",{children:[e.totalItems," item",e.totalItems===1?"":"s"]}),(e.failedCount??0)>0&&o.jsxs("span",{className:"text-error",children:["· ",e.failedCount," errored"]})]})}),o.jsx(lT,{label:"Started",children:i?o.jsx("span",{title:e4n(i,{addSuffix:!0}),children:xr(i,"MMM d, h:mm a")}):o.jsx("span",{children:"—"})}),o.jsx(lT,{label:"Duration",children:o.jsx("span",{children:l})}),t?.isEnabled&&o.jsxs(o.Fragment,{children:[o.jsx(lT,{label:"Tokens",children:t.data?.totalTokens==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:ao(t.data.totalTokens)}),t.data.estimatedCost!=null&&o.jsxs("span",{className:"text-neutral3",children:["· ",Ud(t.data.estimatedCost,t.data.costUnit)]}),r&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(lT,{label:"Latency (avg)",children:t.data?.avgAgentDurationMs==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsx("span",{children:Mrt(Math.round(t.data.avgAgentDurationMs))})})]})]})}function oks({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=ln(),{data:s}=tf(),a=g.useMemo(()=>{if(!e)return[];const i={};for(const l of Object.values(e))for(const c of l)i[c.scorerId]||(i[c.scorerId]={sum:0,count:0}),i[c.scorerId].sum+=c.score,i[c.scorerId].count++;return Object.entries(i).map(([l,{sum:c,count:u}])=>({scorerId:l,avg:c/u})).sort((l,c)=>l.scorerId.localeCompare(c.scorerId))},[e]);if(a.length===0){const i=t==="running"||t==="pending",l=e!==void 0;let c,u;return i?(c="Experiment in progress",u="Summary metrics will appear here once the experiment completes."):l?(c="No scorers configured",u="Add scorers when triggering an experiment to evaluate results and see summary metrics here."):(c="Loading scores",u="Fetching scorer results…"),o.jsxs("div",{className:"text-ui-sm text-neutral3 flex items-center gap-2",children:[o.jsx(Uy,{className:"text-neutral3 size-4 shrink-0"}),o.jsx("span",{className:"text-neutral4",children:c}),o.jsx("span",{className:"truncate",children:u})]})}return o.jsx("div",{className:"flex flex-col gap-2",children:a.map(({scorerId:i,avg:l})=>{const c=s?.[i]?.scorer?.config?.name??i;return o.jsxs(Jr,{className:"min-w-0 p-3",children:[o.jsxs(n,{href:r.scorerLink(i),className:"text-ui-sm text-neutral3 [&>svg]:text-neutral3 flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3 [&>svg]:shrink-0",children:[o.jsxs(gn,{children:[o.jsx(hn,{render:o.jsx(D0,{role:"img","aria-label":"Scorer"})}),o.jsx(pn,{children:"Scorer"})]}),o.jsx("span",{className:"truncate",children:c})]}),o.jsxs("strong",{className:"text-ui-md text-neutral4 font-semibold",children:[l.toFixed(3),o.jsx("span",{className:"text-ui-sm text-neutral3 ml-1.5 font-normal",children:"avg score"})]})]},i)})})}function ale({title:e,children:t}){return o.jsxs("section",{className:"grid gap-3",children:[o.jsx("h2",{className:"text-ui-md text-neutral2 tracking-widest uppercase",children:e}),t]})}function lks({experiment:e,metrics:t,className:n}){const{Link:r,paths:s}=ln(),{data:a}=Fy(e.id,e.status),i=e.agentVersion&&e.targetType==="agent"&&e.targetId?`${s.agentLink(e.targetId)}/editor?version=${encodeURIComponent(e.agentVersion)}`:null;return o.jsxs(Uf,{as:"aside","aria-label":"Experiment details",className:K("grid content-start gap-5 p-5",n),children:[o.jsxs(ale,{title:"Pipeline",children:[o.jsx(aks,{experiment:e}),e.agentVersion&&o.jsxs(Bn,{children:[o.jsx(Bn.Key,{children:"Version"}),i?o.jsx(Bn.ValueLink,{href:i,as:r,children:e.agentVersion}):o.jsx(Bn.Value,{children:e.agentVersion})]})]}),o.jsx(ale,{title:"Run",children:o.jsx(iks,{experiment:e,metrics:t})}),o.jsx(ale,{title:"Scorers",children:o.jsx(oks,{scoresByItemId:a,experimentStatus:e.status})})]})}function cks({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[a,i]=g.useState(e.description??""),{updateExperiment:l}=za(),c=!!r.trim()&&!l.isPending,u=async d=>{if(d.preventDefault(),!(!c||!e.datasetId))try{await l.mutateAsync({datasetId:e.datasetId,experimentId:e.id,name:r.trim(),description:a.trim()}),Be.success("Experiment renamed"),n(!1)}catch(f){Be.error(`Failed to rename experiment: ${f instanceof Error?f.message:"Unknown error"}`)}};return o.jsx(vr,{open:t,onOpenChange:n,children:o.jsxs(yr,{className:"max-w-md",children:[o.jsx(br,{children:o.jsx(hr,{children:"Rename Experiment"})}),o.jsx(Mr,{children:o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"rename-experiment-name",children:"Name *"}),o.jsx(In,{id:"rename-experiment-name",value:r,onChange:d=>s(d.target.value),placeholder:"Enter experiment name",autoFocus:!0})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Dt,{htmlFor:"rename-experiment-description",children:"Description"}),o.jsx(In,{id:"rename-experiment-description",value:a,onChange:d=>i(d.target.value),placeholder:"Enter experiment description (optional)"})]}),o.jsxs("div",{className:"flex justify-end gap-2 pt-4",children:[o.jsx(ie,{icon:o.jsx(qt,{}),type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(ie,{icon:o.jsx(Fn,{}),type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}const uks=["agent","workflow","scorer"];function dks({experiment:e}){const[t,n]=g.useState(!1),r=zr(),{paths:s}=ln(),a=mGt(e),i=uks.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsx(ie,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",icon:o.jsx(oc,{}),children:"Rerun"}),t&&o.jsx(nK,{open:!0,onOpenChange:n,initialDatasetId:e.datasetId,initialDatasetVersion:e.datasetVersion??void 0,initialTargetType:i,initialTargetId:e.targetId,initialScorerIds:a,initialName:e.name??void 0,initialDescription:e.description??void 0,onSuccess:l=>{r(s.experimentLink(l))}},a.join(","))]})}function fks({experiment:e,onDeleteClick:t,children:n}){const{Link:r}=ln(),[s,a]=g.useState(!1),i=!!e.datasetId,l=i||!!t;return o.jsxs(Bt.TopArea,{children:[o.jsxs(Bt.Row,{className:"items-center justify-start gap-2",children:[o.jsxs(Wr,{className:"whitespace-nowrap",children:[o.jsx(dks,{experiment:e}),o.jsx(ie,{as:r,to:$3t(e.id),icon:o.jsx(l0,{}),children:"Review queue"}),l&&o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{size:"lg","aria-label":"Experiment actions menu",children:o.jsx(d1,{})})}),o.jsxs(ot.Content,{align:"start",className:"w-48",children:[i&&o.jsxs(ot.Item,{onSelect:()=>a(!0),children:[o.jsx(Yu,{})," Rename Experiment"]}),t&&o.jsxs(ot.Item,{onSelect:t,className:"text-red-500 focus:text-red-400",children:[o.jsx(yi,{})," Delete Experiment"]})]})]})]}),n]}),s&&o.jsx(cks,{experiment:e,open:!0,onOpenChange:a})]})}const hks=({experimentId:e,experimentStatus:t})=>{const n=Ge(),{supportsMetrics:r}=NY(),s=!!e&&r,i=mt({queryKey:["experiment-metrics",e],enabled:s,refetchInterval:t==="running"||t==="pending"?2e3:!1,queryFn:async()=>{if(!e)throw new Error("experimentId is required");const l={experimentId:e},[c,u,d]=await Promise.all([n.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"avg",filters:l}),n.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:l})]);return{totalTokens:c.value??null,estimatedCost:c.estimatedCost??null,costUnit:c.costUnit??null,avgAgentDurationMs:u.value??null,agentRuns:d.value??null}}});return{data:i.data,isLoading:i.isLoading,isEnabled:s}};function pks({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=za();return{addTag:g.useCallback(async(i,l)=>{const c=l.filter(d=>!(d.tags??[]).includes(i));if(n||c.length===0)return;r(!0);let u=0;try{u=(await Promise.allSettled(c.map(f=>s.mutateAsync({datasetId:e,experimentId:t,resultId:f.id,tags:[...f.tags??[],i]})))).filter(f=>f.status==="fulfilled").length}finally{r(!1)}u>0?Be(`Tag "${i}" added to ${u} result${u>1?"s":""}`):Be.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function gGt(e,t){const{data:n}=tv(e);return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}function mks({datasetId:e,experimentId:t,results:n}){const[r,s]=g.useState(new Set),[a,i]=g.useState(!1),{updateExperimentResult:l}=za(),{addTag:c,isPending:u}=pks({datasetId:e,experimentId:t}),d=gGt(e,n),f=g.useMemo(()=>n.filter(y=>r.has(y.id)),[n,r]),h=g.useCallback(y=>{s(b=>{const x=new Set(b);return x.has(y)?x.delete(y):x.add(y),x})},[]),p=g.useCallback(()=>s(new Set),[]),m=g.useCallback(async()=>{if(a||r.size===0)return;i(!0);const y=new Set;try{for(const b of r)try{await l.mutateAsync({datasetId:e,experimentId:t,resultId:b,status:"needs-review"}),y.add(b)}catch{}}finally{i(!1)}y.size>0&&(s(b=>{const x=new Set(b);for(const w of y)x.delete(w);return x}),Be(`${y.size} result${y.size>1?"s":""} flagged for review`))},[e,t,a,r,l]),v=g.useCallback(y=>c(y,f),[c,f]);return{selectedIds:r,selectedResults:f,toggleSelect:h,clearSelection:p,flagSelectedForReview:m,isFlagging:a,addTagToSelected:v,isTagging:u,tagVocabulary:d}}const gks=[];function B8({children:e}){return o.jsxs(Bt,{height:"full",children:[o.jsx("div",{}),o.jsx(Bt.MainArea,{isCentered:!0,children:e})]})}function vks(){const{experimentId:e}=tr(),t=zr(),[n,r]=g.useState(!1),{data:s,isLoading:a}=RW(),l=s?.experiments?.find(w=>w.id===e)?.datasetId??"",{data:c,isLoading:u,error:d}=w3(l,e??""),{data:f,isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v}=S3({datasetId:l,experimentId:e??"",experimentStatus:c?.status}),y=hks({experimentId:e,experimentStatus:c?.status}),b=mks({datasetId:l,experimentId:e??"",results:f??gks});if(!e||a||u)return null;if(d&&ms(d))return o.jsx(B8,{children:o.jsx(zs,{})});if(d&&gs(d))return o.jsx(B8,{children:o.jsx(Ts,{resource:"datasets"})});const x=o.jsx(B8,{children:o.jsx(mr,{iconSlot:o.jsx(Bwe,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsx(ie,{as:xo,to:"/experiments",icon:o.jsx(Lc,{}),children:"Back to Experiments"})})});return d&&R1(d)?x:d?o.jsx(B8,{children:o.jsx(Fs,{title:"Failed to load experiment",message:d instanceof Error?d.message:"An unexpected error occurred. Please try again."})}):!l||!c?x:o.jsx(DSs,{experimentId:e,datasetId:l,experimentStatus:c.status,results:f??[],isLoadingResults:h,hasNextPage:v,children:o.jsxs("div",{className:"h-full",children:[o.jsxs(Bt,{height:"full",children:[o.jsx(fks,{experiment:c,onDeleteClick:()=>r(!0),children:o.jsx(sks,{selection:b})}),o.jsxs(Bt.MainArea,{className:"grid grid-cols-[1fr_auto] gap-4 overflow-visible",children:[o.jsx(LSs,{experimentId:e,experimentStatus:c.status,results:f??[],isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v,selectedIds:b.selectedIds,onToggleSelect:b.toggleSelect}),o.jsx(lks,{experiment:c,metrics:y,className:"w-80 overflow-y-auto"})]})]}),o.jsx(qg,{}),o.jsx(rGt,{open:n,onOpenChange:r,experimentId:e,experimentName:c.name??void 0,onSuccess:()=>t("/experiments")})]})})}function yks(){const{itemId:e}=tr();return e?o.jsx(bks,{itemId:e},e):null}function bks({itemId:e}){const{experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:a,hasNextPage:i,close:l,goToPreviousItem:c,goToNextItem:u}=tGt(),d=g.useMemo(()=>s.find(w=>w.itemId===e)??null,[s,e]),{data:f}=Fy(t,r),{updateExperimentResult:h}=za(),p=g.useCallback(async w=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,status:"needs-review"}),Be("Result flagged for review")}catch{Be.error("Failed to flag result for review")}},[n,t,h]),m=gGt(n,s),v=g.useCallback(async(w,k)=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,tags:k})}catch{Be.error("Failed to update tags")}},[n,t,h]),y=g.useCallback(async w=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,status:"complete"}),Be("Result marked as reviewed")}catch{Be.error("Failed to complete result")}},[n,t,h]),b=d?f?.[d.itemId]:void 0,x=KHt(b);return o.jsx(rK,{label:`Experiment item ${e}`,wide:x.wide,children:d?o.jsx(CPe,{className:"p-3",result:d,scores:b,state:x,onPrevious:c,onNext:u,onClose:l,onComplete:()=>y(d.id),onFlagForReview:()=>{p(d.id)},onTagsChange:w=>{v(d.id,w)},tagVocabulary:m,isUpdatingTags:h.isPending}):a||i?o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(Zt,{})})}):o.jsx("div",{className:"h-full p-3",children:o.jsx("div",{className:"border-border1 bg-surface3 flex h-full items-center justify-center rounded-lg border shadow-lg",children:o.jsx(mr,{iconSlot:o.jsx(Bwe,{}),titleSlot:"Item not found",descriptionSlot:`No loaded result for item "${e}".`,actionSlot:o.jsx(ie,{icon:o.jsx(qt,{}),onClick:l,children:"Close"})})})})})}const WPe=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 9.83952 9.3295",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.67171 0.838331H6.70163V4.05307L9.68767 8.09999C10.0634 8.6093 9.69869 9.32932 9.06643 9.3295H0.772551C0.140289 9.3293 -0.223777 8.60929 0.151995 8.09999L3.13804 4.05307V0.838331H2.17136V0H7.67171V0.838331ZM3.97705 4.32955L3.89513 4.44015L2.34681 6.53802H7.49285L5.94453 4.44015L5.86261 4.32955V0.860859H3.97705V4.32955Z",fill:"currentColor"})}),mH="all",Drt=60,xks=e=>e.length>Drt?`${e.slice(0,Drt)}…`:e;function wks({value:e,onValueChange:t,className:n,variant:r,allOption:s,targetType:a,targetId:i}){const{data:l,isLoading:c,isError:u}=HPe(void 0,{targetType:a,targetId:i}),d=(l?.experiments??[]).map(h=>({label:sGt(h),value:h.id,start:o.jsx(WPe,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:h.description?xks(h.description):A0(h.id)??h.id})),f=s?[{label:"All experiments",value:mH},...d]:d;return o.jsx(Co,{options:f,value:e??(s?mH:""),onValueChange:t,placeholder:c?"Loading experiments...":u?"Failed to load experiments":"Select experiment",searchPlaceholder:"Search experiments...",emptyText:"No experiments found.",className:n,disabled:c||u,variant:r})}function Sks(){const[e,t]=da(),n=e.get("experiment"),r=e.get("review"),{targetType:s,targetId:a,setTargetType:i,setTargetId:l}=VPe({resetParams:["experiment","review"]}),{Link:c,paths:u}=ln(),{data:d,error:f}=HPe(void 0,{targetType:s,targetId:a}),h=d?.experiments.find(m=>m.id===n),p=m=>{t(v=>{const y=new URLSearchParams(v);return m===mH?y.delete("experiment"):y.set("experiment",m),y.delete("review"),y},{replace:!0})};return f&&ms(f)?o.jsx(Qn,{children:o.jsx(zs,{})}):f&&gs(f)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"experiments"})}):f?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load experiments",message:f.message})}):o.jsx(Bt,{height:"full",children:o.jsx(G1s,{datasetId:h?.datasetId??void 0,experimentId:n??void 0,targetType:s,targetId:a,featuredItemId:r,detailPanelVariant:"overlay",toolbarStart:o.jsxs(o.Fragment,{children:[o.jsx(BPe,{targetType:s,targetId:a,onTargetTypeChange:i,onTargetIdChange:l}),o.jsx(wks,{allOption:!0,value:n??void 0,onValueChange:p,targetType:s,targetId:a,className:"w-72"})]}),toolbarEnd:n?o.jsx(ie,{as:c,href:u.experimentLink(n),icon:o.jsx(Idt,{}),children:"See experiment"}):void 0},`${s}:${a}:${n??mH}`)})}const vGt=[{name:"itemId",label:"Item ID",size:"auto"},{name:"status",label:"Status",size:"auto"},{name:"input",label:"Input",size:"minmax(0,1fr)"},{name:"tags",label:"Tags",size:"auto"}],kks=vGt.map(e=>e.size).join(" ");function Oks({items:e,isLoading:t,error:n}){const r=zr(),[s,a]=g.useState(""),i=s.trim().toLowerCase(),l=i?e.filter(c=>[c.itemId,c.experimentId,c.datasetId,c.traceId??""].some(u=>u.toLowerCase().includes(i))):e;return t?o.jsx(Uo,{columns:kks}):n?o.jsx(Fs,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(mr,{iconSlot:o.jsx(Os,{className:"text-neutral3 h-8 w-8"}),titleSlot:"Nothing to review",descriptionSlot:"Experiment results that need review will show up here."}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(qc,{onSearch:a,label:"Filter dataset items",placeholder:"Filter by item, experiment, dataset or trace",shortcutDisabled:!0})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsx(KY,{results:l,isLoading:!1,featuredResultId:null,onResultClick:c=>{const u=l.find(d=>d.id===c);u&&r($3t(u.experimentId,u.id))},columns:vGt,emptyMessage:"No dataset items match your search"})})]})}function Cks(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"Your inbox is empty",descriptionSlot:o.jsxs(o.Fragment,{children:["Feedback left on traces and experiment results flagged for review ",o.jsx("br",{}),"will show up here until you mark them reviewed."]}),actionSlot:o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(ie,{icon:o.jsx(WPe,{}),as:xo,to:"/experiments",variant:"outline",children:"Go to experiments"}),o.jsx(ie,{icon:o.jsx(__,{}),as:xo,to:"/traces",variant:"outline",children:"Go to traces"})]})})})}function Cwe(e){return e.comment?e.comment:typeof e.value=="string"?e.value:e.feedbackType==="thumbs"?e.value===1?"Thumbs up":"Thumbs down":JSON.stringify(e.value)??String(e.value)}const Lrt="minmax(0, 2fr) minmax(0, 1fr) auto minmax(0, 1fr) auto auto",_ks=e=>e.stopPropagation();function Eks({items:e,isLoading:t,error:n,hasNextPage:r,isFetchingNextPage:s,fetchNextPage:a,onMarkReviewed:i,pendingFeedbackId:l,onSelect:c,selectedFeedbackId:u}){const[d,f]=g.useState(""),h=d.trim().toLowerCase(),p=h?e.filter(x=>Cwe(x).toLowerCase().includes(h)||(oH(x)??"").toLowerCase().includes(h)||(x.traceId??"").toLowerCase().includes(h)||(x.feedbackSource??"").toLowerCase().includes(h)):e,{containerRef:m,getRowProps:v}=ll({count:p.length,global:!0}),{inView:y,setRef:b}=Yy({root:m});return g.useEffect(()=>{y&&r&&!s&&a()},[y,r,s,a]),t?o.jsx(Uo,{columns:Lrt}):n?o.jsx(Fs,{title:"Failed to load feedback",message:n.message}):o.jsxs("div",{className:"grid h-full min-h-0 grid-rows-[auto_1fr] gap-4",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(qc,{onSearch:f,label:"Filter feedback",placeholder:"Filter loaded feedback by text, author, trace or source"})}),o.jsx("div",{className:"min-h-0 overflow-hidden",children:o.jsxs(be,{columns:Lrt,fit:"container",scrollRef:m,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Feedback"}),o.jsx(be.TopCell,{children:"Author"}),o.jsx(be.TopCell,{children:"Source"}),o.jsx(be.TopCell,{children:"Trace"}),o.jsx(be.TopCell,{children:"Date"}),o.jsx(be.TopCell,{children:" "})]}),p.length===0?o.jsx(be.NoMatch,{message:h?"No feedback matches your search":"No feedback needs review"}):p.map((x,w)=>{const k=x.feedbackId,O=oH(x);return o.jsxs(be.RowWrapper,{...v(w),onSelectRow:x.traceId?()=>c(x):void 0,children:[o.jsxs(be.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,tabIndex:-1,onClick:_=>{_.stopPropagation(),c(x)},children:[o.jsx(be.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:Cwe(x)})}),o.jsx(be.Cell,{className:"flex gap-2",children:O&&o.jsxs(o.Fragment,{children:[o.jsx(Ly,{name:O,src:x.author?.avatarUrl,size:"sm"}),o.jsx("span",{className:"truncate",children:O})]})}),o.jsx(be.Cell,{children:o.jsx(xt,{size:"sm",children:x.feedbackSource})}),o.jsx(be.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(be.TextCell,{children:xr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(be.ActionsCell,{className:"pl-2",onClick:_ks,children:k?o.jsx(ie,{icon:o.jsx(l0,{}),variant:"ghost",size:"sm",onClick:()=>i(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(be.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function Tks({feedback:e,traceId:t,initialSpanId:n,onClose:r,onPrevious:s,onNext:a,onMarkReviewed:i,isMarkingReviewed:l}){const[c,u]=g.useState(n),{spans:d,isLoading:f}=MZt({traceId:t,anchorSpanId:null,listMode:"traces"}),h=oH(e)??e.feedbackUserId;return o.jsx(rK,{label:`Review feedback for trace ${t}`,wide:!!c,children:o.jsxs("div",{className:"[&>*]:bg-surface3 grid h-full min-h-0 grid-rows-[auto_minmax(0,1fr)] gap-4 p-3 [&>*]:rounded-lg [&>*]:shadow-lg",children:[o.jsxs(bn,{className:"max-h-[33vh]",children:[o.jsxs(bn.Header,{className:"items-start",children:[o.jsxs("div",{className:"flex min-w-0 flex-col gap-1",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(bn.Heading,{children:"Feedback"}),o.jsx(xt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(xt,{variant:"neutral",emphasis:"muted",children:e.feedbackSource})]}),o.jsxs("div",{className:"flex items-center gap-2",children:[h&&o.jsxs(o.Fragment,{children:[o.jsx(Ly,{name:h,src:e.author?.avatarUrl,size:"sm"}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral5 truncate",children:h}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3",children:"·"})]}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3",children:xr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss")})]})]}),o.jsx(Wr,{className:"ml-auto shrink-0",children:o.jsx(ie,{variant:"primary",size:"sm",onClick:i,disabled:l,icon:o.jsx(Fn,{}),children:"Mark as reviewed"})})]}),o.jsx(bn.Content,{children:o.jsx(ge,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:Cwe(e)})})]}),o.jsx("section",{className:"min-h-0 overflow-hidden",children:o.jsx(OPe,{className:"h-full rounded-none border-0 bg-transparent",spanPanelClassName:"rounded-none border-0 bg-transparent",traceId:t,spans:d,isLoadingSpans:f,selectedSpanId:c??null,initialSpanId:n,onSpanSelect:u,onClose:r,onPrevious:s,onNext:a,traceHref:`/traces?traceId=${encodeURIComponent(t)}`,feedbackTabSlot:({traceId:p})=>o.jsx(k3,{traceId:p}),spanFeedbackTabSlot:({traceId:p,spanId:m})=>p&&m?o.jsx(dPe,{traceId:p,spanId:m},`${p}:${m}`):null})})]})})}const yGt=100;async function jks(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:yGt});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function Nks(e,t,n){const r=[];let s=0,a=!0;for(;a;){const i=await e.listDatasetExperimentResults(t,n,{page:s,perPage:yGt});r.push(...i.results),a=i.pagination.hasMore,s+=1}return r}function Iks(){const e=Ge();return mt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await jks(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await Nks(e,s,r.id)).filter(i=>i.status==="needs-review").map(i=>({id:i.id,datasetId:s,experimentId:r.id,itemId:i.itemId,traceId:i.traceId??void 0,input:i.input,output:i.output,error:i.error,status:i.status,tags:i.tags})):[]}))).flat()},refetchInterval:3e3,refetchOnWindowFocus:!1})}function Aks({enabled:e}){const t=Ge();return mt({queryKey:["inbox-dataset-review-count"],queryFn:async()=>{const{counts:n}=await t.getExperimentReviewSummary();return n.reduce((r,s)=>r+s.needsReview,0)},enabled:e,refetchInterval:3e3})}function Rks(e){return e==="dataset"||e==="feedback"}function Pks(){const[e,t]=da(),n=e.get("tab"),r=Rks(n)?n:"feedback",s=pgs({reviewStatus:"needs-review"}),a=uPe(),i=Iks(),l=i.data??[],c=s.total??0,u=!s.isLoading&&!i.isLoading&&!s.error&&!i.error&&s.items.length===0&&l.length===0,d=e.get("feedbackId")??void 0,f=e.get("traceId")??void 0,h=e.get("spanId")??void 0,p=T=>{t(E=>{const N=new URLSearchParams(E);for(const I of["feedbackId","traceId","spanId"]){const A=T[I];A?N.set(I,A):N.delete(I)}return N},{replace:!0})},m=()=>p({}),v=T=>p({feedbackId:T.feedbackId??void 0,traceId:T.traceId??void 0,spanId:T.spanId??void 0}),y=s.items.findIndex(T=>T.feedbackId===d),b=y>=0?s.items[y]:void 0,x=y>0?s.items[y-1]:void 0,w=y>=0&&y<s.items.length-1?s.items[y+1]:void 0,k=!!f&&!!d,O=T=>{a.mutate({feedbackId:T,reviewStatus:"reviewed"},{onSuccess:()=>T===d&&m()})},_=T=>{t(E=>{const N=new URLSearchParams(E);return N.set("tab",T),N},{replace:!0})};return o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsx(Bt,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsx(Bt.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(Cks,{}):o.jsxs(kl,{defaultTab:"feedback",value:r,onValueChange:_,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(Sl,{variant:"pill-ghost",children:[o.jsxs(kr,{value:"feedback",children:[o.jsx(st,{size:"sm",children:o.jsx(R3,{})}),o.jsx(ge,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(xt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(kr,{value:"dataset",children:[o.jsx(st,{size:"sm",children:o.jsx(l0,{})}),o.jsx(ge,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(xt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(Hr,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(Eks,{items:s.items,isLoading:s.isLoading,error:s.error??void 0,hasNextPage:s.hasNextPage,isFetchingNextPage:s.isFetchingNextPage,fetchNextPage:s.fetchNextPage,onMarkReviewed:O,pendingFeedbackId:a.isPending?a.variables?.feedbackId:void 0,onSelect:v,selectedFeedbackId:d})}),o.jsx(Hr,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(Oks,{items:l,isLoading:i.isLoading,error:i.error??void 0})})]})})}),k&&f&&b&&o.jsx(Tks,{feedback:b,traceId:f,initialSpanId:h,onClose:m,onPrevious:x?()=>v(x):void 0,onNext:w?()=>v(w):void 0,onMarkReviewed:()=>d&&O(d),isMarkingReviewed:a.isPending},`${d}:${f}`)]})}function $ks({connection:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsxs("li",{className:"flex items-center justify-between border-b py-2",children:[o.jsxs("div",{children:[o.jsx("div",{className:"font-mono text-ui-sm",children:e.connectionId}),o.jsxs("div",{className:"text-ui-sm text-gray-500",children:[e.label??"(no label)"," · ",e.status,e.scope?` · ${e.scope}`:"",t&&e.authorId?` · author: ${e.authorId}`:""]})]}),o.jsx("button",{type:"button",className:"text-red-600 underline disabled:opacity-50",onClick:r,disabled:n,children:"Disconnect"})]})}function bGt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx($ks,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function Mks({groups:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("div",{className:"space-y-4",children:e.map(([s,a])=>o.jsxs("div",{children:[o.jsx("h3",{className:"text-ui-md font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(bGt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function Dks({providerId:e,toolkit:t,connections:n,groupedByAuthor:r,isAdmin:s,isLoading:a,error:i,disconnectPending:l,disconnectError:c,onDisconnect:u}){return o.jsxs("div",{className:"space-y-2 border rounded p-4",children:[o.jsx("h2",{className:"text-header-sm font-semibold",children:"Existing connections"}),!e||!t?o.jsx("p",{className:"text-gray-500",children:"Pick a provider and toolkit to list connections."}):a?o.jsx("p",{className:"text-gray-500",children:"Loading…"}):i?o.jsx("p",{className:"text-red-600",children:String(i)}):n.length===0?o.jsx("p",{className:"text-gray-500",children:"No connections."}):r?o.jsx(Mks,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(bGt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function Lks({providers:e,toolkits:t,providerId:n,toolkit:r,label:s,providersLoading:a,providersError:i,toolkitsLoading:l,toolkitsError:c,authorizePending:u,authorizeError:d,authorizedConnection:f,onProviderChange:h,onToolkitChange:p,onLabelChange:m,onConnect:v}){return o.jsxs("div",{className:"space-y-4 border rounded p-4",children:[o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"provider-select",children:"Provider"}),o.jsxs("select",{id:"provider-select",className:"border rounded px-2 py-1 w-full",value:n,onChange:y=>h(y.target.value),disabled:a,children:[o.jsx("option",{value:"",children:"— select provider —"}),e.map(y=>o.jsxs("option",{value:y.id,children:[y.displayName??y.name," (",y.id,")"]},y.id))]}),a&&o.jsx("span",{className:"text-gray-500",children:"Loading providers…"}),i?o.jsx("span",{className:"text-red-600",children:String(i)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"toolkit-select",children:"Toolkit"}),o.jsxs("select",{id:"toolkit-select",className:"border rounded px-2 py-1 w-full",value:r,onChange:y=>p(y.target.value),disabled:!n||l,children:[o.jsx("option",{value:"",children:"— select toolkit —"}),t.map(y=>o.jsxs("option",{value:y.slug,children:[y.name," (",y.slug,")"]},y.slug))]}),l&&o.jsx("span",{className:"text-gray-500",children:"Loading toolkits…"}),c?o.jsx("span",{className:"text-red-600",children:String(c)}):null]}),o.jsxs("div",{className:"space-y-1",children:[o.jsx("label",{className:"block font-medium",htmlFor:"label-input",children:"Label (optional)"}),o.jsx("input",{id:"label-input",type:"text",className:"border rounded px-2 py-1 w-full",placeholder:"My personal Gmail",value:s,onChange:y=>m(y.target.value),disabled:!n||!r})]}),o.jsx("button",{type:"button",className:"bg-blue-600 text-white rounded px-4 py-2 disabled:opacity-50",onClick:v,disabled:!n||!r||u,children:u?"Authorizing…":"Connect"}),d?o.jsx("p",{className:"text-red-600",children:String(d)}):null,f&&o.jsxs("p",{className:"text-green-700",children:["Authorized: ",f.connectionId," (status: ",f.status,")"]})]})}const Frt=e=>e.authorId?.trim()||"shared",Fks=(e,t)=>{if(!t||new Set(e.map(Frt)).size<=1)return null;const r=new Map;for(const a of e){const i=Frt(a);r.set(i,[...r.get(i)??[],a])}const s=Array.from(r.entries());return s.sort(([a],[i])=>a==="shared"?1:i==="shared"?-1:a.localeCompare(i)),s},zks=["*","tool-providers:*","tool-providers:admin"];function Bks(){const{data:e}=zm();return e?.permissions?.some(t=>zks.includes(t))??!1}function Uks(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=CA(),l=aQ(e||null),c=k5t(e||null,n||null),u=S5t(),d=b5t(),f=Bks(),h=i.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>Fks(m,f),[m,f]),y=w=>{t(w),r("")},b=()=>{!e||!n||u.mutate({providerId:e,toolkit:n,label:s.trim()||null},{onSuccess:()=>{a(""),c.refetch()}})},x=w=>{d.mutate({providerId:e,connectionId:w})};return o.jsxs("div",{className:"p-4 max-w-3xl space-y-6 text-ui-md",children:[o.jsx("h1",{className:"text-header-md font-semibold",children:"Integrations"}),o.jsx("p",{className:"text-gray-500",children:"Minimal page to verify the ToolProvider backend. Pick a provider and toolkit, then connect."}),o.jsx(Lks,{providers:h,toolkits:p,providerId:e,toolkit:n,label:s,providersLoading:i.isLoading,providersError:i.error,toolkitsLoading:l.isLoading,toolkitsError:l.error,authorizePending:u.isPending,authorizeError:u.error,authorizedConnection:u.data,onProviderChange:y,onToolkitChange:r,onLabelChange:a,onConnect:b}),o.jsx(Dks,{providerId:e,toolkit:n,connections:m,groupedByAuthor:v,isAdmin:f,isLoading:c.isLoading,error:c.error,disconnectPending:d.isPending,disconnectError:d.error,onDisconnect:x})]})}function qks({title:e,description:t,errorBanner:n,children:r}){return o.jsx("div",{"data-testid":"login-page",className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsxs("div",{className:"w-full max-w-sm space-y-6",children:[o.jsxs("div",{className:"flex flex-col items-center space-y-2",children:[o.jsx(um,{className:"h-10 w-10"}),o.jsx("h1",{className:"text-neutral6 text-header-md font-semibold",children:e})]}),t,n,r]})})}function xGt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=fc(),{mutate:i,isPending:l,error:c}=X4r(),{mutate:u,isPending:d,error:f}=e5r(),{mutate:h,isPending:p}=mLt(),[m,v]=g.useState(n),[y,b]=g.useState(""),[x,w]=g.useState(""),[k,O]=g.useState("");if(a)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Loading..."})});if(!s?.enabled||!s?.login)return o.jsx("div",{className:"bg-surface1 flex min-h-screen items-center justify-center",children:o.jsx("div",{className:"text-neutral3",children:"Authentication is not configured"})});const{login:_}=s,T=_.type==="sso"||_.type==="both",E=_.type==="credentials"||_.type==="both",N=_.sso,I=_.signUpEnabled!==!1,A=m==="signin"||!I,$=A?l:d,z=A?c:f,D=()=>{t?t():e?window.location.href=e:window.location.href=cQ("/")},q=L=>{L.preventDefault(),A?i({email:x,password:k},{onSuccess:D}):u({email:x,password:k,name:y||void 0},{onSuccess:D})},H=()=>{h({redirectUri:e},{onSuccess:L=>{window.location.href=L.url}})},V=()=>{v(A?"signup":"signin")},B=_.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(qd,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-ui-md",children:_.description})]}):null,W=r?o.jsx("div",{className:"text-ui-md rounded-md bg-red-500/10 p-3 text-red-400",children:r}):null;return o.jsxs(qks,{title:A?"Sign in to Mastra Studio":"Create your account",description:B,errorBanner:W,children:[E&&o.jsxs("form",{onSubmit:q,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"text-neutral4 text-ui-md block",children:"Name"}),o.jsx(In,{id:"name",type:"text",value:y,onChange:L=>b(L.target.value),placeholder:"Your name",variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"email",className:"text-neutral4 text-ui-md block",children:"Email"}),o.jsx(In,{id:"email",type:"email",value:x,onChange:L=>w(L.target.value),placeholder:"you@example.com",required:!0,variant:"default",size:"lg"})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"password",className:"text-neutral4 text-ui-md block",children:"Password"}),o.jsx(In,{id:"password",type:"password",value:k,onChange:L=>O(L.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),z&&o.jsx("div",{className:"text-ui-md rounded-md bg-red-500/10 p-3 text-red-400",children:z.message}),o.jsx(ie,{icon:o.jsx(E7,{}),type:"submit",disabled:$,className:"w-full",size:"lg",children:$?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-ui-md text-center",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:V,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),T&&E&&o.jsxs("div",{className:"relative",children:[o.jsx("div",{className:"absolute inset-0 flex items-center",children:o.jsx("div",{className:"border-border1 w-full border-t"})}),o.jsx("div",{className:"text-ui-md relative flex justify-center",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),T&&N&&o.jsxs(ie,{onClick:H,disabled:p,className:"w-full",size:"lg",variant:"outline",children:[N.icon&&o.jsx("span",{className:"mr-2",children:N.icon}),p?"Redirecting...":N.text||"Sign in"]})]})}function Vks(){const[e]=da(),t=zr(),n=e.get("redirect")||"/",s=e.get("mode")==="signup"?"signup":"signin",a=e.get("error_description")||e.get("error")||null,i=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(xGt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const wh=ja.KeyValueList;function Hks(e){return e instanceof Date?e:new Date(e)}function Wks({log:e,onClose:t,onTraceClick:n,onSpanClick:r,onPrevious:s,onNext:a,collapsed:i,onCollapsedChange:l}){const[c,u]=g.useState(!1),d=i??c,f=l??u,h=Hks(e.timestamp),p=e.traceId,m=e.spanId;return o.jsxs(ja,{collapsed:d,children:[o.jsxs(ja.Header,{children:[o.jsxs(ja.Heading,{children:["Log ",o.jsx("b",{children:xr(h,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(Wr,{className:"ml-auto shrink-0",children:[l&&o.jsx(ie,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(T3,{}):o.jsx(vH,{})}),o.jsxs(Wr,{spacing:"close",children:[o.jsx(ie,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(o0,{})}),o.jsx(ie,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(E3,{})})]}),o.jsx(ja.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(ja.Content,{children:[o.jsx("p",{className:"text-ui-md text-neutral4 font-mono wrap-break-word whitespace-pre-wrap",children:e.message}),(p||m)&&o.jsxs("div",{className:K("my-8 grid gap-2","[&>button]:justify-between [&>button]:overflow-hidden"),children:[p&&o.jsxs(Wr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ie,{size:"md",className:"min-w-0 flex-1 overflow-hidden",icon:o.jsx(Df,{}),onClick:()=>n?.(p),children:[o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",p]})]}),o.jsx(Pa,{content:p,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(Wr,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(ie,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!p||!r,onClick:()=>p&&r?.(p,m),icon:o.jsx(Df,{}),children:[o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(Pa,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(wh,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(wh.Key,{children:"Entity Type"}),o.jsx(wh.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(wh.Key,{children:"Entity Name"}),o.jsx(wh.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(wh.Key,{children:"Service"}),o.jsx(wh.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(wh.Key,{children:"Environment"}),o.jsx(wh.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(wh.Key,{children:"Source"}),o.jsx(wh.Value,{children:e.source})]}),e.metadata&&Object.keys(e.metadata).length>0&&o.jsx(o.Fragment,{children:Object.entries(e.metadata).map(([v,y])=>o.jsxs(g.Fragment,{children:[o.jsx(wh.Key,{children:v}),o.jsx(wh.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(ja.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function Zks({error:e,resource:t,errorTitle:n}){if(ms(e))return o.jsx(zs,{});if(gs(e))return o.jsx(Ts,{resource:t});if(x4(e))return o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"Observability storage is not available",descriptionSlot:"The observability storage domain is disabled or not configured. Enable it in your storage configuration to view logs in Studio."});if(b4(e,"logs"))return o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"Logs are not available with your current storage",descriptionSlot:"The configured observability storage provider does not support listing logs. Switch to a storage provider with logs support to view runtime logs in Studio."});const r=e instanceof Error?e.message:void 0;return o.jsx(Fs,{title:n,message:r??"Unknown error"})}function Gks({listSlot:e,logPanelSlot:t,tracePanelSlot:n,spanPanelSlot:r,logCollapsed:s}){const a=!!t;return o.jsxs("div",{className:K("grid h-full min-h-0 items-start gap-4",a?"grid-cols-[1fr_1fr]":"grid-cols-[1fr]"),children:[e,a&&o.jsxs("div",{className:K("grid h-full gap-4 overflow-auto",n&&r?s?"grid-rows-[auto_1fr_1fr]":"grid-rows-[1fr_1fr_1fr]":n?s?"grid-rows-[auto_1fr]":"grid-rows-[1fr_1fr]":s?"grid-rows-[auto]":"grid-rows-[1fr]"),children:[t,n,r]})]})}const Qks={debug:{label:"DEBUG",color:"#71717a"},info:{label:"INFO",color:"#60a5fa"},warn:{label:"WARN",color:"#facc15"},error:{label:"ERROR",color:"#f87171"},fatal:{label:"FATAL",color:"#dc2626"}};function Yks({level:e}){const t=Qks[e];return o.jsx(co,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Kks({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(Pi,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(hc,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Xd,{className:n,"aria-hidden":!0});default:return null}}function Xks({entityType:e,entityName:t}){const n=e??"";return o.jsxs(co,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(Kks,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function Jks({message:e}){return o.jsx(co,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function eOs({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(co,{children:null});const t=Object.entries(e).map(([n,r])=>{if(typeof r=="string")return`${n}: ${r}`;try{return`${n}: ${JSON.stringify(r)}`}catch{return`${n}: <unserializable>`}}).join(", ");return o.jsx(xje,{font:"mono",children:t})}const Jl=Object.assign(g4,{Top:y4,TopCell:C0,TopCellWithTooltip:WG,TopCellSmart:Z2t,RowWrapper:Oje,RowButton:v4,RowLink:kje,Spacer:Cje,NoMatch:HG,DateCell:V2t,TimeCell:H2t,LevelCell:Yks,EntityCell:Xks,MessageCell:Jks,DataCell:eOs,NextPageLoading:VG}),zrt="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",tOs=36,nOs=8;function rOs({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=$Zt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>tOs,overscan:nOs}),{getRowProps:d}=ll({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y),global:!0}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Uo,{columns:zrt});const h=u.getVirtualItems(),p=u.getTotalSize(),m=h[0]?.start??0,v=h.length>0?Math.max(0,p-(h[h.length-1]?.end??0)):0;return o.jsxs(Jl,{columns:zrt,scrollRef:c,className:"min-w-0",children:[o.jsxs(Jl.Top,{children:[o.jsx(Jl.TopCell,{children:"Date"}),o.jsx(Jl.TopCell,{children:"Time"}),o.jsx(Jl.TopCell,{children:"Level"}),o.jsx(Jl.TopCell,{children:"Entity"}),o.jsx(Jl.TopCell,{children:"Message"}),o.jsx(Jl.TopCell,{children:"Data"})]}),e.length===0?o.jsx(Jl.NoMatch,{message:"No logs match your search"}):o.jsxs(o.Fragment,{children:[o.jsx(Jl.Spacer,{height:m}),h.map(y=>{const b=e[y.index];if(!b)return null;const x=a.get(b);if(!x)return null;const w=x===i;return o.jsxs(Jl.RowButton,{ref:u.measureElement,"data-index":y.index,...d(y.index),onClick:()=>l(b),featured:w,variant:b.level==="error"||b.level==="fatal"?"error":"default",children:[o.jsx(Jl.DateCell,{timestamp:b.timestamp}),o.jsx(Jl.TimeCell,{timestamp:b.timestamp}),o.jsx(Jl.LevelCell,{level:b.level}),o.jsx(Jl.EntityCell,{entityType:b.entityType,entityName:b.entityName}),o.jsx(Jl.MessageCell,{message:b.message}),o.jsx(Jl.DataCell,{data:b.data})]},x)}),o.jsx(Jl.Spacer,{height:v})]}),o.jsx(Jl.NextPageLoading,{isLoading:n,hasMore:r,setEndOfListElement:s})]})}function sOs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>aOs(f,a));return u?o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(APe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(NPe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function aOs(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}const iOs={"last-24h":"the last 24 hours","last-3d":"the last 3 days","last-7d":"the last 7 days","last-14d":"the last 14 days","last-30d":"the last 30 days"},ile="MMM d, yyyy HH:mm",ole="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function oOs({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${iOs[e]}`,description:ole}:t&&n?{title:`No logs between ${xr(t,ile)} and ${xr(n,ile)}`,description:ole}:t?{title:`No logs since ${xr(t,ile)}`,description:ole}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const lOs=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=oOs({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsx(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",icon:o.jsx(Cs,{}),children:"Logging Documentation"})})})},cOs=20,uOs=1e4;function dOs(e,t,n){if(e?.pagination?.hasMore)return n+1}function fOs(e){const t=new Set,n=[];for(const r of e.pages)for(const s of r.logs??[]){const a=s.logId??JSON.stringify(s);t.has(a)||(t.add(a),n.push(s))}return n}function hOs(e){return b4(e.state.error,"logs")||x4(e.state.error)?!1:uOs}const pOs=({filters:e}={})=>{const t=Ge(),{inView:n,setRef:r}=Yy(),s=ev({queryKey:["logs",e],queryFn:({pageParam:h})=>t.listLogsVNext({pagination:{page:h,perPage:cOs},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:dOs,select:fOs,retry:!1,refetchInterval:hOs}),{hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,data:c,isLoading:u,isError:d,error:f}=s;return g.useEffect(()=>{n&&a&&!i&&l()},[n,a,i,l]),{data:c,hasNextPage:a,isFetchingNextPage:i,fetchNextPage:l,isLoading:u,isError:d,error:f,setEndOfListElement:r}},U8={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},wGt=[{label:"Agent",entityType:U8.AGENT},{label:"Workflow",entityType:U8.WORKFLOW},{label:"Scorer",entityType:U8.SCORER},{label:"Ingest",entityType:U8.INGEST}],mOs=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],i0="rootEntityType",lx="datePreset",cx="dateFrom",ux="dateTo",gOs=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Al={level:"filterLevel",tags:"filterTags",entityName:"filterEntityName",traceId:"filterTraceId",spanId:"filterSpanId",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId"},E5=Object.keys(Al),ZPe=new Set(["tags"]),GPe="mastra:logs:saved-filters";function vOs(e,t=GPe){const n=SOs(e),r=e.get(lx);r&&n.set(lx,r);const s=e.get(cx);s&&n.set(cx,s);const a=e.get(ux);a&&n.set(ux,a);try{localStorage.setItem(t,n.toString())}catch{}}function yOs(e=GPe){try{localStorage.removeItem(e)}catch{}}function Brt(e=GPe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function bOs(e){if(e.has(lx)||e.has(cx)||e.has(ux)||e.has(i0))return!0;for(const t of E5)if(e.has(Al[t]))return!0;return!1}function xOs({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:wGt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"level",label:"Level",kind:"pick-multi",searchable:!1,options:mOs.map(u=>({label:u.label,value:u.value})),placeholder:"Choose level",emptyText:"No levels."},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"traceId",label:"Trace ID",kind:"text"},{id:"spanId",label:"Span ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"threadId",label:"Thread ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function wOs(e){const t=[],n=new Map([[i0,"rootEntityType"]]);for(const s of E5)n.set(Al[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),ZPe.has(a)){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function SOs(e){const t=new URLSearchParams,n=e.get(i0);n&&t.set(i0,n);for(const r of E5){const s=Al[r];if(ZPe.has(r)){for(const i of e.getAll(s))t.append(s,i);continue}const a=e.get(s);a&&t.set(s,a)}return t}function kOs(e,t){e.delete(i0);for(const n of E5)e.delete(Al[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(i0,n.value);continue}const r=Al[n.fieldId];if(r){if(ZPe.has(n.fieldId)&&Array.isArray(n.value)){if(n.value.length===0)e.append(r,"");else for(const s of n.value)e.append(r,s);continue}typeof n.value=="string"&&e.set(r,n.value.trim())}}}function OOs({rootEntityType:e,dateFrom:t,dateTo:n,tokens:r}){const s={};e&&(s.rootEntityType=e),(t||n)&&(s.timestamp={...t?{start:t}:{},...n?{end:n}:{}});for(const a of r){if(a.fieldId==="tags"){Array.isArray(a.value)&&a.value.length>0?s.tags=a.value:typeof a.value=="string"&&a.value.trim()&&(s.tags=[a.value.trim()]);continue}if(a.fieldId==="level"){typeof a.value=="string"&&a.value.trim()&&a.value!=="Any"&&(s.level=a.value);continue}if(typeof a.value=="string"&&a.value.trim()&&a.value!=="Any")switch(a.fieldId){case"entityName":s.rootEntityName=a.value;break;case"traceId":s.traceId=a.value;break;case"spanId":s.spanId=a.value;break;case"runId":s.runId=a.value;break;case"threadId":s.threadId=a.value;break;case"sessionId":s.sessionId=a.value;break;case"requestId":s.requestId=a.value;break;case"resourceId":s.resourceId=a.value;break;case"userId":s.userId=a.value;break;case"organizationId":s.organizationId=a.value;break;case"serviceName":s.serviceName=a.value;break;case"environment":s.environment=a.value;break;case"experimentId":s.experimentId=a.value;break}}return s}function COs(e,t){return t.map(n=>{const r=e.find(s=>s.id===n.fieldId);return r?r.kind==="text"?{fieldId:n.fieldId,value:""}:r.kind==="pick-multi"?r.multi?{fieldId:n.fieldId,value:[]}:{fieldId:n.fieldId,value:"Any"}:n:n})}const _Os="Filters setting for Logs saved",EOs="Filters setting for Logs cleared up";function TOs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Brt(r)!==null),c=g.useCallback(()=>{vOs(e,r),l(!0);const f=s?.saved??_Os;f!==!1&&Be.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{yOs(r),l(!1);const f=s?.cleared??EOs;f!==!1&&Be.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,bOs(e)))return;const f=Brt(r);f&&t(h=>{const p=new URLSearchParams(h);for(const[m,v]of f)p.append(m,v);return p},{replace:!0})},[]),{hasSavedFilters:i,handleSave:c,handleRemoveSaved:u}}function jOs(e){let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n)|0;return(t>>>0).toString(36)}function NOs(e){const t=new Map;for(const n of e){if(n.logId){t.set(n,n.logId);continue}const r=n.timestamp instanceof Date?n.timestamp.toISOString():n.timestamp;t.set(n,jOs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function IOs(e,t,n,r){const s=g.useMemo(()=>NOs(e),[e]),a=g.useMemo(()=>{const p=new Map;for(const[m,v]of e.entries()){const y=s.get(v);y&&p.set(y,{log:v,idx:m})}return p},[e,s]),l=(t?a.get(t):void 0)?.idx??-1,c=l>=0?e[l]??null:null,u=g.useCallback(p=>s.get(p),[s]),d=g.useCallback(p=>{const m=s.get(p);if(m){if(t===m){n({logId:null});return}n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}},[s,t,r,n]),f=l>0?()=>{const p=e[l-1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0,h=l>=0&&l<e.length-1?()=>{const p=e[l+1];if(!p)return;const m=s.get(p);m&&n(r?{logId:m,traceId:p.traceId??null,spanId:null}:{logId:m})}:void 0;return{logIdMap:s,getLogId:u,featuredLog:c,handleLogClick:d,handlePreviousLog:f,handleNextLog:h}}const _we="logId",Ewe="traceId",Twe="spanId",s$=1440*60*1e3,AOs={"last-24h":s$,"last-3d":3*s$,"last-7d":7*s$,"last-14d":14*s$,"last-30d":30*s$};function q8(e){e.delete(_we),e.delete(Ewe),e.delete(Twe)}function ROs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const O=e.get(lx);return O&&gOs.has(O)?O:"last-24h"},[e]),a=e.get(cx),i=e.get(ux),l=g.useMemo(()=>{if(s==="custom"){if(!a)return;const _=new Date(a);return Number.isNaN(_.getTime())?void 0:_}if(s==="all")return;const O=AOs[s];return O?new Date(Date.now()-O):void 0},[s,a]),c=g.useMemo(()=>{if(s!=="custom"||!i)return;const O=new Date(i);return Number.isNaN(O.getTime())?void 0:O},[s,i]),u=g.useRef(s);u.current=s;const d=e.get(_we),f=e.get(Ewe),h=e.get(Twe),p=g.useMemo(()=>wGt.find(O=>O.entityType===e.get(i0)),[e]),m=g.useMemo(()=>wOs(e),[e]),v=g.useCallback(O=>{t(_=>{const T=new URLSearchParams(_);for(const[E,N]of Object.entries(O)){const I=E==="logId"?_we:E==="traceId"?Ewe:Twe;N?T.set(I,N):T.delete(I)}return T},{replace:!0})},[t]),y=g.useCallback(O=>{t(_=>{const T=new URLSearchParams(_);return kOs(T,O),q8(T),T},{replace:!0})},[t]),b=y,x=g.useCallback((O,_)=>{if(u.current!=="custom")return;const T=_==="from"?cx:ux;t(E=>{const N=new URLSearchParams(E);return O?N.set(T,O.toISOString()):N.delete(T),q8(N),N},{replace:!0})},[t]),w=g.useCallback(O=>{u.current=O,t(_=>{const T=new URLSearchParams(_);return O==="last-24h"?(T.delete(lx),T.delete(cx),T.delete(ux)):O==="custom"?T.set(lx,"custom"):(T.set(lx,O),T.delete(cx),T.delete(ux)),q8(T),T},{replace:!0})},[t]),k=g.useCallback(()=>{t(O=>{const _=new URLSearchParams(O);_.delete(i0);for(const T of E5)_.delete(Al[T]);return _.delete(lx),_.delete(cx),_.delete(ux),q8(_),_},{replace:!0}),r?.()},[t,r]);return g.useMemo(()=>({searchParams:e,setSearchParams:t,datePreset:s,selectedDateFrom:l,selectedDateTo:c,datePresetRef:u,featuredLogId:d,featuredTraceId:f,featuredSpanId:h,selectedEntityOption:p,filterTokens:m,handleFeaturedChange:v,handleFilterTokensChange:b,handleDateChange:x,handleDatePresetChange:w,handleRemoveAll:k,applyFilterTokens:y}),[e,t,s,l,c,u,d,f,h,p,m,v,b,x,w,k,y])}const lle=ja.KeyValueList;function POs({spanId:e,span:t,isLoading:n,onClose:r}){return o.jsxs(ja,{children:[o.jsxs(ja.Header,{children:[o.jsxs("div",{className:"flex min-w-0 flex-1 flex-col gap-1",children:[o.jsxs(ja.Heading,{className:"items-center",children:["Span",o.jsx(AY,{id:e})]}),t&&o.jsx(mWt,{span:t})]}),o.jsx(ja.CloseButton,{onClick:r})]}),n?o.jsx(ja.LoadingData,{children:"Loading span..."}):t?o.jsxs(ja.Content,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsxs(lle,{children:[o.jsx(lle.Key,{children:"Type"}),o.jsx(lle.Value,{children:t.spanType})]}),o.jsx("br",{})]}),o.jsx(ja.CodeSection,{title:"Input",icon:o.jsx(zO,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(ja.CodeSection,{title:"Output",icon:o.jsx(xy,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(ja.CodeSection,{title:"Metadata",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(ja.CodeSection,{title:"Attributes",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(ja.NoData,{children:"Span not found."})]})}function $Os({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>b5(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(PY(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(ja,{children:[o.jsxs(ja.Header,{children:[o.jsxs(ja.Heading,{className:"items-center",children:["Trace",o.jsx(AY,{id:e})]}),o.jsx(ja.CloseButton,{onClick:r})]}),n?o.jsx(ja.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(ja.NoData,{children:"No spans found for this trace."}):o.jsx(ja.Content,{children:o.jsx(fPe,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function MOs(){const[e,t]=da(),n=ROs(e,t),r=TOs(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=FPe(),{data:d=[],isPending:f}=MPe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:p}=DPe(),{data:m=[],isPending:v}=LPe(),y=g.useMemo(()=>xOs({availableTags:c,availableRootEntityNames:d,availableServiceNames:m,availableEnvironments:h,loading:{tags:u,entityNames:f,serviceNames:v,environments:p}}),[c,d,m,h,u,f,v,p]),b=g.useMemo(()=>OOs({rootEntityType:n.selectedEntityOption?.entityType,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,tokens:n.filterTokens}),[n.filterTokens,n.selectedDateFrom,n.selectedDateTo,n.selectedEntityOption]),{data:x=[],isLoading:w,error:k,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:T}=pOs({filters:b}),{logIdMap:E,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:$}=IOs(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:z,isLoading:D}=MA(n.featuredTraceId??null),{data:q,isLoading:H}=RY(n.featuredTraceId??"",n.featuredSpanId??""),V=g.useCallback(()=>n.applyFilterTokens(COs(y,n.filterTokens)),[y,n]),B=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),W=g.useCallback(Q=>n.handleFeaturedChange({traceId:Q,spanId:null}),[n]),L=g.useCallback((Q,te)=>n.handleFeaturedChange({traceId:Q,spanId:te}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),M=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),R=g.useCallback(Q=>n.handleFeaturedChange({spanId:Q??null}),[n]),F=o.jsxs(Bt.TopArea,{children:[o.jsx(Bt.Row,{children:o.jsxs(Bt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(w4,{preset:n.datePreset,onPresetChange:n.handleDatePresetChange,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo,onDateChange:n.handleDateChange,disabled:w,presets:["last-24h","last-3d","last-7d","last-14d","last-30d","custom"]}),o.jsx(RPe,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:a})]})}),o.jsx(sOs,{isLoading:w,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:V,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Bt,{width:"wide",height:"full",children:[F,o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(Zks,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const U=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!w&&!U?o.jsxs(Bt,{width:"wide",height:"full",children:[F,o.jsx(Bt.MainArea,{isCentered:!0,children:o.jsx(lOs,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Bt,{width:"wide",height:"full",children:[F,o.jsx(Gks,{logCollapsed:i,listSlot:o.jsx(rOs,{logs:x,isLoading:w,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:T,logIdMap:E,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Wks,{log:N,onClose:B,onTraceClick:W,onSpanClick:L,onPrevious:A,onNext:$,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx($Os,{traceId:n.featuredTraceId,spans:z?.spans,isLoading:D,onClose:G,onSpanSelect:R,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(POs,{spanId:n.featuredSpanId,span:q?.span,isLoading:H,onClose:M}):null})]})}function DOs({server:e,rowProps:t}){const{paths:n,Link:r}=ln(),a=Ge().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=Zqt(e),c=Object.values(l||{}),u=c.length,d=c.filter(p=>p.toolType==="agent").length,f=c.filter(p=>p.toolType==="workflow").length,h=Vf(e.name,50);return o.jsxs(be.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(be.NameCell,{children:h}),o.jsx(be.DescriptionCell,{children:i}),o.jsx(be.TextCell,{className:"text-center",children:d||""}),o.jsx(be.TextCell,{className:"text-center",children:u||""}),o.jsx(be.TextCell,{className:"text-center",children:f||""})]})}function LOs({mcpServers:e,isLoading:t,search:n=""}){const r=g.useMemo(()=>{const i=n.toLowerCase();return e.filter(l=>l.name?.toLowerCase().includes(i)||l.id?.toLowerCase().includes(i))},[e,n]),{containerRef:s,getRowProps:a}=ll({count:r.length,global:!0});return t?o.jsx(Uo,{columns:"auto 1fr auto auto auto"}):o.jsxs(be,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Name"}),o.jsx(be.TopCell,{children:"URL"}),o.jsx(be.TopCellSmart,{long:"Agents",short:o.jsx(Pi,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(be.TopCellSmart,{long:"Tools",short:o.jsx(Xd,{}),tooltip:"Tools",className:"text-center"}),o.jsx(be.TopCellSmart,{long:"Workflows",short:o.jsx(hc,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(be.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(DOs,{server:i,rowProps:a(l)},i.id))]})}const FOs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"No MCP Servers yet",descriptionSlot:o.jsxs(o.Fragment,{children:["MCP servers are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsx(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",icon:o.jsx(Cs,{}),children:"MCP Documentation"})})}),zOs=()=>{const{data:e=[],isLoading:t,error:n}=d5(),[r,s]=g.useState("");return n&&ms(n)?o.jsx(Qn,{children:o.jsx(zs,{})}):n&&gs(n)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"MCP servers"})}):n?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Qn,{children:o.jsx(FOs,{})}):o.jsxs(Bt,{height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(qc,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(LOs,{mcpServers:e,isLoading:t,search:r})]})},BOs=(e,t)=>{const n=new Map,r=Object.keys(t);for(const s of r){const a=t[s],i=a.tools,l=Object.keys(i);for(const c of l){const u=i[c];n.has(u.id)||n.set(u.id,{...u,agents:[]}),n.get(u.id).agents.push({...a,id:s})}}for(const[s,a]of Object.entries(e))n.has(a.id)||n.set(a.id,{...a,agents:[]});return Array.from(n.values())};function UOs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=ln(),i=g.useMemo(()=>BOs(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=ll({count:l.length,global:!0});return n?o.jsx(Uo,{columns:"auto 1fr auto"}):o.jsxs(be,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Name"}),o.jsx(be.TopCell,{children:"Description"}),o.jsx(be.TopCellSmart,{long:"Agents",short:o.jsx(Pi,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(be.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const h=Vf(d.id,50),p=Vf(d.description??"",200),m=d.agents.length;return o.jsxs(be.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(be.NameCell,{children:h}),o.jsx(be.DescriptionCell,{children:p}),o.jsx(be.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const qOs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"No Tools yet",descriptionSlot:o.jsxs(o.Fragment,{children:["Mastra tools are not configured yet. ",o.jsx("br",{}),"More information in the documentation."]}),actionSlot:o.jsx(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",icon:o.jsx(Cs,{}),children:"Tools Documentation"})})}),VOs=()=>{const e=Ge();return wn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new e_;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Be.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},HOs=({toolId:e})=>{const{canExecute:t}=Wo(),n=t("tools"),{data:r={}}=Yf(),s=g.useMemo(()=>{for(const v of Object.values(r))if(v.tools){const y=Object.values(v.tools).find(b=>b.id===e);if(y)return y}return null},[r,e]),{data:a,isLoading:i,error:l}=f4r(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=VOs(),{requestContext:h}=vs();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Be.error(`Error loading tool: ${v}`)}},[l]);const p=async(v,y)=>{if(!c)return;const b={...h??{},...y??{}};return u({toolId:c.id,input:v,requestContext:b})},m=c?.inputSchema?xm(zx(c?.inputSchema)):ws({});return i?o.jsxs("div",{className:"p-4",children:[o.jsx(Et,{className:"mb-4 h-8 w-48"}),o.jsx(Et,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(HRe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:p,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})}):o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function WOs({value:e,onValueChange:t,placeholder:n="Select a tool...",searchPlaceholder:r="Search tools...",emptyText:s="No tools found.",className:a,disabled:i=!1,variant:l,size:c,"aria-label":u,align:d}){const{data:f={},isLoading:h,isError:p,error:m}=SA(),{data:v={},isLoading:y,isError:b,error:x}=Yf(),{navigate:w,paths:k}=ln();g.useEffect(()=>{if(p){const E=m instanceof Error?m.message:"Failed to load tools";Be.error(`Error loading tools: ${E}`)}},[p,m]),g.useEffect(()=>{if(b){const E=x instanceof Error?x.message:"Failed to load agents";Be.error(`Error loading agents: ${E}`)}},[b,x]);const O=new Map;Object.values(v).forEach(E=>{E.tools&&Object.values(E.tools).forEach(N=>{O.has(N.id)||O.set(N.id,N)})}),Object.values(f).forEach(E=>{O.has(E.id)||O.set(E.id,E)});const _=Array.from(O.values()).map(E=>({label:E.id,value:E.id})),T=E=>{t?t(E):E&&E!==e&&w(k.toolLink(E))};return o.jsx(Co,{options:_,value:e,onValueChange:T,placeholder:h||y?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||h||y||p||b,variant:l,size:c,"aria-label":u,align:d})}const ZOs=({isLoading:e,server:t})=>{const[{sseUrl:n,httpStreamUrl:r},s]=g.useState({sseUrl:"",httpStreamUrl:""});if(g.useEffect(()=>{if(!t)return;const i=window.MASTRA_SERVER_HOST,l=window.MASTRA_SERVER_PORT;let c=null;i&&l&&(c=`http://${i}:${l}`);const u=c||"http://localhost:4111",d=`${u}/api/mcp/${t.id}/sse`,f=`${u}/api/mcp/${t.id}/mcp`;s({sseUrl:d,httpStreamUrl:f})},[t]),e)return null;if(!t)return o.jsx(jx,{children:o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral3 py-20 text-center font-medium",children:"Server not found"})});const a=`npx -y mcp-remote ${n}`;return o.jsxs(jx,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-5 py-8",children:[o.jsx(ge,{as:"h1",variant:"header-md",className:"text-neutral6 pb-4 font-medium",children:t.name}),o.jsxs("div",{className:"flex items-center gap-1 pb-4",children:[o.jsx(xt,{icon:o.jsx(yWt,{}),size:"sm",children:"Version"}),o.jsx(xt,{size:"sm",children:t.version_detail.version})]}),o.jsx(ge,{className:"text-neutral3 pb-4",children:"This MCP server can be accessed through multiple transport methods. Choose the one that best fits your use case."}),o.jsxs("div",{className:"flex flex-col gap-4",children:[o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"HTTP"}),children:"Regular HTTP Endpoint"}),o.jsx(ge,{className:"text-neutral3 pt-1 pb-2",children:"Use for stateless HTTP transport with streamable responses."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ge,{className:"bg-surface4 rounded-lg px-2 py-1",children:r}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"SSE"}),children:"Server-Sent Events"}),o.jsx(ge,{className:"text-neutral3 pt-1 pb-2",children:"Use for real-time communication via SSE."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ge,{className:"bg-surface4 rounded-lg px-2 py-1",children:n}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(xt,{icon:o.jsx("span",{className:"text-accent1 mr-1 w-6 font-mono font-medium",children:"CLI"}),children:"Command Line"}),o.jsx(ge,{className:"text-neutral3 pt-1 pb-2",children:"Use for local command-line access via npx and mcp-remote."}),o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(ge,{className:"bg-surface4 rounded-lg px-2 py-1",children:a}),o.jsx("div",{className:"pt-1",children:o.jsx(Pa,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(GOs,{server:t})})]})},GOs=({server:e})=>{const{data:t={},isLoading:n}=Zqt(e);if(n)return null;const r=Object.keys(t);return o.jsxs("div",{className:"overflow-y-scroll p-5",children:[o.jsxs("div",{className:"text-neutral6 flex items-center gap-2",children:[o.jsx(st,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(Z_,{})}),o.jsx(ge,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-4",children:r.map(s=>{const a=t[s];return o.jsx(YOs,{tool:a,serverId:e.id},s)})})]})};function QOs(e){if(!e)return!1;const t=e.ui;return!!(typeof t?.resourceUri=="string"&&t.resourceUri.startsWith("ui://")||typeof e["ui/resourceUri"]=="string"&&e["ui/resourceUri"].startsWith("ui://"))}const YOs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=ln(),a=WVt[e.toolType||"tool"],i=QOs(e._meta);return o.jsxs(Kf,{onClick:()=>n.current?.click(),children:[o.jsx(w5t,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Jf,{children:[o.jsx(Xf,{children:o.jsxs("span",{className:"flex items-center gap-2",children:[o.jsx(r,{ref:n,href:s.mcpServerToolLink(t,e.id),children:e.id}),i&&o.jsx(xt,{size:"xs",children:"App"})]})}),o.jsx(dp,{children:e.description})]})]})},KOs=()=>{const{serverId:e}=tr(),{data:t=[],isLoading:n}=d5(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(ZOs,{isLoading:n,server:r})})};function XOs(e){if(!e)return;const t=e.ui;if(t?.resourceUri)return t.resourceUri;const n=e["ui/resourceUri"];if(typeof n=="string")return n}const JOs=({toolId:e,serverId:t})=>{const{canExecute:n}=Wo(),r=n("tools"),s=Ge(),{data:a,isLoading:i,error:l}=IRe(t,e),{mutateAsync:c,isPending:u,data:d}=Nos(t,e),f=a?XOs(a._meta):void 0,{data:h}=mt({queryKey:["mcp-app-resource",t,f],queryFn:async()=>f?(await s.readMcpServerResource(t,f)).contents[0]?.text??null:null,enabled:!!f}),p=g.useCallback(async(y,b)=>await c(b),[c]);g.useEffect(()=>{if(l){const y=l instanceof Error?l.message:"Failed to load tool";Be.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-4",children:[o.jsx(Et,{className:"mb-4 h-8 w-48"}),o.jsx(Et,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-4 py-8 text-center",children:o.jsx(ge,{variant:"ui-sm",className:"text-neutral3",children:"You don't have permission to execute tools."})});let v;try{v=xm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Be.error("Failed to process tool input schema."),v=ws({})}return o.jsxs("div",{className:"flex flex-col gap-4",children:[h&&o.jsx("div",{className:"border-border1 border-b p-4",children:o.jsx(Wqt,{html:h,toolName:a.name??a.id,onToolCall:p})}),o.jsx(HRe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},eCs=()=>{const{serverId:e,toolId:t}=tr(),{data:n,isLoading:r}=IRe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(JOs,{toolId:t,serverId:e})})},SGt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],vI="rootEntityType",yI={tags:"filterTags",entityId:"filterEntityId",entityName:"filterEntityName",runId:"filterRunId",threadId:"filterThreadId",sessionId:"filterSessionId",requestId:"filterRequestId",resourceId:"filterResourceId",userId:"filterUserId",organizationId:"filterOrganizationId",serviceName:"filterServiceName",environment:"filterEnvironment",experimentId:"filterExperimentId",provider:"filterProvider",model:"filterModel"},sK=Object.keys(yI),QPe="mastra:metrics:saved-filters";function tCs(e){const t=iCs(e);try{localStorage.setItem(QPe,t.toString())}catch{}}function nCs(){try{localStorage.removeItem(QPe)}catch{}}function kGt(){try{const e=localStorage.getItem(QPe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function rCs(e){if(e.has(vI))return!0;for(const t of sK)if(e.has(yI[t]))return!0;return!1}function sCs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:SGt.map(u=>({label:u.label,value:u.entityType})),placeholder:"Choose entity type",emptyText:"No entity types."},{id:"entityName",label:"Primitive Name",kind:"pick-multi",options:t.map(u=>({label:u,value:u})),placeholder:"Choose entity names",emptyText:"No entity names found.",isLoading:s?.entityNames},{id:"entityId",label:"Primitive ID",kind:"text"},{id:"tags",label:"Tags",kind:"pick-multi",multi:!0,options:e.map(u=>({label:u,value:u})),placeholder:"Choose tags",emptyText:"No tags found.",isLoading:s?.tags},{id:"serviceName",label:"Service Name",kind:"pick-multi",options:n.map(u=>({label:u,value:u})),placeholder:"Choose service names",emptyText:"No service names found.",isLoading:s?.serviceNames},{id:"environment",label:"Environment",kind:"pick-multi",options:r.map(u=>({label:u,value:u})),placeholder:"Choose environments",emptyText:"No environments found.",isLoading:s?.environments},{id:"threadId",label:"Thread ID",kind:"text"},{id:"resourceId",label:"Resource ID",kind:"text"},{id:"userId",label:"User ID",kind:"text"},{id:"organizationId",label:"Organization ID",kind:"text"},{id:"runId",label:"Run ID",kind:"text"},{id:"sessionId",label:"Session ID",kind:"text"},{id:"requestId",label:"Request ID",kind:"text"},{id:"experimentId",label:"Experiment ID",kind:"text"}],i=(u,d)=>u.label.localeCompare(d.label),l=a.filter(u=>u.kind==="pick-multi").sort(i),c=a.filter(u=>u.kind==="text").sort(i);return[...l,...c]}function aCs(e){const t=[],n=new Map([[vI,"rootEntityType"]]);for(const s of sK)n.set(yI[s],s);const r=new Set;for(const[s]of e.entries()){const a=n.get(s);if(!a||r.has(a))continue;if(r.add(a),a==="tags"){const l=e.getAll(s);if(l.length===0)continue;t.push({fieldId:a,value:l.filter(Boolean)});continue}if(a==="rootEntityType"||a==="entityName"||a==="serviceName"||a==="environment"||a==="provider"||a==="model"){const l=e.getAll(s);if(l.length>1){t.push({fieldId:a,value:l});continue}}const i=e.get(s);i!==null&&t.push({fieldId:a,value:i})}return t}function iCs(e){const t=new URLSearchParams,n=e.getAll(vI);for(const r of n)t.append(vI,r);for(const r of sK){const s=yI[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function oCs(e,t){e.delete(vI);for(const n of sK)e.delete(yI[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?vI:yI[n.fieldId];if(r)if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string"&&a!=="");if(s.length===0){n.fieldId==="tags"&&e.append(r,"");continue}for(const a of s)e.append(r,a)}else typeof n.value=="string"&&e.set(r,n.value.trim())}}const lCs="Any";function Urt(e){const t=e.trim();return t===""||t===lCs}const cCs=new Set(SGt.map(e=>e.entityType));function qrt(e){const t=e.trim();return cCs.has(t)?t:void 0}function uCs(e){const t={};for(const n of e){const r=n.fieldId;if(Array.isArray(n.value)){const s=n.value.filter(a=>typeof a=="string").map(a=>a.trim()).filter(a=>!Urt(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?qrt(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Urt(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=qrt(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const OGt=[{label:"Last 24 hours",value:"24h"},{label:"Last 3 days",value:"3d"},{label:"Last 7 days",value:"7d"},{label:"Last 14 days",value:"14d"},{label:"Last 30 days",value:"30d"}],dCs=new Set(OGt.map(e=>e.value));function fCs(e){return typeof e=="string"&&(dCs.has(e)||e==="custom")}const CGt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function aK(){return g.useContext(CGt)}function hCs(e,t){return e!=="custom"?OGt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${xr(t.from,"MMM d, yyyy")} – ${xr(t.to,"MMM d, yyyy")}`:xr(t.from,"MMM d, yyyy"):"Custom range"}function pCs({children:e,preset:t,filterTokens:n,onPresetChange:r,onFilterTokensChange:s,customRange:a,onCustomRangeChange:i,tracesBasePath:l,logsBasePath:c}){const u=g.useMemo(()=>JSON.stringify(n),[n]),d=g.useMemo(()=>n,[u]),f=g.useMemo(()=>uCs(d),[d]),h=g.useMemo(()=>JSON.stringify(f),[f]),p=hCs(t,a),m=g.useMemo(()=>({datePreset:t,setDatePreset:r,customRange:a,setCustomRange:i??(()=>{}),dateRangeLabel:p,filterTokens:d,setFilterTokens:s,dimensionalFilter:f,dimensionalFilterKey:h,tracesBasePath:l,logsBasePath:c}),[t,r,a,i,p,d,s,f,h,l,c]);return o.jsx(CGt.Provider,{value:m,children:e})}const mCs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function gCs(e){switch(e){case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return"last-24h"}}function vCs(e){switch(e){case"last-3d":return"3d";case"last-7d":return"7d";case"last-14d":return"14d";case"last-30d":return"30d";case"custom":return"custom";default:return"24h"}}function yCs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=aK(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(w4,{preset:gCs(e),onPresetChange:i=>{const l=vCs(i);s.current=l,t(l)},dateFrom:n?.from,dateTo:n?.to,onDateChange:(i,l)=>{if(s.current!=="custom")return;const c={...a.current,[l]:i};a.current=c,r(c)},presets:mCs})}const jwe=1440*60*1e3,bCs={"24h":jwe,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function xCs(e,t,n){if(e!=="custom"){const r=bCs[e]??jwe;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-jwe),end:t?.to??new Date(n)}}function Hm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=aK(),s=g.useRef(null),a=e==="custom"?`custom:${t?.from?.getTime()??""}:${t?.to?.getTime()??""}`:`preset:${e}`;(!s.current||s.current.key!==a)&&(s.current={key:a,anchor:Date.now()});const i=s.current.anchor,l=g.useMemo(()=>xCs(e,t,i),[e,t,i]),c=g.useMemo(()=>({timestamp:l,...n}),[l,r]),u=g.useMemo(()=>`${a}|${r}`,[a,r]);return{datePreset:e,customRange:t,timestamp:l,filters:c,dimensionalFilter:n,filterKey:u}}function _Gt(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function T5({href:e,LinkComponent:t="a"}){return o.jsx(ie,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(Ui,{})})}function wCs({href:e,LinkComponent:t="a"}){return o.jsx(ie,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(onn,{})})}function SCs(e){return e==="agents"||e==="workflows"||e==="tools"}function Vrt(e,t){if(e.length===0)return"0";const n=e.reduce((r,s)=>{const a=s[t];return r+(typeof a=="number"&&Number.isFinite(a)?a:0)},0);return`${Math.round(n/e.length)}`}function kCs(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const OCs=[{dataKey:"p50",label:"p50",color:Xh.blue,aggregate:e=>({value:Vrt(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Xh.yellow,aggregate:e=>({value:Vrt(e,"p95"),suffix:"avg ms"})}];function cle({data:e,onPointClick:t}){return e.length===0?o.jsx(Wt.NoData,{message:"No latency data yet"}):o.jsx(y3,{data:e,series:OCs,onPointClick:t?n=>kCs(n)?t(n):void 0:void 0})}function CCs({data:e,isLoading:t,isError:n,onPointClick:r,actions:s}){const a=(e?.agentData.length??0)>0,i=(e?.workflowData.length??0)>0,l=(e?.toolData.length??0)>0,c={agents:a,workflows:i,tools:l},u=a?"agents":i?"workflows":l?"tools":"agents",[d,f]=g.useState("agents"),h=c[d]?d:u,p=typeof s=="function"?s(h):s,m=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),v=e?Object.values(e).filter(Array.isArray).flat().map(b=>b.p50).filter(b=>typeof b=="number"):[],y=v.length>0?`${Math.round(v.reduce((b,x)=>b+x,0)/v.length)}ms`:"—";return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(Wt.Summary,{value:y,label:"Avg p50"}),p?o.jsx(Wt.Actions,{children:p}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load latency data"}):o.jsx(Wt.Content,{children:m?o.jsxs(kl,{value:h,onValueChange:b=>{SCs(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(Sl,{children:[o.jsx(kr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(kr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(kr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Hr,{value:"agents",children:o.jsx(cle,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Hr,{value:"workflows",children:o.jsx(cle,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Hr,{value:"tools",children:o.jsx(cle,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(Wt.NoData,{message:"No latency data yet"})})]})}function _Cs(e){switch(e){case"24h":return"last-24h";case"3d":return"last-3d";case"7d":return"last-7d";case"14d":return"last-14d";case"30d":return"last-30d";case"custom":return"custom";default:return}}function ECs(e,t){if(t==="1h"){const s=new Date(e);s.setUTCMinutes(0,0,0);const a=new Date(s.getTime()+3600*1e3);return{from:s,to:a}}const n=new Date(e);n.setUTCHours(0,0,0,0);const r=new Date(n.getTime()+1440*60*1e3);return{from:n,to:r}}function EGt(e,t,n,r,s,a,i){if(i){e.set(t,"custom"),e.set(n,i.from.toISOString()),e.set(r,i.to.toISOString());return}if(s==="custom"){e.set(t,"custom"),a?.from&&e.set(n,a.from.toISOString()),a?.to&&e.set(r,a.to.toISOString());return}const l=_Cs(s);l&&e.set(t,l)}function $o(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function TGt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function Hrt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(tS,"branches"),EGt(a,nS,sj,aj,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(s0,i),r.status&&a.set(a0,r.status),$o(a,Il.entityName,r.entityName??n.entityName),$o(a,Il.threadId,r.threadId??n.threadId),$o(a,Il.resourceId,r.resourceId??n.resourceId),$o(a,Il.entityId,n.entityId),$o(a,Il.runId,n.runId),$o(a,Il.sessionId,n.sessionId),$o(a,Il.requestId,n.requestId),$o(a,Il.userId,n.userId),$o(a,Il.organizationId,n.organizationId),$o(a,Il.experimentId,n.experimentId),$o(a,Il.serviceName,n.serviceName),$o(a,Il.environment,n.environment),TGt(a,Il.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function TCs({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;EGt(a,lx,cx,ux,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(i0,i),$o(a,Al.entityName,r.entityName??n.entityName),$o(a,Al.threadId,r.threadId??n.threadId),$o(a,Al.resourceId,r.resourceId??n.resourceId),$o(a,Al.runId,n.runId),$o(a,Al.sessionId,n.sessionId),$o(a,Al.requestId,n.requestId),$o(a,Al.userId,n.userId),$o(a,Al.organizationId,n.organizationId),$o(a,Al.experimentId,n.experimentId),$o(a,Al.serviceName,n.serviceName),$o(a,Al.environment,n.environment),TGt(a,Al.tags,n.tags),r.status==="error"&&a.append(Al.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function WA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=aK(),a=g.useCallback((c={})=>Hrt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>TCs({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=ECs(u,d);return Hrt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const jGt="1h";async function ule(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:jGt,filters:n}),s=r.series.find(l=>l.percentile===.5),a=r.series.find(l=>l.percentile===.95);if(!s||!a)return[];const i=new Map(a.points.map(l=>[new Date(l.timestamp).getTime(),l.value]));return s.points.map(l=>{const c=new Date(l.timestamp),u=c.getTime();return{time:c.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}),tsMs:u,p50:Math.round(l.value),p95:Math.round(i.get(u)??0)}})}function jCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([ule(e,"mastra_agent_duration_ms",t),ule(e,"mastra_workflow_duration_ms",t),ule(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:jGt}}})}const Wrt={agents:Qu.AGENT,workflows:Qu.WORKFLOW_RUN,tools:Qu.TOOL};function NCs(){const{data:e,isLoading:t,isError:n}=jCs(),{getTracesHref:r,getBucketTracesHref:s}=WA(),{Link:a}=ln(),i=zr();return o.jsx(CCs,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Wrt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(T5,{href:r({rootEntityType:Wrt[l]}),LinkComponent:a})})}function ICs(e){return e==="threads"||e==="resources"}function dle(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function ACs({threads:e,resources:t,getThreadRowHref:n,getResourceRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("threads"),c=e.data?.map(y=>({...y,key:y.threadId}))??[],u=t.data?.map(y=>({...y,key:y.resourceId}))??[],d=c.length>0,f=u.length>0,h=e.data?.reduce((y,b)=>y+b.runs,0)??0,p=t.data?.reduce((y,b)=>y+b.threadCount,0)??0,m=i==="threads"?e:t,v=typeof s=="function"?s(i):s;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(Wt.Summary,{value:h.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(Wt.Summary,{value:p.toLocaleString(),label:"Total threads"}),v?o.jsx(Wt.Actions,{children:v}):null]}),m.isLoading?o.jsx(Wt.Loading,{}):m.isError?o.jsx(Wt.Error,{message:"Failed to load memory data"}):o.jsx(Wt.Content,{children:o.jsxs(kl,{defaultTab:"threads",value:i,onValueChange:y=>{ICs(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Sl,{children:[o.jsx(kr,{value:"threads",children:"Threads"}),o.jsx(kr,{value:"resources",children:"Resources"})]}),o.jsx(Hr,{value:"threads",children:d?o.jsxs(be,{columns:"auto auto auto auto auto",...dwe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:dle(y.threadId)}),o.jsx(be.NumberCell,{children:y.resourceId?dle(y.resourceId):"—"}),o.jsx(be.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(be.NumberCell,{children:y.tokens>0?ao(y.tokens):"—"}),o.jsx(be.NumberCell,{children:y.cost!=null?Ud(y.cost,y.costUnit):"—"})]});return b?o.jsx(be.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(be.RowStatic,{children:x},y.key)})]}):o.jsx(Wt.NoData,{message:"No thread activity yet"})}),o.jsx(Hr,{value:"resources",children:f?o.jsxs(be,{columns:"auto auto auto auto",...dwe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:dle(y.resourceId)}),o.jsx(be.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(be.NumberCell,{children:y.tokens>0?ao(y.tokens):"—"}),o.jsx(be.NumberCell,{children:y.cost!=null?Ud(y.cost,y.costUnit):"—"})]});return b?o.jsx(be.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(be.RowStatic,{children:x},y.key)})]}):o.jsx(Wt.NoData,{message:"No resource activity yet"})})]})})]})}const fle=20;function RCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","top-active-threads",n],queryFn:async()=>{const r={groupBy:["threadId","resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count",limit:fle}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:fle}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:fle})]),l=new Map,c=d=>DA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.threadId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.threadId).map(d=>{const f=d.dimensions.threadId,h=l.get(f);return{threadId:f,resourceId:d.dimensions.resourceId??null,runs:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}const hle=20;function PCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","top-resources-by-threads",n],queryFn:async()=>{const r={groupBy:["resourceId"],orderDirection:"DESC",filters:t},[s,a,i]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",limit:hle}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:hle}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:hle})]),l=new Map,c=d=>DA(l,d,()=>({tokens:0,cost:null,costUnit:null})),u=d=>{for(const f of d){const h=f.dimensions.resourceId;if(!h)continue;const p=c(h);p.tokens+=f.value,f.estimatedCost!=null&&(p.cost=(p.cost??0)+f.estimatedCost,f.costUnit&&(p.costUnit=f.costUnit))}};return u(a.groups),u(i.groups),s.groups.filter(d=>!!d.dimensions.resourceId).map(d=>{const f=d.dimensions.resourceId,h=l.get(f);return{resourceId:f,threadCount:d.value,tokens:h?.tokens??0,cost:h?.cost??null,costUnit:h?.costUnit??null}})}})}function $Cs(){const e=RCs(),t=PCs(),{getTracesHref:n}=WA(),{Link:r}=ln();return o.jsx(ACs,{threads:{data:e.data,isLoading:e.isLoading,isError:e.isError},resources:{data:t.data,isLoading:t.isLoading,isError:t.isError},LinkComponent:r,getThreadRowHref:s=>n({threadId:s.threadId,...s.resourceId?{resourceId:s.resourceId}:{}}),getResourceRowHref:s=>n({resourceId:s.resourceId})})}function j5({label:e,value:t,prevValue:n,changePct:r,isLoading:s,isError:a}){const i=t!=null;return o.jsxs(Jr,{children:[o.jsx(Jr.Label,{children:e}),o.jsx(Jr.Value,{className:i?void 0:"invisible",children:i?t:"—"}),a?o.jsx(Jr.Error,{}):s?o.jsx(Jr.Loading,{}):i?r!=null?o.jsx(Jr.Change,{changePct:r,prevValue:n}):o.jsx(Jr.NoChange,{}):o.jsx(Jr.NoData,{})]})}function MCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","active-resources-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"resourceId",filters:t,comparePeriod:"previous_period"})})}function DCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","active-threads-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count_distinct",distinctColumn:"threadId",filters:t,comparePeriod:"previous_period"})})}function LCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","model-cost-kpi",n],queryFn:async()=>{const r=await e.getMetricAggregate({name:["mastra_model_total_input_tokens","mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"});return{cost:r.estimatedCost??null,costUnit:r.costUnit??null,previousCost:r.previousEstimatedCost??null,costChangePercent:r.costChangePercent??null}}})}function FCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","total-tokens-kpi",n],queryFn:async()=>{const[r,s]=await Promise.all([e.getMetricAggregate({name:["mastra_model_total_input_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"}),e.getMetricAggregate({name:["mastra_model_total_output_tokens"],aggregation:"sum",filters:t,comparePeriod:"previous_period"})]),a=r.value!=null||s.value!=null,i=r.previousValue!=null||s.previousValue!=null,l=(r.value??0)+(s.value??0),c=(r.previousValue??0)+(s.previousValue??0),u=i&&c>0?(l-c)/c*100:null;return{value:a?l:null,previousValue:i?c:null,changePercent:u}}})}function zCs(){const{data:e,isLoading:t,isError:n}=_Gt();return o.jsx(j5,{label:"Total Agent Runs",value:e?.value!=null?e.value.toLocaleString():null,prevValue:e?.previousValue!=null?e.previousValue.toLocaleString():void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function BCs(){const{data:e,isLoading:t,isError:n}=LCs();return o.jsx(j5,{label:"Total Model Cost",value:e?.cost!=null?Ud(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Ud(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function UCs(){const{data:e,isLoading:t,isError:n}=FCs();return o.jsx(j5,{label:"Total Tokens",value:e?.value!=null?ao(e.value):null,prevValue:e?.previousValue!=null?ao(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function qCs(){const{data:e,isLoading:t,isError:n}=DCs();return o.jsx(j5,{label:"Total Threads",value:e?.value!=null?ao(e.value):null,prevValue:e?.previousValue!=null?ao(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function VCs(){const{data:e,isLoading:t,isError:n}=MCs();return o.jsx(j5,{label:"Total Resources",value:e?.value!=null?ao(e.value):null,prevValue:e?.previousValue!=null?ao(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function HCs({onClear:e,onRemoveAll:t,onSave:n,onRemoveSaved:r,isLoading:s,filterFields:a,filterTokens:i,onFilterTokensChange:l,autoFocusFilterFieldId:c}){const u=i.length>0,d=i.some(f=>WCs(f,a));return u?o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(APe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(NPe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]}):null}function WCs(e,t){const n=t.find(r=>r.id===e.fieldId);return n?n.kind==="text"?typeof e.value=="string"&&e.value.trim()!=="":n.kind==="pick-multi"?n.multi?Array.isArray(e.value)&&e.value.length>0:typeof e.value=="string"&&e.value!==""&&e.value!=="Any":n.kind==="multi-select"?Array.isArray(e.value)&&e.value.length>0:!1:!1}function ZCs({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Model Usage & Cost",description:"Token consumption by model."}),i&&(()=>{const l=e.reduce((d,f)=>d+(f.cost??0),0),c=new Set;for(const d of e)d.cost!=null&&d.costUnit&&c.add(d.costUnit);let u;return c.size===0?u=l>0?Ud(l):"—":c.size===1?u=l>0?Ud(l,[...c][0]):"—":u="Mixed",o.jsx(Wt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(Wt.Actions,{children:s}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load model usage data"}):o.jsx(Wt.Content,{children:i?o.jsxs(be,{columns:"auto auto auto auto auto auto",...dwe,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{sticky:"start",children:"Model"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(be.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(be.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(be.NumberCell,{children:l.input}),o.jsx(be.NumberCell,{children:l.output}),o.jsx(be.NumberCell,{children:l.cacheRead}),o.jsx(be.NumberCell,{children:l.cacheWrite}),o.jsx(be.NumberCell,{highlight:!0,children:l.cost!=null?Ud(l.cost,l.costUnit):"—"})]});return c?o.jsx(be.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(be.RowStatic,{children:u},l.model)})]}):o.jsx(Wt.NoData,{message:"No model usage data yet"})})]})}function GCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","model-usage-cost",n],queryFn:async()=>{const[r,s,a,i]=await Promise.all(["mastra_model_total_input_tokens","mastra_model_total_output_tokens","mastra_model_input_cache_read_tokens","mastra_model_input_cache_write_tokens"].map(d=>e.getMetricBreakdown({name:[d],groupBy:["model"],aggregation:"sum",orderDirection:"DESC",filters:t})));if(!r||!s||!a||!i)return[];const l=new Map,c=d=>DA(l,d,()=>({input:0,output:0,cacheRead:0,cacheWrite:0,cost:null,costUnit:null})),u=(d,f)=>{f.estimatedCost!=null&&(d.cost=(d.cost??0)+f.estimatedCost,f.costUnit&&(d.costUnit=f.costUnit))};for(const d of r.groups){const f=d.dimensions.model??"unknown",h=c(f);h.input=d.value,u(h,d)}for(const d of s.groups){const f=d.dimensions.model??"unknown",h=c(f);h.output=d.value,u(h,d)}for(const d of a.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheRead=d.value}for(const d of i.groups){const f=d.dimensions.model??"unknown",h=c(f);h.cacheWrite=d.value}return Array.from(l.entries()).map(([d,f])=>({model:d,input:ao(f.input),output:ao(f.output),cacheRead:ao(f.cacheRead),cacheWrite:ao(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function QCs(){const{data:e,isLoading:t,isError:n}=GCs(),{getTracesHref:r}=WA(),{Link:s}=ln();return o.jsx(ZCs,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Qu.AGENT}),actions:o.jsx(T5,{href:r({rootEntityType:Qu.AGENT}),LinkComponent:s})})}function YCs(e){return e==="tokens"||e==="cost"}function KCs({data:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const[i,l]=g.useState("tokens"),c=e??[],u=c.length>0,d=c.reduce((b,x)=>b+x.total,0),f=c.filter(b=>b.cost!=null&&b.cost>0),h=new Set(f.map(b=>b.costUnit??"usd")),p=h.size<=1,m=p?[...h][0]??"usd":null,v=p?f.reduce((b,x)=>b+(x.cost??0),0):0,y=p&&v>0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(Wt.Summary,{value:Ud(v,m),label:"Total cost"}):o.jsx(Wt.Summary,{value:ao(d),label:"Total tokens"})),u&&s?o.jsx(Wt.Actions,{children:s}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load token usage data"}):o.jsx(Wt.Content,{children:u?o.jsxs(kl,{defaultTab:"tokens",value:i,onValueChange:b=>{YCs(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Sl,{children:[o.jsx(kr,{value:"tokens",children:"Tokens"}),o.jsx(kr,{value:"cost",children:"Cost"})]}),o.jsx(Hr,{value:"tokens",children:o.jsx(gI,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Xh.blueDark},{label:"Output",color:Xh.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:ao})}),o.jsx(Hr,{value:"cost",children:y?o.jsx(gI,{LinkComponent:a,data:f.slice().sort((b,x)=>(x.cost??0)-(b.cost??0)).map(b=>({name:b.name,values:[b.cost],href:r?.(b)})),segments:[{label:"Cost",color:Xh.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Ud(b,m)}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function XCs(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","token-usage-by-agent",n],queryFn:async()=>{const r={groupBy:["entityName"],aggregation:"sum",orderDirection:"DESC",filters:t},[s,a]=await Promise.all([e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"]}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"]})]),i=new Map,l=u=>DA(i,u,()=>({input:0,output:0,cost:null,costUnit:null})),c=(u,d)=>{d.estimatedCost!=null&&(u.cost=(u.cost??0)+d.estimatedCost,d.costUnit&&(u.costUnit=d.costUnit))};for(const u of s.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.input=u.value,c(f,u)}for(const u of a.groups){const d=u.dimensions.entityName??"unknown",f=l(d);f.output=u.value,c(f,u)}return Array.from(i.entries()).map(([u,d])=>({name:u,input:d.input,output:d.output,total:d.input+d.output,cost:d.cost,costUnit:d.costUnit})).sort((u,d)=>d.total-u.total)}})}function JCs(){const{data:e,isLoading:t,isError:n}=XCs(),{getTracesHref:r}=WA(),{Link:s}=ln();return o.jsx(KCs,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Qu.AGENT,entityName:a.name}),actions:o.jsx(T5,{href:r({rootEntityType:Qu.AGENT}),LinkComponent:s})})}function Nwe(e,t=ao){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const e_s=[{dataKey:"input",label:"Input tokens",color:Xh.blue,aggregate:Nwe("input")},{dataKey:"output",label:"Output tokens",color:Xh.yellow,aggregate:Nwe("output")}];function t_s(e){return e==="tokens"||e==="cost"}function n_s({data:e,interval:t="1d",isLoading:n,isError:r,actions:s}){const[a,i]=g.useState("tokens"),l=e??[],c=l.map(k=>({...k})),u=l.length>0,d=l.reduce((k,O)=>k+O.total,0),f=l.filter(k=>k.cost!=null&&k.cost>0),h=f.map(k=>({...k})),p=new Set(f.map(k=>k.costUnit).filter(k=>!!k)),m=p.size===1&&f.every(k=>k.costUnit!=null),v=m?[...p][0]??null:null,y=m?f.reduce((k,O)=>k+(O.cost??0),0):0,b=m&&y>0,x=t==="1h"?"Input and output tokens per hour.":"Input and output tokens per day.",w=[{dataKey:"cost",label:"Cost",color:Xh.purple,aggregate:Nwe("cost",k=>Ud(k,v))}];return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(Wt.Summary,{value:Ud(y,v),label:"Total cost"}):o.jsx(Wt.Summary,{value:ao(d),label:"Total tokens"})),u&&s?o.jsx(Wt.Actions,{children:s}):null]}),n?o.jsx(Wt.Loading,{}):r?o.jsx(Wt.Error,{message:"Failed to load token usage timeline"}):o.jsx(Wt.Content,{children:u?o.jsxs(kl,{defaultTab:"tokens",value:a,onValueChange:k=>{t_s(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(Sl,{children:[o.jsx(kr,{value:"tokens",children:"Tokens"}),o.jsx(kr,{value:"cost",children:"Cost"})]}),o.jsx(Hr,{value:"tokens",children:o.jsx(y3,{data:c,series:e_s})}),o.jsx(Hr,{value:"cost",children:b?o.jsx(y3,{data:h,series:w}):o.jsx(Wt.NoData,{message:"No cost data yet"})})]}):o.jsx(Wt.NoData,{message:"No token usage data yet"})})]})}function r_s(e){return e==="24h"?"1h":"1d"}function s_s(e,t){return t==="1h"?e.toLocaleTimeString("en-US",{hour:"2-digit",minute:"2-digit",hour12:!1}):e.toLocaleDateString("en-US",{month:"short",day:"2-digit"})}function Zrt(e,t,n){for(const r of t?.points??[]){const s=new Date(r.timestamp).getTime();if(!Number.isFinite(s))continue;const a=e.get(s)??{tsMs:s,input:0,output:0,cost:null,costUnits:new Set,hasUnknownCostUnit:!1};a[n]+=r.value,r.estimatedCost!=null&&(a.cost=(a.cost??0)+r.estimatedCost,t?.costUnit?a.costUnits.add(t.costUnit):a.hasUnknownCostUnit=!0),e.set(s,a)}}function a_s(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function i_s(){const e=Ge(),{datePreset:t,filters:n,filterKey:r}=Hm(),s=r_s(t);return mt({queryKey:["metrics","token-usage-timeseries",r,s],queryFn:async()=>{const[a,i]=await Promise.all([e.getMetricTimeSeries({name:["mastra_model_total_input_tokens"],interval:s,aggregation:"sum",filters:n}),e.getMetricTimeSeries({name:["mastra_model_total_output_tokens"],interval:s,aggregation:"sum",filters:n})]),l=new Map;return Zrt(l,a.series[0],"input"),Zrt(l,i.series[0],"output"),{data:Array.from(l.values()).sort((u,d)=>u.tsMs-d.tsMs).map(u=>{const d=new Date(u.tsMs);return{time:s_s(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:a_s(u)}}),interval:s}}})}function o_s(){const{data:e,isLoading:t,isError:n}=i_s(),{getTracesHref:r}=WA(),{Link:s}=ln();return o.jsx(n_s,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(T5,{href:r(),LinkComponent:s})})}function ple({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(gI,{LinkComponent:r,data:e.map(s=>{const a=n?.(s),i=t?.(s);return a?{name:s.name,values:[s.completed,s.errors],hrefs:[i,a]}:{name:s.name,values:[s.completed,s.errors],href:i}}),segments:[{label:"Completed",color:Xh.blueDark},{label:"Errors",color:Xh.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:ao})}function l_s({data:e,isLoading:t,isError:n,getRowHref:r,getErrorSegmentHref:s,actions:a,LinkComponent:i}){const[l,c]=g.useState("agents"),u=typeof a=="function"?a(l):a,d=!!e&&(e.agentData.length>0||e.workflowData.length>0||e.toolData.length>0),f=e?[...e.agentData,...e.workflowData,...e.toolData].reduce((m,v)=>m+v.completed+v.errors,0):0,h=m=>r?v=>r(m,v):void 0,p=m=>s?v=>s(m,v):void 0;return o.jsxs(Wt,{children:[o.jsxs(Wt.TopBar,{children:[o.jsx(Wt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(Wt.Summary,{value:ao(f),label:"Total runs"}),u?o.jsx(Wt.Actions,{children:u}):null]}),t?o.jsx(Wt.Loading,{}):n?o.jsx(Wt.Error,{message:"Failed to load trace volume data"}):o.jsx(Wt.Content,{children:d?o.jsxs(kl,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(Sl,{children:[o.jsx(kr,{value:"agents",children:"Agents"}),o.jsx(kr,{value:"workflows",children:"Workflows"}),o.jsx(kr,{value:"tools",children:"Tools"})]}),o.jsx(Hr,{value:"agents",children:e.agentData.length>0?o.jsx(ple,{data:e.agentData,rowHrefs:h("agents"),errorHrefs:p("agents"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No agent data yet"})}),o.jsx(Hr,{value:"workflows",children:e.workflowData.length>0?o.jsx(ple,{data:e.workflowData,rowHrefs:h("workflows"),errorHrefs:p("workflows"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No workflow data yet"})}),o.jsx(Hr,{value:"tools",children:e.toolData.length>0?o.jsx(ple,{data:e.toolData,rowHrefs:h("tools"),errorHrefs:p("tools"),LinkComponent:i}):o.jsx(Wt.NoData,{message:"No tool data yet"})})]}):o.jsx(Wt.NoData,{message:"No trace volume data yet"})})]})}async function mle(e,t,n){const r=await e.getMetricBreakdown({name:[t],groupBy:["entityName","status"],aggregation:"count",orderDirection:"DESC",filters:n}),s=new Map;for(const a of r.groups){const i=a.dimensions.entityName??"unknown",l=a.dimensions.status??"ok",c=DA(s,i,()=>({completed:0,errors:0}));l==="error"?c.errors+=a.value:c.completed+=a.value}return Array.from(s.entries()).map(([a,i])=>({name:a,...i})).sort((a,i)=>i.completed+i.errors-(a.completed+a.errors))}function c_s(){const e=Ge(),{filters:t,filterKey:n}=Hm();return mt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([mle(e,"mastra_agent_duration_ms",t),mle(e,"mastra_workflow_duration_ms",t),mle(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const V8={agents:Qu.AGENT,workflows:Qu.WORKFLOW_RUN,tools:Qu.TOOL};function u_s(){const{data:e,isLoading:t,isError:n}=c_s(),{getTracesHref:r,getLogsHref:s}=WA(),{Link:a}=ln();return o.jsx(l_s,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:V8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:V8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(T5,{href:r({rootEntityType:V8[i]}),LinkComponent:a}),o.jsx(wCs,{href:s({rootEntityType:V8[i],status:"error"}),LinkComponent:a})]})})}const gle="period",H8="dateFrom",W8="dateTo";function d_s(){const[e,t]=da(),n=e.get(gle),r=fCs(n)?n:"24h",s=g.useMemo(()=>{if(r!=="custom")return;const d=p=>{if(!p)return;const m=new Date(p);return Number.isNaN(m.getTime())?void 0:m},f=d(e.get(H8)),h=d(e.get(W8));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),a=g.useMemo(()=>aCs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(gle):h.set(gle,d),d!=="custom"&&(h.delete(H8),h.delete(W8)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(H8,d.from.toISOString()):h.delete(H8),d?.to?h.set(W8,d.to.toISOString()):h.delete(W8),h},{replace:!0})},[t]),c=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return oCs(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,rCs(e)))return;const d=kGt();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),o.jsx(pCs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(f_s,{})})}function f_s(){const[e]=da(),{error:t,isLoading:n}=_Gt(),{filterTokens:r,setFilterTokens:s}=aK(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=NY(),{data:d,isLoading:f}=FPe(),{data:h,isLoading:p}=MPe(),{data:m,isLoading:v}=LPe(),{data:y,isLoading:b}=DPe(),x=g.useMemo(()=>sCs({availableTags:d??[],availableEntityNames:h??[],availableServiceNames:m??[],availableEnvironments:y??[],loading:{tags:f,entityNames:p,serviceNames:v,environments:b}}),[d,h,m,y,f,p,v,b]),[w,k]=g.useState(()=>kGt()!==null),O=g.useCallback(()=>{tCs(e),k(!0),Be.success("Filters setting for Metrics saved")},[e]),_=g.useCallback(()=>{nCs(),k(!1),Be.success("Filters setting for Metrics cleared up")},[]),T=g.useCallback(()=>{s([])},[s]),E=g.useCallback(()=>{const N=r.map(I=>{const A=x.find($=>$.id===I.fieldId);return A?A.kind==="text"?{fieldId:I.fieldId,value:""}:A.kind==="pick-multi"?A.multi?{fieldId:I.fieldId,value:[]}:{fieldId:I.fieldId,value:"Any"}:A.kind==="multi-select"?{fieldId:I.fieldId,value:[]}:I:I});s(N)},[x,r,s]);return t&&ms(t)?o.jsx(Qn,{children:o.jsx(zs,{})}):t&&gs(t)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"metrics"})}):t?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Bt,{width:"wide",height:"full",children:[o.jsxs(Bt.TopArea,{children:[o.jsx(Bt.Row,{children:o.jsxs(Bt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(yCs,{}),o.jsx(RPe,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(HCs,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:E,onRemoveAll:T,onSave:O,onRemoveSaved:w?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-4 pb-6",children:[c&&o.jsx(Nn,{variant:"info",title:"Metrics are not persisted",children:o.jsx(Nn.Message,{children:"This project uses in-memory storage for observability. Metrics will be lost on every server restart. For persistent metrics, switch the observability storage to ClickHouse, DuckDB, Postgres v-next, or Spanner."})}),o.jsxs(Owe,{children:[o.jsx(zCs,{}),o.jsx(BCs,{}),o.jsx(UCs,{}),o.jsx(qCs,{}),o.jsx(VCs,{})]}),o.jsxs(Owe,{children:[o.jsx(QCs,{}),o.jsx(JCs,{}),o.jsx(o_s,{}),o.jsx($Cs,{}),o.jsx(u_s,{}),o.jsx(NCs,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(mr,{iconSlot:o.jsx(Os,{}),titleSlot:"Metrics are not available with your current storage",descriptionSlot:"Metrics require ClickHouse, DuckDB, Postgres v-next, Spanner, or in-memory storage for observability. Other relational databases (LibSQL, MSSQL) and document stores (MongoDB) do not support metrics collection. To enable metrics on an existing project, switch the observability storage in the Mastra configuration.",actionSlot:o.jsx(ie,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",icon:o.jsx(Cs,{}),children:"Metrics Documentation"})})})]})}function Grt(){const{isCmsAvailable:e}=ob(),{Link:t,paths:n}=ln();return e?o.jsx(nv,{owner:"prompt-block-list",children:o.jsx(Fx,{as:t,to:n.cmsPromptBlockCreateLink(),tooltip:"Create a prompt",variant:"ghost",size:"sm",children:"New prompt"})}):null}const h_s=50;function p_s(){const[e,t]=g.useState(""),[n,r]=g.useState(0),{data:s,isLoading:a,error:i,isPlaceholderData:l}=KVt({page:n,perPage:h_s}),c=s?.promptBlocks??[],u=s?.hasMore??!1,d=g.useCallback(()=>{l||r(p=>p+1)},[l]),f=g.useCallback(()=>{l||r(p=>Math.max(0,p-1))},[l]),h=g.useCallback(p=>{t(p),r(0)},[]);return i&&ms(i)?o.jsx(Qn,{children:o.jsx(zs,{})}):i&&gs(i)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"prompt blocks"})}):i?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load prompt blocks",message:i.message})}):c.length===0&&!a&&n===0?o.jsxs(Qn,{children:[o.jsx(Grt,{}),o.jsx(Jfs,{})]}):o.jsxs(Bt,{height:"full",children:[o.jsx(Grt,{}),o.jsx(Bt.TopArea,{children:o.jsx(Bt.Row,{align:"center",stack:"responsive",children:o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(qc,{onSearch:h,label:"Filter prompts",placeholder:"Filter by name or description"})})})}),o.jsx(Xfs,{promptBlocks:c,isLoading:a,search:e,currentPage:n,hasMore:u,onNextPage:d,onPrevPage:f})]})}function m_s(){return o.jsx(Bt,{width:"narrow",children:o.jsx(Bt.MainArea,{children:o.jsx(ils,{children:o.jsx(q0e,{})})})})}const g_s=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:jen,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:Rdt,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Cs,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:R3,href:"https://discord.gg/mastra-ai",external:!0},{title:"Share with your team",description:"Running Mastra Studio locally? Deploy to the cloud so your team can collaborate.",icon:Mdt,href:"https://mastra.ai/cloud",external:!0},{title:"Talk to our Sales team",description:"Get a custom demo, discuss on-prem deployments, and how we can help you accelerate getting agents into production.",icon:Pdt,href:"https://mastra.ai/contact?ref=studio",external:!0}];function v_s(){return o.jsx(Bt,{width:"narrow",children:o.jsx(Bt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:g_s.map(e=>o.jsxs("a",{href:e.href,...e.external?{target:"_blank",rel:"noreferrer"}:{},className:"group border-border1 bg-surface2 hover:border-accent1 hover:bg-surface3 flex flex-col gap-3 rounded-lg border p-5 transition-colors",children:[o.jsxs("div",{className:"flex items-center gap-2.5",children:[o.jsx(e.icon,{className:"text-icon3 group-hover:text-accent1 h-5 w-5 transition-colors"}),o.jsx("span",{className:"text-ui-md text-text1 font-medium",children:e.title}),e.external&&o.jsx(Cs,{className:"text-icon3 ml-auto h-3.5 w-3.5 opacity-0 transition-opacity group-hover:opacity-100"})]}),o.jsx("p",{className:"text-ui-sm text-text3",children:e.description})]},e.href))})})})}function Qrt(){const{isCmsAvailable:e}=ob(),{Link:t,paths:n}=ln();return e?o.jsx(nv,{owner:"scorer-list",children:o.jsx(Fx,{as:t,to:n.cmsScorersCreateLink(),tooltip:"Create a scorer",variant:"ghost",size:"sm",children:"New scorer"})}):null}function y_s(){const{data:e={},isLoading:t,error:n}=tf(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&ms(n))return o.jsx(Qn,{children:o.jsx(zs,{})});if(n&&gs(n))return o.jsx(Qn,{children:o.jsx(Ts,{resource:"scorers"})});if(n)return o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsxs(Qn,{children:[o.jsx(Qrt,{}),o.jsx(nus,{})]});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Bt,{height:"full",children:[o.jsx(Qrt,{}),o.jsx(Bt.TopArea,{children:o.jsx(sus,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(tus,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}const NGt=["input","entity"],b_s={input:"Input",entity:"Entity"};function x_s(e){const t=["auto","auto","minmax(0, 10rem)"];return e.has("entity")&&t.push("minmax(0, 14rem)"),e.has("input")&&t.push("minmax(0, 40rem)"),t.join(" ")}function w_s(){const[e,t]=g.useState(new Set),n=g.useMemo(()=>new Set(NGt.filter(a=>!e.has(a))),[e]),r=g.useMemo(()=>x_s(n),[n]),s=g.useCallback(a=>{t(i=>{const l=new Set(i);return l.has(a)?l.delete(a):l.add(a),l})},[]);return{visibleColumns:n,columns:r,toggleColumn:s}}function S_s({visibleColumns:e,toggleColumn:t}){return o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{icon:o.jsx(ime,{}),children:"Columns"})}),o.jsxs(ot.Content,{align:"end",children:[o.jsx(ot.Label,{children:"Toggle columns"}),NGt.map(n=>o.jsx(ot.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:b_s[n]},n))]})]})}function k_s(){const{scorerId:e}=tr(),[t,n]=da(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=zr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=$cs(e),p=w_s(),{data:m={},isLoading:v,error:y}=Yf(),{isLoading:b,error:x}=Bm(),{data:w=[],isLoading:k,error:O,isFetchingNextPage:_,hasNextPage:T,setEndOfListElement:E}=Pcs({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),N=g.useMemo(()=>f?.agentIds?.filter(U=>m[U]).map(U=>({value:U,label:m[U].name,type:"AGENT"}))||[],[f?.agentIds,m]),I=g.useMemo(()=>f?.workflowIds?.map(U=>({value:U,label:U,type:"WORKFLOW"}))||[],[f?.workflowIds]),A=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...N,...I],[N,I]),$=t.get("entity")??"all",z=A.find(U=>U.value===$);z&&z.value!==u?.value&&d(z),g.useEffect(()=>{if(h){const U=h instanceof Error?h.message:"Failed to load scorer";Be.error(`Error loading scorer: ${U}`)}},[h]),g.useEffect(()=>{if(y){const U=y instanceof Error?y.message:"Failed to load agents";Be.error(`Error loading agents: ${U}`)}},[y]),g.useEffect(()=>{if(x){const U=x instanceof Error?x.message:"Failed to load workflows";Be.error(`Error loading workflows: ${U}`)}},[x]);const D=U=>{U?.value&&n(Q=>{const te=new URLSearchParams(Q);return te.set("entity",U.value),te})};g.useEffect(()=>{const U=t.get("scoreId")??void 0;if(U===s)return;if(!U){a(void 0);return}w.find(te=>te.id===U)&&a(U)},[t,w]);const q=g.useCallback(U=>{a(U||void 0),n(Q=>{const te=new URLSearchParams(Q);return U?te.set("scoreId",U):te.delete("scoreId"),te})},[n]);if(!f)return null;const H=ms(h)||ms(y)||ms(x),V=h&&gs(h),B=!H&&!V&&(h||y||x),W=!k&&w.length===0,L=u?.value!=="all",G=f?.scorer?.source==="stored",M=e?o.jsx(nK,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:U=>{c(`/experiments/${U}`)}}):null,R=G?o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(ie,{size:"lg","aria-label":"Scorer actions menu",children:o.jsx(d1,{})})}),o.jsx(ot.Content,{align:"end",className:"w-48",children:o.jsxs(ot.Item,{onSelect:()=>{c(`/cms/scorers/${e}/edit`)},children:[o.jsx(Yu,{})," Edit Scorer"]})})]}):null;if(H||V||B||W&&!L){const U=(h instanceof Error?h.message:void 0)??(y instanceof Error?y.message:void 0)??(x instanceof Error?x.message:void 0)??"An unexpected error occurred",Q=H||V||B;return o.jsxs(Bt,{width:"wide",height:"full",className:Q||!R?"grid-rows-[1fr]":void 0,children:[!Q&&R&&o.jsx(Bt.TopArea,{children:o.jsx(Wr,{className:"ml-auto",children:R})}),o.jsx(Bt.MainArea,{isCentered:!0,children:H?o.jsx(zs,{}):V?o.jsx(Ts,{resource:"scorers"}):B?o.jsx(Fs,{title:"Failed to load scorer",message:U}):o.jsx(Ecs,{onRunExperiment:()=>l(!0)})}),M]})}return o.jsxs(Bt,{width:"wide",height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(Tcs,{selectedEntity:u,entityOptions:A,onEntityChange:D,onReset:()=>{n(U=>{const Q=new URLSearchParams(U);return Q.set("entity","all"),Q})},isLoading:k||v||b}),o.jsxs(Wr,{children:[o.jsx(S_s,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),o.jsx(ie,{variant:"primary",onClick:()=>l(!0),icon:o.jsx(oc,{}),children:"Run Experiment"}),R]})]})}),o.jsx(_cs,{scores:w,isLoading:k,selectedScoreId:s,isFetchingNextPage:_,hasNextPage:T,setEndOfListElement:E,onScoreClick:q,errorMsg:O?.message,columnsState:p}),M]})}const O_s=[{value:"system",label:"System",icon:o.jsx(Kdt,{})},{value:"light",label:"Light",icon:o.jsx(Yrn,{})},{value:"dark",label:"Dark",icon:o.jsx(Onn,{})}],C_s={md:{itemGap:2,itemWidth:28,root:"gap-0.5 p-0.5",indicator:"inset-y-0.5 left-0.5",item:"h-6 [&_svg]:size-3.5"},xs:{itemGap:1,itemWidth:20,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-4 [&_svg]:h-icon-sm [&_svg]:w-icon-sm"},sm:{itemGap:1,itemWidth:24,root:"gap-px p-px",indicator:"inset-y-px left-px",item:"h-5 [&_svg]:h-icon-sm [&_svg]:w-icon-sm"}},__s=({value:e,onChange:t,options:n=O_s,size:r="md",className:s,"aria-label":a="Theme",...i})=>{const{theme:l,setTheme:c}=b_(),u=e??l,d=t??c,f=n.some(y=>y.value===u)?u:n[0]?.value??"system",h=y=>{const b=n.find(x=>x.value===y);b&&d(b.value)},p=Math.max(0,n.findIndex(y=>y.value===f)),m=C_s[r],v=p*(m.itemWidth+m.itemGap);return o.jsxs(EVt,{...i,value:f,onValueChange:h,"aria-label":a,className:K("relative inline-flex w-fit items-center rounded-full border border-border1 bg-surface3",m.root,s),children:[o.jsx("span",{"aria-hidden":"true",className:K("pointer-events-none absolute rounded-full bg-surface5 motion-reduce:transition-none",ts.transform,m.indicator),style:{width:m.itemWidth,transform:`translateX(${v}px)`}}),n.map(y=>o.jsx(_Vt,{value:y.value,"aria-label":y.label,style:{width:m.itemWidth},className:K("relative inline-flex cursor-pointer items-center justify-center rounded-full","text-icon3 hover:text-icon6 data-[checked]:text-icon6",m.item,"focus-visible:outline-hidden","active:scale-90 motion-reduce:transition-none",ts.colors,ts.transform),children:o.jsx("span",{"aria-hidden":"true",className:"pointer-events-none inline-flex items-center justify-center",children:y.icon})},y.value))]})},E_s=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=kW();return o.jsx(Bt,{className:"p-0",children:o.jsx(Rus,{children:o.jsxs("div",{className:"mx-auto flex max-w-4xl flex-col gap-8",children:[o.jsxs(rtt,{children:[o.jsxs(stt,{children:[o.jsx(att,{children:"General"}),o.jsx(itt,{children:"Stored in this browser."})]}),o.jsx(vVt,{children:o.jsx(Q0e,{label:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(__s,{})})})]}),o.jsxs(rtt,{children:[o.jsxs(stt,{children:[o.jsx(att,{children:"Mastra Connection"}),o.jsx(itt,{children:"Configure the Mastra instance URL, API prefix, and request headers used by the studio."})]}),o.jsx($Vt,{variant:"factory",initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})]})]})})})};function T_s(){const[e]=da(),t=zr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(xGt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function j_s(e){return e.replace(/\/$/,"").split("/").pop()}function iK({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-5 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function N_s({templates:e,linkComponent:t,className:n,isLoading:r}){const s=t||"a";return r?o.jsx("div",{className:K("grid gap-y-4",n),children:Array.from({length:5}).map((a,i)=>o.jsx("div",{className:"bg-surface3 h-16 animate-pulse rounded-lg"},i))}):o.jsx("div",{className:K("grid gap-y-4",n),children:e.map(a=>{const i=a?.agents||a?.tools||a?.networks||a?.workflows||a?.mcp;return o.jsxs("article",{className:K("border border-border1 rounded-lg overflow-hidden w-full grid grid-cols-[1fr_auto] bg-surface3 transition-colors hover:bg-surface4"),children:[o.jsxs(s,{to:`/templates/${a.slug}`,className:K("grid [&:hover_p]:text-neutral5",{"grid-cols-[8rem_1fr] lg:grid-cols-[12rem_1fr]":a.imageURL}),children:[a.imageURL&&o.jsx("div",{className:K("overflow-hidden"),children:o.jsx("div",{className:"thumb transition-scale h-full w-full bg-cover duration-150",style:{backgroundImage:`url(${a.imageURL})`}})}),o.jsxs("div",{className:K("grid py-3 px-4 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-md text-neutral5",children:a.title}),o.jsx("p",{className:"text-ui-md text-neutral4 transition-colors duration-500",children:a.description}),o.jsxs("div",{className:"text-neutral3 text-ui-md mt-3 hidden flex-wrap items-center gap-4 2xl:flex",children:[i&&o.jsxs("ul",{className:K("flex gap-4 text-ui-md text-neutral3 m-0 p-0 list-none","[&>li]:flex [&>li]:items-center [&>li]:gap-0.5 text-neutral4"),children:[a?.agents&&a.agents.length>0&&o.jsxs("li",{children:[o.jsx(Pi,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Xd,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Xdt,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(NI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(Z_,{})," ",a.mcp.length]})]}),i&&a.supportedProviders&&o.jsx("small",{children:"|"}),o.jsx("div",{className:"text-neutral3 flex items-center gap-4",children:a.supportedProviders.map(l=>o.jsx("span",{className:"",children:l},l))})]})]})]}),o.jsx("a",{href:a.githubUrl,className:K("group items-center gap-2 text-ui-md ml-auto pr-4 hidden","lg:flex"),target:"_blank",rel:"noopener noreferrer",children:o.jsxs("span",{className:"bg-surface1 group-hover:bg-surface2 text-neutral3 group-hover:text-neutral5 flex items-center gap-2 rounded px-2 py-1 transition-colors",children:[o.jsx(lQ,{})," ",j_s(a.githubUrl)]})})]},a.slug)})})}function I_s({tagOptions:e,selectedTag:t,providerOptions:n,selectedProvider:r,onTagChange:s,onProviderChange:a,searchTerm:i,onSearchChange:l,onReset:c,className:u,isLoading:d}){return d?o.jsxs("div",{className:K("h-[6.5rem] flex items-center gap-5","[&>div]:bg-surface3 [&>div]:w-48 [&>div]:h-8 [&>div]:animate-pulse",u),children:[o.jsx("div",{})," ",o.jsx("div",{})," ",o.jsx("div",{})]}):o.jsxs("div",{className:K("flex flex-wrap mx-auto sticky top-0 gap-4 bg-surface2 py-5",u),children:[o.jsx(QD,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(ad,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(ad,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsx(ie,{onClick:c,icon:o.jsx(qt,{}),children:"Reset"})]})}function A_s(){const{data:e,isLoading:t}=Ocr(),{templates:n,tags:r,providers:s}=e??{templates:[],tags:[],providers:[]},[a,i]=g.useState("all"),[l,c]=g.useState("all"),[u,d]=g.useState(""),f=[{value:"all",label:"Any tag"}];(r||[]).forEach(x=>{f.push({value:x,label:x})});const h=[{value:"all",label:"Any provider"}];(s||[]).forEach(x=>{h.push({value:x,label:x})});const p=(x,w)=>{w==="tag"?i(x):w==="provider"&&c(x)},m=x=>{d(x)},v=()=>{i("all"),c("all"),d("")},y=n.filter(x=>!(u&&!x.title.toLowerCase().includes(u)&&!x.description.toLowerCase().includes(u)||a!=="all"&&!x.tags.includes(a)||l!=="all"&&!x.supportedProviders.includes(l))),b=u||a!=="all"||l!=="all";return o.jsxs(oa,{children:[o.jsx(vL,{children:o.jsxs(X0t,{children:[o.jsx(st,{children:o.jsx(gx,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-5 pb-12 z-10"),children:[o.jsx(I_s,{selectedTag:a,onTagChange:x=>p(x,"tag"),tagOptions:f,selectedProvider:l,onProviderChange:x=>p(x,"provider"),providerOptions:h,searchTerm:u,onSearchChange:m,onReset:b?v:void 0,className:"max-w-[80rem]",isLoading:t}),o.jsx(N_s,{templates:y,linkComponent:xo,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const R_s="1.67.0";function P_s({errorMsg:e,validationErrors:t}){const n=typeof e=="string"?e:e!=null?String(e):void 0,r=n?.includes("Invalid schema for function"),s=n?.includes("validation issue")||t&&t.length>0,a=()=>s?"Template installation completed but some validation issues remain. The template may still be functional, but you should review and fix these issues.":r?"There was an issue with the AI model configuration. This may be related to the selected model or AI SDK version compatibility.":"An unexpected error occurred during template installation.",i=()=>s?{icon:o.jsx(Ic,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(Uen,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(iK,{className:"text-neutral3 mb-5 content-center space-y-4",children:[o.jsxs("div",{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[l,o.jsxs("div",{className:"space-y-2 text-center",children:[o.jsx("p",{className:"text-ui-md text-neutral5 font-medium",children:c}),o.jsx("p",{className:"text-ui-md text-neutral3",children:a()})]})]}),t&&t.length>0&&o.jsxs("details",{className:"text-ui-sm",children:[o.jsxs("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:["Show Validation Issues (",t.length,")"]}),o.jsx("div",{className:"text-ui-sm mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left dark:bg-gray-800",children:t.map((u,d)=>o.jsxs("div",{className:"border-l-2 border-red-400 pl-2",children:[o.jsx("div",{className:"font-medium text-red-600 dark:text-red-400",children:u.type==="typescript"?"🔴 TypeScript Error":"⚠️ Lint Error"}),o.jsx("div",{className:"text-ui-sm mt-1 font-mono wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-ui-sm",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"text-ui-sm mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}const $_s=g.createContext(null);function M_s(){const e=g.useContext($_s);return e||{registerResetFn:()=>{},triggerReset:()=>{}}}const IGt=({defaultProvider:e,defaultModel:t,updateModel:n,resetModel:r})=>{const[s]=g.useState(e),[a]=g.useState(t),[i,l]=g.useState(t),[c,u]=g.useState(e||""),[d,f]=g.useState(!1),[h,p]=g.useState(!1),[m,v]=g.useState(!1),{data:y,isLoading:b}=k4(),x=h0(),{models:w}=_0(),k=g.useMemo(()=>y?.providers||[],[y]);g.useEffect(()=>{l(t),u(e||"")},[t,e]);const O=Ra(c),T=Uj(k,O)?.id||O,E=async D=>{if(l(D),D&&T){f(!0);try{const q=await n({provider:T,modelId:D});console.info("Model updated:",q)}catch(q){console.error("Failed to update model:",q)}finally{f(!1)}}},N=D=>{const q=Ra(D);u(q),q!==O&&(l(""),v(!0))},{registerResetFn:I}=M_s();if(g.useEffect(()=>(I(()=>{if(h||m)return;if(O&&O!==s&&(!i||i==="")){u(Ra(s)),l(a);const B=Uj(k,s)?.id||s;B&&a&&n({provider:B,modelId:a}).catch(W=>{console.error("Failed to reset model:",W)})}}),()=>{I(null)}),[I,O,i,s,a,n,h,m,k]),b)return o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Zt,{}),o.jsx("span",{className:"text-ui-md text-gray-500",children:"Loading providers..."})]});const A=async()=>{if(!r){console.warn("Reset model function not provided");return}try{f(!0),await r()}catch(D){console.error("Failed to reset model:",D)}finally{f(!1)}},$=Uj(k,O);if(x.active&&x.pickerVisible===!1){const D=x.default&&x.default.provider&&x.default.modelId?`${x.default.provider}/${x.default.modelId}`:c&&i?`${c}/${i}`:"Locked by admin";return o.jsxs("div",{className:"border-border1 bg-surface3 flex items-center gap-2 rounded-md border px-3 py-2","data-testid":"agent-metadata-model-locked",children:[o.jsx(qd,{className:"text-neutral3 h-4 w-4 shrink-0"}),o.jsx("span",{className:"text-ui-sm text-neutral6 truncate",children:D}),o.jsx("span",{className:"text-ui-xs text-neutral3 ml-auto shrink-0",children:"Set by admin"})]})}const z=!!(O&&i)&&x.active&&x.allowed!==void 0&&!w.some(D=>Ra(D.provider)===O&&D.model===i);return o.jsxs("div",{className:"@container",children:[o.jsxs("div",{className:"flex w-full flex-col items-stretch gap-2 @xs:flex-row @xs:items-center",children:[o.jsx("div",{className:"w-full @xs:w-2/5",children:o.jsx(sb,{value:O,onValueChange:N,open:h,onOpenChange:p})}),o.jsx("div",{className:"w-full @xs:w-3/5",children:o.jsx(ab,{llmId:O,value:i,onValueChange:E,open:m,onOpenChange:v})}),o.jsx(ie,{variant:"default",size:"md",onClick:A,disabled:d,className:"text-ui-sm flex items-center gap-1.5 border-0! whitespace-nowrap",title:"Reset to original model",children:o.jsx(f1,{className:"h-3.5 w-3.5"})})]}),z&&o.jsx("div",{className:"p-2 pt-2","data-testid":"agent-metadata-model-stale-warning",children:o.jsx(Nn,{variant:"warning",title:"Model not allowed",children:o.jsxs(Nn.Message,{children:[o.jsxs("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:[c,"/",i]})," ","is no longer allowed by the admin policy. Pick a different model to save changes."]})})}),$&&!$.connected&&o.jsx("div",{className:"p-2 pt-2",children:o.jsx(Nn,{variant:"warning",title:"Provider not connected",children:o.jsxs(Nn.Message,{children:["Set the"," ",o.jsx("code",{className:"rounded bg-yellow-100 px-1 py-0.5 dark:bg-yellow-900/50",children:Array.isArray($.envVar)?$.envVar.join(", "):$.envVar})," ","environment"," ",Array.isArray($.envVar)&&$.envVar.length>1?"variables":"variable"," to use this provider."]})})})]})};function D_s({providerOptions:e,selectedProvider:t,onProviderChange:n,variables:r,errors:s,handleInstallTemplate:a,handleVariableChange:i,isLoadingEnvVars:l,isInstalling:c,defaultModelProvider:u,defaultModelId:d,onModelUpdate:f}){return o.jsx(iK,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-5 p-4 lg:p-5",children:[o.jsxs("h2",{className:K("text-neutral4 text-header-sm font-semibold flex items-center gap-2","[&>svg]:w-[1.2em] [&_svg]:h-[1.2em] [&_svg]:opacity-70"),children:["Install Template ",o.jsx(Jdt,{})]}),o.jsx(ad,{name:"template-provider",options:e,label:"Template AI Model Provider",onValueChange:n,value:t,placeholder:"Select",layout:"horizontal"}),t&&Object.entries(r||{}).length>0&&o.jsxs(o.Fragment,{children:[o.jsx("h3",{className:"text-neutral3 text-ui-md",children:"Set required Environmental Variables"}),o.jsx("div",{className:"grid grid-cols-[1fr_1fr] items-start gap-4",children:l?o.jsxs("div",{className:K("flex items-center justify-center col-span-2 text-neutral3 text-ui-sm gap-4","[&_svg]:opacity-50 [&_svg]:w-[1.1em] [&_svg]:h-[1.1em]","animate-in fade-in duration-300"),children:[o.jsx(Zt,{})," Loading variables..."]}):Object.entries(r).map(([h,p])=>o.jsxs(g.Fragment,{children:[o.jsx(bm,{name:`env-${h}`,labelIsHidden:!0,label:"Key",value:h,disabled:!0,className:"w-full"}),o.jsx(bm,{name:h,labelIsHidden:!0,label:"Value",value:p,onChange:i,errorMsg:s.includes(h)?"Value is required.":"",autoComplete:"off",className:"w-full"})]},h))}),o.jsxs("div",{className:"border-border1 relative mt-3.5 border-t pt-12",children:[o.jsx("div",{className:"bg-surface2 text-ui-sm text-neutral3 absolute top-0 left-1/2 flex h-8 w-8 -translate-x-1/2 -translate-y-4 items-center justify-center rounded-full",children:"And"}),o.jsx("h3",{className:"text-neutral4 text-ui-md",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-5",children:"This model will be used by the workflow to process and install the template"}),o.jsx(IGt,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(ie,{className:K("flex items-center gap-2 mt-4 justify-center text-ui-md w-full bg-surface5 min-h-10 rounded-lg text-neutral5 hover:bg-surface6 transition-colors","[&>svg]:w-[1.1em] [&_svg]:h-[1.1em] [&_svg]:text-neutral5"),onClick:a,disabled:!t||!u||!d||s.length>0||c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(Zt,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Df,{})]})})]})})}function L_s({title:e,description:t,githubUrl:n,isLoading:r,infoData:s,templateSlug:a}){const i=a?`feat/install-template-${a}`:"feat/install-template-[slug]";return o.jsxs(o.Fragment,{children:[o.jsx("div",{className:K("grid mt-5 items-center"),children:o.jsxs("div",{className:K("text-header-lg flex items-center gap-3","[&>svg]:w-[1.2em] [&>svg]:h-[1.2em] [&>svg]:opacity-50",{"[&>svg]:opacity-20":r}),children:[o.jsx(gx,{}),o.jsx("h2",{className:K({"bg-surface4 flex rounded-lg min-w-[50%]":r}),children:r?o.jsx(o.Fragment,{children:" "}):e})]})}),o.jsxs("div",{className:"grid gap-x-24 lg:grid-cols-[1fr_1fr]",children:[o.jsxs("div",{className:"grid",children:[o.jsx("p",{className:K("mb-4 text-ui-md text-neutral4 mt-2",{"bg-surface4 rounded-lg ":r}),children:r?o.jsx(o.Fragment,{children:" "}):t}),!r&&a&&o.jsxs("div",{className:K("bg-surface2 border border-surface4 rounded-lg p-4 mb-4","flex items-start gap-3"),children:[o.jsx("div",{className:"mt-0.5 shrink-0",children:o.jsx(_m,{className:"h-[1.1em] w-[1.1em] text-blue-500"})}),o.jsxs("div",{className:"flex-1 space-y-2",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(Wwe,{className:"text-neutral4 h-[1em] w-[1em]"}),o.jsx("span",{className:"text-ui-md text-neutral5 font-medium",children:"A new Git branch will be created"})]}),o.jsxs("div",{className:"text-ui-sm text-neutral4 space-y-1",children:[o.jsxs("div",{children:[o.jsx("span",{className:"font-medium",children:"Branch name:"})," ",o.jsx("code",{className:"bg-surface3 text-ui-sm rounded px-1.5 py-0.5 font-mono",children:i})]}),o.jsx("div",{children:"This ensures safe installation with easy rollback if needed. Your main branch remains unchanged."})]})]})]}),n&&o.jsxs("a",{href:n,target:"_blank",rel:"noopener noreferrer",className:"text-neutral3 text-ui-md hover:text-neutral5 mt-auto flex items-center gap-2",children:[o.jsx(lQ,{}),n?.split("/")?.pop()]})]}),s&&o.jsx($Re,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Yrt(e){switch(e){case"running":return o.jsx(Zt,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Fn,{"aria-hidden":!0});case"failed":return o.jsx(qt,{"aria-hidden":!0});default:return null}}function F_s(){return o.jsx("svg",{viewBox:"0 0 24 24",className:"text-neutral2","aria-hidden":!0,children:o.jsx("circle",{cx:"12",cy:"12",r:"8.5",pathLength:"48",fill:"none",stroke:"currentcolor",strokeWidth:"2.8",strokeLinecap:"round",strokeDasharray:"3 3"})})}function z_s({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",ts.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(F_s,{}):Yrt(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",ts.colors,ts.transform,ts.shadow,{"[&>svg]:text-notice-success-fg":e==="success","[&>svg]:text-notice-destructive-fg":e==="failed","border border-dashed border-neutral2":e==="pending","[&>svg]:size-4":e!=="running","bg-accent1Dark shadow-glow-accent1":e==="success","bg-accent2Dark shadow-glow-accent2":e==="failed","scale-110":e==="success"||e==="failed"}),children:Yrt(e)})}function B_s({step:e,isActive:t,position:n,variant:r="default"}){return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-6 rounded-lg px-4 py-3 motion-reduce:transition-none",ts.colors,{"border border-transparent":r==="default","border-dashed border-neutral2 bg-surface3":t&&r==="default"}),children:[o.jsxs("div",{className:"grid min-w-0 grid-cols-[auto_1fr] gap-2",children:[o.jsxs("span",{className:K("flex min-w-6 justify-end text-ui-md",ts.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:[n,"."]}),o.jsxs("div",{className:"min-w-0",children:[o.jsx("h4",{className:K("text-ui-md",ts.colors,{"text-neutral5":t||e.status==="success","text-neutral3":!t&&e.status!=="success"}),children:e.title}),e.description&&o.jsx("p",{className:K("-mt-0.5 text-ui-md text-neutral2",{truncate:r==="plain"}),children:e.description})]})]}),o.jsx(z_s,{status:e.status,variant:r})]})}function U_s({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(B_s,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function q_s({steps:e}){const t=e.length,n=e.filter(r=>r.status==="success").length;return o.jsxs("div",{className:"flex w-full flex-col content-center justify-center gap-4",children:[o.jsx("div",{className:"grid w-full grid-cols-[0_repeat(9,1fr)]",children:e.map((r,s)=>o.jsx("div",{className:K("relative flex h-8 items-center justify-end",ts.colors,{"bg-accent1Dark":r.status==="success"&&e?.[s-1]?.status==="success"}),children:o.jsx("div",{className:K("absolute right-0 z-10 flex size-8 translate-x-1/2 items-center justify-center self-center rounded-full bg-surface3 text-ui-sm font-bold text-neutral3 motion-reduce:transition-none",ts.colors,ts.transform,ts.shadow,{"border border-dashed border-neutral2":r.status==="pending","bg-accent1Dark text-notice-success-fg shadow-glow-accent1 scale-110":r.status==="success","bg-accent2Dark text-notice-destructive-fg shadow-glow-accent2 scale-110":r.status==="failed"}),children:r.status==="running"?o.jsx(Zt,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-ui-sm text-neutral3",ts.colors),children:[n," of ",t," steps completed"]})]})}function V_s({name:e,streamResult:t,runId:n,workflowInfo:r}){const s=t?.phase||"initializing",a=t?.payload?.workflowState,i=t?.payload?.currentStep,l=t?.error,c=a?.steps||{},u=Object.keys(c).length>0,d=v=>v==="input"||v.endsWith(".input")||v.startsWith("Mapping_")&&/[0-9a-f]{8}/.test(v)||/[0-9a-f]{8,}/.test(v)?!1:r?.allSteps?v in r.allSteps:!0,f=Object.entries(c).filter(([v,y])=>d(v)),h=f.length,p=()=>{switch(s){case"initializing":return"Preparing template installation...";case"processing":return`Installing ${e} template`;case"completed":return"Template installation completed!";case"error":return"Template installation failed";default:return"Installing template..."}},m=f.map(([v,y])=>({id:v,status:y?.status,description:y?.description,title:v.charAt(0).toUpperCase()+v.slice(1).replace(/-/g," "),isActive:i?.id===v}));return o.jsxs(iK,{className:"text-neutral3 mb-5 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-header-sm font-semibold",children:p()}),(t?.runId||n)&&o.jsxs("div",{className:"text-ui-sm text-neutral3 mt-2",children:["Run ID: ",t?.runId??n]})]}),u&&h>0&&!["error"].includes(s)&&o.jsx("div",{className:"mx-auto w-full max-w-[30rem] px-4",children:o.jsx(q_s,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-4 flex items-center gap-3 text-ui-md bg-red-500/10","[&>svg]:w-6 [&>svg]:h-6 [&>svg]:opacity-70 [&>svg]:text-red-500"),children:[o.jsx(Dnn,{}),l||"Something went wrong"]}),u&&o.jsx(U_s,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 text-ui-md grid justify-items-center gap-4 text-center",children:[o.jsx(Zt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function H_s({name:e,installedEntities:t}){return o.jsxs(iK,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx(Jdt,{}),o.jsx("h2",{className:"text-header-md",children:"Done!"}),o.jsxs("p",{className:"text-ui-md text-neutral3 text-center",children:["The ",o.jsx("b",{className:"text-neutral4",children:e})," template has been successfully installed.",t&&t.length>0&&o.jsxs(o.Fragment,{children:[o.jsx("br",{})," Installed entities are listed below."]})]}),t&&t.length>0&&o.jsx($Re,{data:t})]})}function W_s(){const{templateSlug:e}=tr(),[t,n]=da(),[r,s]=g.useState(""),[a,i]=g.useState(""),[l,c]=g.useState(""),[u,d]=g.useState({}),[f,h]=g.useState([]),[p,m]=g.useState(null),[v,y]=g.useState(!1),[b,x]=g.useState(""),[w,k]=g.useState(!1),[O,_]=g.useState(!1),[T,E]=g.useState([]),{data:N,isLoading:I}=Ccr({repoOrSlug:e,owner:"mastra-ai"}),$=R_s?.includes("beta")??!1?"beta":"main",{data:z,isLoading:D}=_cr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:$}),{data:q,isLoading:H}=Ecr(),{mutateAsync:V,isPending:B}=Tcr(),{mutateAsync:W}=jcr(),{streamInstall:L,streamResult:G,isStreaming:M}=Icr(q),{observeInstall:R,streamResult:F,isStreaming:U}=Acr(q);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!p&&!M&&!U&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),W({runId:ne}).then(se=>{const ce=se.snapshot;if(ce?.status==="success"&&ce?.result?.success)y(!0);else if(ce?.result?.success===!1)if(ce?.result?.validationResults&&!ce?.result?.validationResults?.valid&&ce?.result?.validationResults?.remainingErrors>0){const{remainingErrors:ve,errors:ye}=ce.result.validationResults,Te=`Template installation completed but ${ve} validation issue${ve>1?"s":""} remain unresolved.`;m(Te),E(ye||[])}else{const ve=ce?.result?.message||ce?.result?.error||"Template installation failed";m(typeof ve=="string"?ve:String(ve))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,p,M,U,W]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),ce=t.get("provider");if(ne&&se==="true"&&ce&&!M&&!U&&!w&&!O&&q){x(ne),k(!0);try{W({runId:ne}).then(le=>{if(le.snapshot?.status==="running")return R.mutateAsync({runId:ne})}).then(()=>{n(le=>{const ve=new URLSearchParams(le);return ve.delete("resume"),ve})}).catch(le=>{console.error("❌ Failed to resume template installation:",le),le.message?.includes("404")||le.message?.includes("not found")?m("Template installation run not found. It may have expired or been completed."):m("Failed to resume template installation. Please try again.")})}catch(le){console.error("❌ Auto-resume failed with error:",le),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,M,U,w,O,q,W,R,n]);const Q=[{value:"openai",label:"OpenAI"},{value:"anthropic",label:"Anthropic"},{value:"groq",label:"Groq"},{value:"google",label:"Google"}],te=[{key:"tools",label:"Tools",value:N?.tools?.length?N.tools.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Xd,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(Pi,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(NI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(ny,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(TI,{})}],J=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{z&&d(z)},[z]),g.useEffect(()=>{const ne=G||F;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,F?.phase,F?.error]);const ee=ne=>{s(ne)},re=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),ae=async()=>{const ne=Object.entries(u).reduce((se,[ce,le])=>(le===""&&se.push(ce),se),[]);if(ne.length>0){h(ne);return}if(N){m(null),y(!1),x(""),_(!0);try{const ce={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:$,slug:N.slug,variables:u},{runId:le}=await V({});x(le),n(ve=>{const ye=new URLSearchParams(ve);return ye.set("runId",le),ye.set("resume","true"),ye.set("provider",r||"openai"),ye}),await L.mutateAsync({inputData:ce,selectedModel:{provider:a,modelId:l},runId:le})}catch(se){_(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=ne=>{const{name:se,value:ce}=ne.target;ce.trim()===""?h(le=>[...le,se]):h(le=>le.filter(ve=>ve!==se)),d(le=>({...le,[se]:ce}))};return o.jsx(oa,{children:o.jsx("div",{className:K("w-full lg:px-12 h-full overflow-y-scroll"),children:o.jsxs("div",{className:"mx-auto grid w-full max-w-[80rem] gap-y-4 p-4",children:[o.jsx(L_s,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(M||U)&&o.jsx(V_s,{name:N.title,streamResult:U?F:G,runId:b,workflowInfo:q}),v&&o.jsx(H_s,{name:N.title,installedEntities:J,linkComponent:xo}),p&&o.jsx(P_s,{errorMsg:p,validationErrors:T.length>0?T:G?.validationResults?.errors||F?.validationResults?.errors}),!M&&!U&&!v&&!p&&o.jsx(D_s,{providerOptions:Q,selectedProvider:r,onProviderChange:ee,variables:u,setVariables:d,errors:f,setErrors:h,handleInstallTemplate:ae,handleVariableChange:X,isLoadingEnvVars:D||H,isInstalling:B,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const Z_s=()=>{const{toolId:e,agentId:t}=tr();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(tfs,{toolId:e,agentId:t})})},G_s=()=>{const{toolId:e}=tr();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(HOs,{toolId:e})})};function Q_s(){const{data:e,isLoading:t,error:n}=Bm(),[r,s]=g.useState("");return n&&ms(n)?o.jsx(Qn,{children:o.jsx(zs,{})}):n&&gs(n)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"workflows"})}):n?o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Qn,{children:o.jsx(SKr,{})}):o.jsxs(Bt,{height:"full",children:[o.jsx(Bt.TopArea,{children:o.jsxs(Bt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(qc,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsx(ie,{as:xo,to:"/workflows/schedules",variant:"primary",className:"shrink-0",icon:o.jsx(WC,{}),children:"Schedules"})]})}),o.jsx(wKr,{workflows:e||{},isLoading:t,search:r})]})}const Y_s={active:"bg-accent1",paused:"bg-accent3"},K_s={active:"text-accent1",paused:"text-accent3"},AGt=({status:e})=>o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{className:`h-1.5 w-1.5 rounded-full ${Y_s[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${K_s[e]}`,children:e})]}),Wj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),zM=e=>{if(!e||e<=0)return"—";const t=e-Date.now(),n=Math.abs(t),r=Math.floor(n/1e3);if(r<60)return t>=0?`in ${r}s`:`${r}s ago`;const s=Math.floor(r/60);if(s<60)return t>=0?`in ${s}m`:`${s}m ago`;const a=Math.floor(s/60);if(a<24)return t>=0?`in ${a}h`:`${a}h ago`;const i=Math.floor(a/24);return t>=0?`in ${i}d`:`${i}d ago`};function RGt({status:e}){const{icon:t,color:n}=X_s(e);return o.jsxs("span",{className:`text-ui-sm inline-flex items-center gap-1.5 whitespace-nowrap ${n}`,children:[o.jsx("span",{className:"inline-flex shrink-0 items-center","aria-hidden":!0,children:t}),o.jsx("span",{children:e})]})}function X_s(e){switch(e){case"success":return{icon:o.jsx(Fn,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(qt,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Zt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(yH,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(Os,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(xS,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const Krt="auto auto auto auto 1fr";function J_s(e){if(e===void 0)return"—";if(e<1e3)return`${e}ms`;if(e<6e4)return`${(e/1e3).toFixed(1)}s`;const t=Math.floor(e/6e4),n=Math.floor(e%6e4/1e3);return`${t}m ${n}s`}function eEs(e){const t=Math.abs(e),n=e<0?"-":"";return t<1e3?`${n}${t}ms`:t<6e4?`${n}${(t/1e3).toFixed(1)}s`:t<36e5?`${n}${(t/6e4).toFixed(1)}m`:`${n}${(t/36e5).toFixed(1)}h`}const tEs=3e4,nEs=5*6e4;function rEs({triggers:e,isLoading:t,workflowId:n,hasNextPage:r,isFetchingNextPage:s,setEndOfListElement:a}){const{Link:i,paths:l}=ln(),c=p=>!!(n&&p.runId&&p.outcome!=="failed"),u=e.filter(c).length,{containerRef:d,getRowProps:f}=ll({count:u});let h=-1;return t?o.jsx(Uo,{columns:Krt}):e.length===0?o.jsx(ge,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(be,{columns:Krt,className:"min-w-0",scrollRef:d,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Run"}),o.jsx(be.TopCell,{children:"Status"}),o.jsx(be.TopCell,{children:"Started"}),o.jsx(be.TopCell,{children:"Duration"}),o.jsx(be.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=eEs(m),y=`Scheduled ${Wj(p.scheduledFireAt)} — published ${Wj(p.actualFireAt)} (drift ${v})`,b=p.outcome==="failed",x=b?p.error:p.run?.error,w=Math.abs(m),k=!b&&w>tEs&&w<=nEs,O=`${p.scheduleId}-${p.runId}-${p.actualFireAt}`,_=c(p);_&&(h+=1);const T=o.jsx("span",{className:_?"text-accent1 text-ui-sm font-mono whitespace-nowrap":"text-neutral3 text-ui-sm font-mono whitespace-nowrap",children:p.runId}),E=o.jsxs(o.Fragment,{children:[o.jsx(be.Cell,{children:T}),o.jsx(be.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2",children:[b?o.jsxs("span",{className:"text-ui-sm text-accent2 inline-flex items-center gap-1.5 whitespace-nowrap",children:[o.jsx(Ic,{size:14}),"publish failed"]}):p.run?o.jsx(RGt,{status:p.run.status}):o.jsx("span",{className:"text-ui-sm text-neutral3 inline-flex items-center gap-1.5 whitespace-nowrap",children:"pending"}),x?o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(Ic,{size:14})})}),o.jsx(pn,{children:x})]}):null]})}),o.jsx(be.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:zM(p.actualFireAt)}),k?o.jsxs(gn,{children:[o.jsx(hn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(Ic,{size:14})})}),o.jsxs(pn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(be.Cell,{children:p.run?o.jsx("span",{children:J_s(p.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(be.Cell,{children:" "})]});return _?o.jsx(be.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:i,...f(h),children:E},O):o.jsx(be.RowStatic,{children:E},O)}),o.jsx(be.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const sEs=e=>{const t=Ge();return mt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},Xrt=25,aEs=e=>{const t=Ge(),{inView:n,setRef:r}=Yy(),s=ev({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:Xrt,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<Xrt))return u.triggers[u.triggers.length-1].actualFireAt},refetchInterval:u=>(u.state.data?.pages.flatMap(h=>h.triggers)??[]).some(h=>h.run?h.run.status==="pending"||h.run.status==="running"||h.run.status==="waiting":h.outcome==="published")?5e3:!1}),a=s.data?.pages.flatMap(u=>u?.triggers??[])??[],{hasNextPage:i,isFetchingNextPage:l,fetchNextPage:c}=s;return g.useEffect(()=>{n&&i&&!l&&c()},[n,i,l,c]),{...s,data:a,setEndOfListElement:r}},iEs=e=>{const t=Ge(),n=Cr();return wn({mutationFn:async r=>{if(!e)throw new Error("scheduleId is required");return r==="pause"?t.pauseSchedule(e):t.resumeSchedule(e)},onSuccess:(r,s)=>{n.invalidateQueries({queryKey:["schedule",e]}),n.invalidateQueries({queryKey:["schedules"]}),Be.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Be.error(r.message)}})};function Z8({label:e,children:t}){return o.jsxs("div",{className:"flex flex-col gap-1",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 tracking-wide uppercase",children:e}),o.jsx("div",{className:"text-ui-md",children:t})]})}function oEs(){const{scheduleId:e}=tr(),{paths:t}=ln(),{data:n,error:r}=sEs(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=aEs(e),d=iEs(e);if(r&&ms(r))return o.jsx(Qn,{children:o.jsx(zs,{})});if(r&&gs(r))return o.jsx(Qn,{children:o.jsx(Ts,{resource:"schedules"})});if(r)return o.jsx(Qn,{children:o.jsx(Fs,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,h=n?.agentId;return o.jsxs(Bt,{children:[o.jsx(Bt.TopArea,{children:o.jsx(Bt.Row,{className:"justify-end",children:o.jsxs(Bt.Column,{className:"flex justify-end gap-2",children:[o.jsx(ie,{as:xo,to:t.schedulesLink(),variant:"ghost",icon:o.jsx(Lc,{}),children:"Back to schedules"}),f?o.jsx(ie,{icon:o.jsx(hc,{}),as:xo,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(ie,{onClick:()=>d.mutate(n.status==="active"?"pause":"resume"),disabled:d.isPending,"data-testid":"schedule-toggle-button",children:n.status==="active"?o.jsxs(o.Fragment,{children:[o.jsx(OH,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(oc,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-4 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(Z8,{label:h?"Agent":"Workflow",children:f?o.jsx(xo,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):h?o.jsx(xo,{to:t.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),o.jsxs(Z8,{label:"Cron",children:[o.jsx("code",{className:"text-ui-md font-mono",children:n.cron}),n.timezone?o.jsx("span",{className:"text-neutral4 text-ui-sm ml-2",children:n.timezone}):null]}),o.jsx(Z8,{label:"Status",children:o.jsx(AGt,{status:n.status})}),o.jsx(Z8,{label:"Next fire",children:o.jsx("span",{title:Wj(n.nextFireAt),children:zM(n.nextFireAt)})})]}),o.jsxs("div",{className:"overflow-y-auto","data-testid":"schedule-triggers-panel",children:[o.jsx(ge,{variant:"ui-md",className:"mb-3",children:"Trigger history"}),i?o.jsx(Fs,{title:"Failed to load trigger history",message:i.message}):o.jsx(rEs,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const Jrt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function lEs({schedules:e,isLoading:t,search:n=""}){const{paths:r,Link:s}=ln(),a=g.useMemo(()=>{const c=n.toLowerCase();return c?e.filter(u=>u.id.toLowerCase().includes(c)||(u.workflowId??u.agentId??"").toLowerCase().includes(c)):e},[e,n]),{containerRef:i,getRowProps:l}=ll({count:a.length,global:!0});return t?o.jsx(Uo,{columns:Jrt}):o.jsxs(be,{columns:Jrt,className:"min-w-0",scrollRef:i,children:[o.jsxs(be.Top,{children:[o.jsx(be.TopCell,{children:"Target"}),o.jsx(be.TopCell,{children:"Schedule ID"}),o.jsx(be.TopCell,{children:"Cron"}),o.jsx(be.TopCell,{children:"Status"}),o.jsx(be.TopCell,{children:"Next fire"}),o.jsx(be.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(be.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(be.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(be.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(be.NameCell,{children:c.workflowId??c.agentId}),o.jsx(be.Cell,{className:"min-w-0",children:o.jsx("span",{className:"text-ui-smd text-neutral3 block truncate font-mono",title:c.id,children:c.id})}),o.jsx(be.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("code",{className:"text-ui-sm font-mono",children:c.cron}),c.timezone?o.jsx("span",{className:"text-neutral4 text-ui-xs",children:c.timezone}):null]})}),o.jsx(be.Cell,{children:o.jsx(AGt,{status:c.status})}),o.jsx(be.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:Wj(c.nextFireAt),children:zM(c.nextFireAt)})}),o.jsx(be.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(RGt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Wj(c.lastFireAt),children:c.lastFireAt?zM(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Wj(c.lastFireAt),children:zM(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function cEs({workflowId:e}={}){const{data:t,isLoading:n,error:r}=qke(e?{workflowId:e}:{}),[s,a]=g.useState("");return r?o.jsx(Fs,{title:"Failed to load schedules",message:r.message}):o.jsxs("div",{className:"grid h-full grid-rows-[auto_1fr] gap-4 overflow-hidden",children:[o.jsx("div",{className:"max-w-120",children:o.jsx(qc,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(lEs,{schedules:t??[],isLoading:n,search:s})})]})}function uEs(){const[e]=da(),t=e.get("workflowId")??void 0,{error:n}=qke(t?{workflowId:t}:{});return n&&ms(n)?o.jsx(Qn,{children:o.jsx(zs,{})}):n&&gs(n)?o.jsx(Qn,{children:o.jsx(Ts,{resource:"schedules"})}):o.jsx(Bt,{children:o.jsx("div",{className:"h-full",children:o.jsx(cEs,{workflowId:t})})})}function dEs({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=k_e({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=CTt(r),[d]=_Tt(s),{edgeTypes:f,nodeTypes:h,styledEdges:p}=RFt({edges:d,workflowName:n,stepGraph:e});return g.useEffect(()=>{if(t){const m=setTimeout(()=>{i(!0)},500);return()=>clearTimeout(m)}},[t]),o.jsx("div",{className:"bg-surface1 relative h-full w-full",children:a?o.jsx(kjt,{variant:"nested",nodes:l,edges:p,edgeTypes:f,nodeTypes:h,onNodesChange:u}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Zt,{})})})}function est(){const{stepDetail:e,closeStepDetail:t}=AZ();return e?o.jsxs("div",{className:"flex h-full flex-col","data-testid":"workflow-step-detail-panel",children:[o.jsxs("div",{className:"border-border1 bg-surface1 flex items-center justify-between border-b px-4 py-3",children:[o.jsxs("div",{className:"flex items-center gap-2",children:[e.type==="map-config"&&o.jsx(wS,{className:"h-4 w-4",style:{color:Pu.map}}),e.type==="nested-graph"&&o.jsx(hc,{className:"h-4 w-4",style:{color:Pu.workflow}}),o.jsxs("div",{className:"flex flex-col",children:[o.jsx(ge,{variant:"ui-md",className:"text-neutral6 font-medium",children:e.type==="map-config"?`${e.stepName} Config`:`${e.stepName} Workflow`}),e.type==="map-config"&&e.stepId&&e.stepId!==e.stepName&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral3",children:e.stepId})]})]}),o.jsx("button",{onClick:t,className:"hover:bg-surface3 rounded p-1 transition-colors","aria-label":"Close",children:o.jsx(qt,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(yM,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(m_e,{children:o.jsx(dEs,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function fEs(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function hEs(e,t){if(e&&typeof e=="object"&&!Array.isArray(e)){const n=Object.keys(e);if(n.length===1)return n[0]}return t}function pEs({suspendedSteps:e,workflow:t,isStreaming:n,onResume:r}){return n||e.length===0?null:o.jsxs("div",{className:"border-border1 bg-surface4 space-y-5 rounded-lg border p-5","data-testid":"workflow-suspended-steps",children:[o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsxs(ge,{as:"p",variant:"ui-md",className:"text-neutral6 flex items-center gap-2 font-semibold",children:[o.jsx(st,{children:o.jsx(yH,{})}),"Step suspended"]}),o.jsx(xt,{variant:"yellow",children:"Needs input"})]}),e.map((s,a)=>{const i=t.allSteps[s.stepId];if(!i||i.isWorkflow)return null;const l=i?.resumeSchema?xm(zx(i.resumeSchema)):vf(dr(),Ef());return o.jsx(mEs,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function mEs({step:e,stepSchema:t,description:n,isStreaming:r,onResume:s}){const[a,i]=g.useState(!1);return o.jsxs("div",{className:"space-y-5",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(ge,{as:"p",variant:"ui-md",className:"text-neutral6 truncate font-medium",children:e.stepId}),n&&o.jsx(ge,{as:"p",variant:"ui-sm",className:"text-neutral3",children:n})]}),e.suspendPayload&&o.jsxs("div",{className:"space-y-2",children:[o.jsxs(ge,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(st,{children:o.jsx(_nn,{})}),"The step is asking"]}),o.jsxs(cc,{open:a,onOpenChange:i,children:[o.jsxs(ql,{className:"border-border1 bg-surface3 flex w-full items-center justify-between gap-2 rounded-lg border px-3 py-2.5",children:[o.jsxs("span",{className:"flex min-w-0 items-center gap-2",children:[o.jsx(st,{children:o.jsx(wr,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ge,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:hEs(e.suspendPayload,e.stepId)})]}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:fEs(e.suspendPayload)})]}),o.jsx(Vl,{children:o.jsx("div",{"data-testid":"suspended-payload",className:"pt-2",children:o.jsx(Vr,{data:e.suspendPayload,className:"w-full overflow-x-auto p-2",showCopyButton:!1})})})]})]}),o.jsxs("div",{className:"space-y-3",children:[o.jsxs(ge,{as:"p",variant:"ui-sm",className:"text-neutral3 flex items-center gap-2",children:[o.jsx(st,{children:o.jsx(Nnn,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(sq,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(oc,{}),submitButtonFullWidth:!0,collapsible:!1,hideHeading:!0,hideInputTypeLabel:!0,onSubmit:l=>{const c=e.stepId?.split(".");s({stepId:c,runId:e.runId,suspendPayload:e.suspendPayload,resumeData:l,isLoading:!1})}})})]})]})}function gEs(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Zl),{runId:a}=tr(),i=Tjt(e,r??""),l=nor(),c=!!a,u=t?.status==="suspended",f=!!(a&&r&&a===r)&&e?.status==="suspended";return s||!n||i.length===0||c&&!u&&!f?null:o.jsx("div",{"data-testid":"workflow-suspended-overlay",className:"animate-in fade-in-0 slide-in-from-top-2 zoom-in-95 absolute top-2 right-2 z-20 max-h-[calc(100%-1rem)] w-[380px] max-w-[calc(100%-1rem)] overflow-y-auto rounded-lg shadow-lg duration-300",children:o.jsx(pEs,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const vEs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.97865 4.57004C8.22604 4.75795 8.27426 5.11082 8.08635 5.35821L6.05486 8.03279C5.94873 8.17251 5.78348 8.25471 5.60803 8.25505C5.43257 8.2554 5.267 8.17385 5.16032 8.03454L3.80937 6.27034C3.6205 6.02369 3.66733 5.67063 3.91398 5.48176C4.16063 5.29288 4.51369 5.33972 4.70257 5.58637L5.6051 6.76498L7.19048 4.67774C7.37839 4.43036 7.73126 4.38213 7.97865 4.57004Z",fill:"currentColor"})]}),yEs=e=>o.jsxs("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:[o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M5.99982 2.0625C3.8252 2.0625 2.06232 3.82538 2.06232 6C2.06232 8.17462 3.8252 9.9375 5.99982 9.9375C8.17444 9.9375 9.93732 8.17462 9.93732 6C9.93732 3.82538 8.17444 2.0625 5.99982 2.0625ZM0.937317 6C0.937317 3.20406 3.20388 0.9375 5.99982 0.9375C8.79576 0.9375 11.0623 3.20406 11.0623 6C11.0623 8.79594 8.79576 11.0625 5.99982 11.0625C3.20388 11.0625 0.937317 8.79594 0.937317 6Z",fill:"currentColor"}),o.jsx("path",{fillRule:"evenodd",clipRule:"evenodd",d:"M7.89741 4.10293C8.11707 4.32261 8.11706 4.67877 7.89738 4.89843L6.79517 6.00058L7.8962 7.10155C8.11588 7.32122 8.11589 7.67737 7.89623 7.89705C7.67656 8.11673 7.32041 8.11674 7.10073 7.89707L5.99965 6.79605L4.89856 7.89707C4.67889 8.11673 4.32273 8.11672 4.10307 7.89704C3.88341 7.67737 3.88342 7.32121 4.10309 7.10155L5.20413 6.00058L4.10191 4.89843C3.88224 4.67877 3.88223 4.32262 4.10189 4.10294C4.32155 3.88326 4.67771 3.88325 4.89738 4.10292L5.99965 5.20511L7.10191 4.10291C7.32159 3.88325 7.67774 3.88326 7.89741 4.10293Z",fill:"currentColor"})]}),bEs=e=>e.includes("."),xEs=e=>e==="input"||e.endsWith(".input"),wEs=1;function SEs(e){return`${Number((e/1e3).toPrecision(3))}s`}function kEs(e,t){const n=Object.entries(e).filter(([i])=>!xEs(i));if(n.length===0)return[];const r=Math.min(...n.map(([,i])=>i.startedAt)),s=Math.max(...n.map(([,i])=>i.endedAt??t)),a=Math.max(s-r,1);return n.map(([i,l])=>{const c=l.endedAt===void 0,d=(l.endedAt??t)-l.startedAt,f=(l.startedAt-r)/a*100,h=Math.max(d/a*100,wEs);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:h,durationMs:d,isRunning:c,isNestedEntry:bEs(i)}})}const OEs=({status:e})=>o.jsxs(st,{children:[e==="success"&&o.jsx(vEs,{className:"text-accent1"}),e==="failed"&&o.jsx(yEs,{className:"text-accent2"}),e==="suspended"&&o.jsx(yH,{className:"text-accent3"}),e==="waiting"&&o.jsx(cme,{className:"text-accent5"}),e==="skipped"&&o.jsx(cme,{className:"text-icon3"}),e==="running"&&o.jsx(Hs,{className:"text-accent6 animate-spin"})]}),CEs={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function PGt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const tst=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},_Es=e=>{const t=e;return xjt({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},EEs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=_Es(e.step),u=e.status==="running",d=!e.isNestedEntry;return o.jsxs("div",{role:"button",tabIndex:0,"data-testid":"workflow-timeline-row","data-workflow-step-key":e.stepId,"data-workflow-step-active":n?"true":void 0,"data-workflow-step-hovered":r?"true":void 0,"data-workflow-step-nested":e.isNestedEntry?"true":void 0,"aria-pressed":n,"aria-disabled":!d,onMouseEnter:()=>{d&&a(e.stepId)},onMouseLeave:()=>{d&&a(null)},onClick:()=>{d&&s(e.stepId)},onKeyDown:f=>{!d||f.key!=="Enter"&&f.key!==" "||(f.preventDefault(),s(e.stepId))},className:K("grid grid-cols-[auto_auto_auto_minmax(0,10rem)_minmax(0,1fr)_auto_5rem] items-center gap-2 rounded-md border border-transparent px-2 py-1 text-left transition-colors focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-accent1",d&&"cursor-pointer",d&&"hover:bg-surface4",d&&r&&!n&&"border-neutral6 bg-surface4",d&&n&&"border-accent1",e.isNestedEntry&&"cursor-default opacity-55"),children:[o.jsx("div",{className:"flex justify-center",children:o.jsx(OEs,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step input",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||i(e)},children:o.jsx(Vrn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(nq,{indicators:c,className:"shrink-0"})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral6 block max-w-full min-w-0 justify-self-stretch overflow-hidden text-left text-ellipsis whitespace-nowrap",children:PGt(e.stepId)}),o.jsx("div",{className:"bg-surface4 relative h-2 min-w-0 rounded",children:o.jsx("div",{"data-testid":"workflow-timeline-bar","data-offset":String(e.offsetPct),"data-width":String(e.widthPct),className:`absolute top-0 h-full rounded ${CEs[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(ie,{type:"button",variant:"ghost",size:"icon-sm",tooltip:"View step output",disabled:u,className:"text-neutral3 hover:text-neutral6 disabled:cursor-not-allowed disabled:opacity-40",onClick:f=>{f.stopPropagation(),u||l(e)},children:o.jsx(Urn,{})})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:SEs(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function TEs(){const{steps:e}=I4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=DW(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);dwt(f,{enabled:!l});const h=kEs(e,a),p=h.some(m=>m.isRunning);return g.useEffect(()=>{if(!p)return;const m=setInterval(()=>i(Date.now()),100);return()=>clearInterval(m)},[p]),g.useEffect(()=>{if(l||h.length===0)return;const m=f.current;m&&(m.scrollTop=m.scrollHeight)},[l,h.length]),h.length===0?null:o.jsxs(o.Fragment,{children:[o.jsx("div",{"data-testid":"workflow-timeline",className:"pointer-events-none absolute right-0 bottom-0 z-20 px-2 pb-2",style:{left:"var(--workflow-left-panel-width, 0px)"},children:o.jsxs("div",{className:"rounded-studio-panel border-border1/50 bg-surface3 pointer-events-auto flex max-h-64 w-full min-w-0 flex-col gap-3 overflow-hidden border p-4 shadow-lg",children:[o.jsxs("div",{className:"flex shrink-0 items-center justify-between gap-3",children:[o.jsx(ge,{as:"p",variant:"ui-md",className:"text-neutral3",children:"Timeline"}),o.jsx("button",{type:"button","aria-label":l?"Expand timeline":"Collapse timeline","aria-expanded":!l,onClick:()=>c(m=>!m),className:"text-neutral3 hover:bg-surface4 hover:text-neutral6 rounded-md p-1 transition-colors",children:o.jsx(Ps,{className:K("h-4 w-4 transition-transform",l&&"-rotate-90")})})]}),!l&&o.jsx("div",{ref:f,"data-testid":"workflow-timeline-list",className:"flex min-h-0 flex-col gap-2 overflow-y-auto",children:h.map((m,v)=>o.jsx(EEs,{row:m,index:v,isSelected:t===m.stepId,isHovered:n===m.stepId,onSelectStep:r,onHoverStep:s,onOpenInput:y=>d({type:"input",stepId:y.stepId,data:tst(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:tst(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(Njt,{data:u.data,title:`${PGt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const jEs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=AZ(),s=XI(),a=o.jsx("div",{className:"flex h-full min-h-0 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(PFt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(gEs,{}),o.jsx(TEs,{})]})});return s?r?o.jsx("div",{className:"h-full min-h-0 overflow-hidden",children:o.jsx(est,{})}):a:o.jsxs(_D,{className:"h-full min-h-0 w-full min-w-0",children:[o.jsx(Yx,{id:"workflow-graph",className:"min-w-0",children:a}),r?o.jsxs(o.Fragment,{children:[o.jsx(AN,{}),o.jsx(Yx,{id:"workflow-step-detail",minSize:300,maxSize:"60%",defaultSize:420,className:"min-w-0",children:o.jsx("div",{className:"border-border1 h-full min-h-0 overflow-hidden border-l",children:o.jsx(est,{})})})]}):null]})},nst=()=>{const{workflowId:e}=tr(),{data:t,isLoading:n,error:r}=HL(e);return r&&ms(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(zs,{})}):r&&gs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Ts,{resource:"workflows"})}):o.jsx(U_e,{children:o.jsx(jEs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function NEs(e,t){if(e==null)return{};var n,r,s=BCt(e,t);if(Object.getOwnPropertySymbols){var a=Object.getOwnPropertySymbols(e);for(r=0;r<a.length;r++)n=a[r],t.indexOf(n)===-1&&{}.propertyIsEnumerable.call(e,n)&&(s[n]=e[n])}return s}function Iwe(e,t){(t==null||t>e.length)&&(t=e.length);for(var n=0,r=Array(t);n<t;n++)r[n]=e[n];return r}function IEs(e){if(Array.isArray(e))return Iwe(e)}function AEs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function REs(e,t){if(e){if(typeof e=="string")return Iwe(e,t);var n={}.toString.call(e).slice(8,-1);return n==="Object"&&e.constructor&&(n=e.constructor.name),n==="Map"||n==="Set"?Array.from(e):n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Iwe(e,t):void 0}}function PEs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
695
695
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function Awe(e){return IEs(e)||AEs(e)||REs(e)||PEs()}function O3(e){"@babel/helpers - typeof";return O3=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},O3(e)}function $Es(e,t){if(O3(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(O3(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function MEs(e){var t=$Es(e,"string");return O3(t)=="symbol"?t:t+""}function $Gt(e,t,n){return(t=MEs(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function rst(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function ij(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?rst(Object(n),!0).forEach(function(r){$Gt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):rst(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function DEs(e){var t=e.length;if(t===0||t===1)return e;if(t===2)return[e[0],e[1],"".concat(e[0],".").concat(e[1]),"".concat(e[1],".").concat(e[0])];if(t===3)return[e[0],e[1],e[2],"".concat(e[0],".").concat(e[1]),"".concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[0]),"".concat(e[1],".").concat(e[2]),"".concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[1],".").concat(e[0])];if(t>=4)return[e[0],e[1],e[2],e[3],"".concat(e[0],".").concat(e[1]),"".concat(e[0],".").concat(e[2]),"".concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[0]),"".concat(e[1],".").concat(e[2]),"".concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[1]),"".concat(e[2],".").concat(e[3]),"".concat(e[3],".").concat(e[0]),"".concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[0]),"".concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[0],".").concat(e[1],".").concat(e[2],".").concat(e[3]),"".concat(e[0],".").concat(e[1],".").concat(e[3],".").concat(e[2]),"".concat(e[0],".").concat(e[2],".").concat(e[1],".").concat(e[3]),"".concat(e[0],".").concat(e[2],".").concat(e[3],".").concat(e[1]),"".concat(e[0],".").concat(e[3],".").concat(e[1],".").concat(e[2]),"".concat(e[0],".").concat(e[3],".").concat(e[2],".").concat(e[1]),"".concat(e[1],".").concat(e[0],".").concat(e[2],".").concat(e[3]),"".concat(e[1],".").concat(e[0],".").concat(e[3],".").concat(e[2]),"".concat(e[1],".").concat(e[2],".").concat(e[0],".").concat(e[3]),"".concat(e[1],".").concat(e[2],".").concat(e[3],".").concat(e[0]),"".concat(e[1],".").concat(e[3],".").concat(e[0],".").concat(e[2]),"".concat(e[1],".").concat(e[3],".").concat(e[2],".").concat(e[0]),"".concat(e[2],".").concat(e[0],".").concat(e[1],".").concat(e[3]),"".concat(e[2],".").concat(e[0],".").concat(e[3],".").concat(e[1]),"".concat(e[2],".").concat(e[1],".").concat(e[0],".").concat(e[3]),"".concat(e[2],".").concat(e[1],".").concat(e[3],".").concat(e[0]),"".concat(e[2],".").concat(e[3],".").concat(e[0],".").concat(e[1]),"".concat(e[2],".").concat(e[3],".").concat(e[1],".").concat(e[0]),"".concat(e[3],".").concat(e[0],".").concat(e[1],".").concat(e[2]),"".concat(e[3],".").concat(e[0],".").concat(e[2],".").concat(e[1]),"".concat(e[3],".").concat(e[1],".").concat(e[0],".").concat(e[2]),"".concat(e[3],".").concat(e[1],".").concat(e[2],".").concat(e[0]),"".concat(e[3],".").concat(e[2],".").concat(e[0],".").concat(e[1]),"".concat(e[3],".").concat(e[2],".").concat(e[1],".").concat(e[0])]}var vle={};function LEs(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return vle[t]||(vle[t]=DEs(e)),vle[t]}function FEs(e){var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},n=arguments.length>2?arguments[2]:void 0,r=e.filter(function(a){return a!=="token"}),s=LEs(r);return s.reduce(function(a,i){return ij(ij({},a),n[i])},t)}function sst(e){return e.join(" ")}function zEs(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return MGt({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function MGt(e){var t=e.node,n=e.stylesheet,r=e.style,s=r===void 0?{}:r,a=e.useInlineStyles,i=e.key,l=t.properties,c=t.type,u=t.tagName,d=t.value;if(c==="text")return d;if(u){var f=zEs(n,a),h;if(!a)h=ij(ij({},l),{},{className:sst(l.className)});else{var p=Object.keys(n).reduce(function(b,x){return x.split(".").forEach(function(w){b.includes(w)||b.push(w)}),b},[]),m=l.className&&l.className.includes("token")?["token"]:[],v=l.className&&m.concat(l.className.filter(function(b){return!p.includes(b)}));h=ij(ij({},l),{},{className:sst(v)||void 0,style:FEs(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return ze.createElement(u,xC({key:i},h),y)}}const BEs=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var UEs=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function ast(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(s){return Object.getOwnPropertyDescriptor(e,s).enumerable})),n.push.apply(n,r)}return n}function rS(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?ast(Object(n),!0).forEach(function(r){$Gt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ast(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var qEs=/\n/g;function VEs(e){return e.match(qEs)}function HEs(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,a){var i=a+n;return ze.createElement("span",{key:"line-".concat(a),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
|
|
696
696
|
`))})}function WEs(e){var t=e.codeString,n=e.codeStyle,r=e.containerStyle,s=r===void 0?{float:"left",paddingRight:"10px"}:r,a=e.numberStyle,i=a===void 0?{}:a,l=e.startingLineNumber;return ze.createElement("code",{style:Object.assign({},n,s)},HEs({lines:t.replace(/\n$/,"").split(`
|
|
697
697
|
`),style:i,startingLineNumber:l}))}function ZEs(e){return"".concat(e.toString().length,".25em")}function DGt(e,t){return{type:"element",tagName:"span",properties:{key:"line-number--".concat(e),className:["comment","linenumber","react-syntax-highlighter-line-number"],style:t},children:[{type:"text",value:e}]}}function LGt(e,t,n){var r={display:"inline-block",minWidth:ZEs(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=rS(rS({},r),s);return a}function w7(e){var t=e.children,n=e.lineNumber,r=e.lineNumberStyle,s=e.largestLineNumber,a=e.showInlineLineNumbers,i=e.lineProps,l=i===void 0?{}:i,c=e.className,u=c===void 0?[]:c,d=e.showLineNumbers,f=e.wrapLongLines,h=e.wrapLines,p=h===void 0?!1:h,m=p?rS({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(Awe(m.className.trim().split(/\s+/)),Awe(u)):u,n&&a){var v=LGt(r,n,s);t.unshift(DGt(n,v))}return f&d&&(m.style=rS({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function FGt(e){for(var t=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],n=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],r=0;r<e.length;r++){var s=e[r];if(s.type==="text")n.push(w7({children:[s],className:Awe(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);FGt(s.children,a).forEach(function(i){return n.push(i)})}}return n}function GEs(e,t,n,r,s,a,i,l,c){var u,d=FGt(e.value),f=[],h=-1,p=0;function m(O,_){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return w7({children:O,lineNumber:_,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:T,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function v(O,_){if(r&&_&&s){var T=LGt(l,_,i);O.unshift(DGt(_,T))}return O}function y(O,_){var T=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||T.length>0?m(O,_,T):v(O,_)}for(var b=function(){var _=d[p],T=_.children[0].value,E=VEs(T);if(E){var N=T.split(`
|