@mastra/deployer-cloud 1.66.0-alpha.4 → 1.66.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-XzdCljR7.js → core-DZ8VqGw4.js} +1 -1
- package/dist/studio/assets/{index-yqOx2ahi.js → index-C_pF9NFh.js} +2 -2
- package/dist/studio/assets/{main-CKy-QYA2.js → main-CFNEuACq.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-DZ8VqGw4.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 qa}from"./preload-helper-PPVm8Dsz.js";function IYt(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 Pj=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{};function ql(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}var jX={exports:{}},wR={};var q2e;function AYt(){if(q2e)return wR;q2e=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 wR.Fragment=t,wR.jsx=n,wR.jsxs=n,wR}var V2e;function RYt(){return V2e||(V2e=1,jX.exports=AYt()),jX.exports}var o=RYt(),NX={exports:{}},Gr={},H2e;function PYt(){if(H2e)return Gr;H2e=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(z){return z===null||typeof z!="object"?null:(z=p&&z[p]||z["@@iterator"],typeof z=="function"?z:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},y=Object.assign,b={};function x(z,$,U){this.props=z,this.context=$,this.refs=b,this.updater=U||v}x.prototype.isReactComponent={},x.prototype.setState=function(z,$){if(typeof z!="object"&&typeof z!="function"&&z!=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,z,$,"setState")},x.prototype.forceUpdate=function(z){this.updater.enqueueForceUpdate(this,z,"forceUpdate")};function w(){}w.prototype=x.prototype;function k(z,$,U){this.props=z,this.context=$,this.refs=b,this.updater=U||v}var O=k.prototype=new w;O.constructor=k,y(O,x.prototype),O.isPureReactComponent=!0;var _=Array.isArray;function E(){}var T={H:null,A:null,T:null,S:null},N=Object.prototype.hasOwnProperty;function I(z,$,U){var W=U.ref;return{$$typeof:t,type:z,key:$,ref:W!==void 0?W:null,props:U}}function A(z,$){return I(z.type,$,z.props)}function R(z){return typeof z=="object"&&z!==null&&z.$$typeof===t}function L(z){var $={"=":"=0",":":"=2"};return"$"+z.replace(/[=:]/g,function(U){return $[U]})}var M=/\/+/g;function B(z,$){return typeof z=="object"&&z!==null&&z.key!=null?L(""+z.key):$.toString(36)}function V(z){switch(z.status){case"fulfilled":return z.value;case"rejected":throw z.reason;default:switch(typeof z.status=="string"?z.then(E,E):(z.status="pending",z.then(function($){z.status==="pending"&&(z.status="fulfilled",z.value=$)},function($){z.status==="pending"&&(z.status="rejected",z.reason=$)})),z.status){case"fulfilled":return z.value;case"rejected":throw z.reason}}throw z}function q(z,$,U,W,Y){var te=typeof z;(te==="undefined"||te==="boolean")&&(z=null);var ee=!1;if(z===null)ee=!0;else switch(te){case"bigint":case"string":case"number":ee=!0;break;case"object":switch(z.$$typeof){case t:case n:ee=!0;break;case f:return ee=z._init,q(ee(z._payload),$,U,W,Y)}}if(ee)return Y=Y(z),ee=W===""?"."+B(z,0):W,_(Y)?(U="",ee!=null&&(U=ee.replace(M,"$&/")+"/"),q(Y,$,U,"",function(le){return le})):Y!=null&&(R(Y)&&(Y=A(Y,U+(Y.key==null||z&&z.key===Y.key?"":(""+Y.key).replace(M,"$&/")+"/")+ee)),$.push(Y)),1;ee=0;var J=W===""?".":W+":";if(_(z))for(var re=0;re<z.length;re++)W=z[re],te=J+B(W,re),ee+=q(W,$,U,te,Y);else if(re=m(z),typeof re=="function")for(z=re.call(z),re=0;!(W=z.next()).done;)W=W.value,te=J+B(W,re++),ee+=q(W,$,U,te,Y);else if(te==="object"){if(typeof z.then=="function")return q(V(z),$,U,W,Y);throw $=String(z),Error("Objects are not valid as a React child (found: "+($==="[object Object]"?"object with keys {"+Object.keys(z).join(", ")+"}":$)+"). If you meant to render a collection of children, use an array instead.")}return ee}function F(z,$,U){if(z==null)return z;var W=[],Y=0;return q(z,W,"","",function(te){return $.call(U,te,Y++)}),W}function H(z){if(z._status===-1){var $=z._result;$=$(),$.then(function(U){(z._status===0||z._status===-1)&&(z._status=1,z._result=U)},function(U){(z._status===0||z._status===-1)&&(z._status=2,z._result=U)}),z._status===-1&&(z._status=0,z._result=$)}if(z._status===1)return z._result.default;throw z._result}var D=typeof reportError=="function"?reportError:function(z){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var $=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof z=="object"&&z!==null&&typeof z.message=="string"?String(z.message):String(z),error:z});if(!window.dispatchEvent($))return}else if(typeof e=="object"&&typeof e.emit=="function"){e.emit("uncaughtException",z);return}console.error(z)},G={map:F,forEach:function(z,$,U){F(z,function(){$.apply(this,arguments)},U)},count:function(z){var $=0;return F(z,function(){$++}),$},toArray:function(z){return F(z,function($){return $})||[]},only:function(z){if(!R(z))throw Error("React.Children.only expected to receive a single React element child.");return z}};return Gr.Activity=h,Gr.Children=G,Gr.Component=x,Gr.Fragment=r,Gr.Profiler=a,Gr.PureComponent=k,Gr.StrictMode=s,Gr.Suspense=u,Gr.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=T,Gr.__COMPILER_RUNTIME={__proto__:null,c:function(z){return T.H.useMemoCache(z)}},Gr.cache=function(z){return function(){return z.apply(null,arguments)}},Gr.cacheSignal=function(){return null},Gr.cloneElement=function(z,$,U){if(z==null)throw Error("The argument must be a React element, but you passed "+z+".");var W=y({},z.props),Y=z.key;if($!=null)for(te in $.key!==void 0&&(Y=""+$.key),$)!N.call($,te)||te==="key"||te==="__self"||te==="__source"||te==="ref"&&$.ref===void 0||(W[te]=$[te]);var te=arguments.length-2;if(te===1)W.children=U;else if(1<te){for(var ee=Array(te),J=0;J<te;J++)ee[J]=arguments[J+2];W.children=ee}return I(z.type,Y,W)},Gr.createContext=function(z){return z={$$typeof:l,_currentValue:z,_currentValue2:z,_threadCount:0,Provider:null,Consumer:null},z.Provider=z,z.Consumer={$$typeof:i,_context:z},z},Gr.createElement=function(z,$,U){var W,Y={},te=null;if($!=null)for(W in $.key!==void 0&&(te=""+$.key),$)N.call($,W)&&W!=="key"&&W!=="__self"&&W!=="__source"&&(Y[W]=$[W]);var ee=arguments.length-2;if(ee===1)Y.children=U;else if(1<ee){for(var J=Array(ee),re=0;re<ee;re++)J[re]=arguments[re+2];Y.children=J}if(z&&z.defaultProps)for(W in ee=z.defaultProps,ee)Y[W]===void 0&&(Y[W]=ee[W]);return I(z,te,Y)},Gr.createRef=function(){return{current:null}},Gr.forwardRef=function(z){return{$$typeof:c,render:z}},Gr.isValidElement=R,Gr.lazy=function(z){return{$$typeof:f,_payload:{_status:-1,_result:z},_init:H}},Gr.memo=function(z,$){return{$$typeof:d,type:z,compare:$===void 0?null:$}},Gr.startTransition=function(z){var $=T.T,U={};T.T=U;try{var W=z(),Y=T.S;Y!==null&&Y(U,W),typeof W=="object"&&W!==null&&typeof W.then=="function"&&W.then(E,D)}catch(te){D(te)}finally{$!==null&&U.types!==null&&($.types=U.types),T.T=$}},Gr.unstable_useCacheRefresh=function(){return T.H.useCacheRefresh()},Gr.use=function(z){return T.H.use(z)},Gr.useActionState=function(z,$,U){return T.H.useActionState(z,$,U)},Gr.useCallback=function(z,$){return T.H.useCallback(z,$)},Gr.useContext=function(z){return T.H.useContext(z)},Gr.useDebugValue=function(){},Gr.useDeferredValue=function(z,$){return T.H.useDeferredValue(z,$)},Gr.useEffect=function(z,$){return T.H.useEffect(z,$)},Gr.useEffectEvent=function(z){return T.H.useEffectEvent(z)},Gr.useId=function(){return T.H.useId()},Gr.useImperativeHandle=function(z,$,U){return T.H.useImperativeHandle(z,$,U)},Gr.useInsertionEffect=function(z,$){return T.H.useInsertionEffect(z,$)},Gr.useLayoutEffect=function(z,$){return T.H.useLayoutEffect(z,$)},Gr.useMemo=function(z,$){return T.H.useMemo(z,$)},Gr.useOptimistic=function(z,$){return T.H.useOptimistic(z,$)},Gr.useReducer=function(z,$,U){return T.H.useReducer(z,$,U)},Gr.useRef=function(z){return T.H.useRef(z)},Gr.useState=function(z){return T.H.useState(z)},Gr.useSyncExternalStore=function(z,$,U){return T.H.useSyncExternalStore(z,$,U)},Gr.useTransition=function(){return T.H.useTransition()},Gr.version="19.2.7",Gr}var W2e;function oI(){return W2e||(W2e=1,NX.exports=PYt()),NX.exports}var g=oI();const qe=ql(g),lI=IYt({__proto__:null,default:qe},[g]);var IX={exports:{}},SR={},AX={exports:{}},RX={};var Z2e;function $Yt(){return Z2e||(Z2e=1,(function(e){function t(V,q){var F=V.length;V.push(q);e:for(;0<F;){var H=F-1>>>1,D=V[H];if(0<s(D,q))V[H]=q,V[F]=D,F=H;else break e}}function n(V){return V.length===0?null:V[0]}function r(V){if(V.length===0)return null;var q=V[0],F=V.pop();if(F!==q){V[0]=F;e:for(var H=0,D=V.length,G=D>>>1;H<G;){var z=2*(H+1)-1,$=V[z],U=z+1,W=V[U];if(0>s($,F))U<D&&0>s(W,$)?(V[H]=W,V[U]=F,H=U):(V[H]=$,V[z]=F,H=z);else if(U<D&&0>s(W,F))V[H]=W,V[U]=F,H=U;else break e}}return q}function s(V,q){var F=V.sortIndex-q.sortIndex;return F!==0?F:V.id-q.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(V){for(var q=n(u);q!==null;){if(q.callback===null)r(u);else if(q.startTime<=V)r(u),q.sortIndex=q.expirationTime,t(c,q);else break;q=n(u)}}function O(V){if(v=!1,k(V),!m)if(n(c)!==null)m=!0,_||(_=!0,R());else{var q=n(u);q!==null&&B(O,q.startTime-V)}}var _=!1,E=-1,T=5,N=-1;function I(){return y?!0:!(e.unstable_now()-N<T)}function A(){if(y=!1,_){var V=e.unstable_now();N=V;var q=!0;try{e:{m=!1,v&&(v=!1,x(E),E=-1),p=!0;var F=h;try{t:{for(k(V),f=n(c);f!==null&&!(f.expirationTime>V&&I());){var H=f.callback;if(typeof H=="function"){f.callback=null,h=f.priorityLevel;var D=H(f.expirationTime<=V);if(V=e.unstable_now(),typeof D=="function"){f.callback=D,k(V),q=!0;break t}f===n(c)&&r(c),k(V)}else r(c);f=n(c)}if(f!==null)q=!0;else{var G=n(u);G!==null&&B(O,G.startTime-V),q=!1}}break e}finally{f=null,h=F,p=!1}q=void 0}}finally{q?R():_=!1}}}var R;if(typeof w=="function")R=function(){w(A)};else if(typeof MessageChannel<"u"){var L=new MessageChannel,M=L.port2;L.port1.onmessage=A,R=function(){M.postMessage(null)}}else R=function(){b(A,0)};function B(V,q){E=b(function(){V(e.unstable_now())},q)}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(V){V.callback=null},e.unstable_forceFrameRate=function(V){0>V||125<V?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):T=0<V?Math.floor(1e3/V):5},e.unstable_getCurrentPriorityLevel=function(){return h},e.unstable_next=function(V){switch(h){case 1:case 2:case 3:var q=3;break;default:q=h}var F=h;h=q;try{return V()}finally{h=F}},e.unstable_requestPaint=function(){y=!0},e.unstable_runWithPriority=function(V,q){switch(V){case 1:case 2:case 3:case 4:case 5:break;default:V=3}var F=h;h=V;try{return q()}finally{h=F}},e.unstable_scheduleCallback=function(V,q,F){var H=e.unstable_now();switch(typeof F=="object"&&F!==null?(F=F.delay,F=typeof F=="number"&&0<F?H+F:H):F=H,V){case 1:var D=-1;break;case 2:D=250;break;case 5:D=1073741823;break;case 4:D=1e4;break;default:D=5e3}return D=F+D,V={id:d++,callback:q,priorityLevel:V,startTime:F,expirationTime:D,sortIndex:-1},F>H?(V.sortIndex=F,t(u,V),n(c)===null&&V===n(u)&&(v?(x(E),E=-1):v=!0,B(O,F-H))):(V.sortIndex=D,t(c,V),m||p||(m=!0,_||(_=!0,R()))),V},e.unstable_shouldYield=I,e.unstable_wrapCallback=function(V){var q=h;return function(){var F=h;h=q;try{return V.apply(this,arguments)}finally{h=F}}}})(RX)),RX}var G2e;function MYt(){return G2e||(G2e=1,AX.exports=$Yt()),AX.exports}var PX={exports:{}},Tu={};var Q2e;function DYt(){if(Q2e)return Tu;Q2e=1;var e=oI();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 Tu.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,Tu.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)},Tu.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()}},Tu.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))},Tu.prefetchDNS=function(c){typeof c=="string"&&r.d.D(c)},Tu.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})}},Tu.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)},Tu.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})}},Tu.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)},Tu.requestFormReset=function(c){r.d.r(c)},Tu.unstable_batchedUpdates=function(c,u){return c(u)},Tu.useFormState=function(c,u,d){return i.H.useFormState(c,u,d)},Tu.useFormStatus=function(){return i.H.useHostTransitionStatus()},Tu.version="19.2.7",Tu}var Y2e;function cut(){if(Y2e)return PX.exports;Y2e=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(),PX.exports=DYt(),PX.exports}var K2e;function LYt(){if(K2e)return SR;K2e=1;var e={env:{}};var t=MYt(),n=oI(),r=cut();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 Q=Z.alternate;if(Q===null){if(P=Z.return,P!==null){j=P;continue}break}if(Z.child===Q.child){for(Q=Z.child;Q;){if(Q===j)return u(Z),S;if(Q===P)return u(Z),C;Q=Q.sibling}throw Error(s(188))}if(j.return!==P.return)j=Z,P=Q;else{for(var ie=!1,we=Z.child;we;){if(we===j){ie=!0,j=Z,P=Q;break}if(we===P){ie=!0,P=Z,j=Q;break}we=we.sibling}if(!ie){for(we=Q.child;we;){if(we===j){ie=!0,j=Q,P=Z;break}if(we===P){ie=!0,P=Q,j=Z;break}we=we.sibling}if(!ie)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"),E=Symbol.for("react.suspense_list"),T=Symbol.for("react.memo"),N=Symbol.for("react.lazy"),I=Symbol.for("react.activity"),A=Symbol.for("react.memo_cache_sentinel"),R=Symbol.iterator;function L(S){return S===null||typeof S!="object"?null:(S=R&&S[R]||S["@@iterator"],typeof S=="function"?S:null)}var M=Symbol.for("react.client.reference");function B(S){if(S==null)return null;if(typeof S=="function")return S.$$typeof===M?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 E: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 T:return C=S.displayName||null,C!==null?C:B(S.type)||"Memo";case N:C=S._payload,S=S._init;try{return B(S(C))}catch{}}return null}var V=Array.isArray,q=n.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,F=r.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,H={pending:!1,data:null,method:null,action:null},D=[],G=-1;function z(S){return{current:S}}function $(S){0>G||(S.current=D[G],D[G]=null,G--)}function U(S,C){G++,D[G]=S.current,S.current=C}var W=z(null),Y=z(null),te=z(null),ee=z(null);function J(S,C){switch(U(te,C),U(Y,S),U(W,null),C.nodeType){case 9:case 11:S=(S=C.documentElement)&&(S=S.namespaceURI)?f2e(S):0;break;default:if(S=C.tagName,C=C.namespaceURI)C=f2e(C),S=h2e(C,S);else switch(S){case"svg":S=1;break;case"math":S=2;break;default:S=0}}$(W),U(W,S)}function re(){$(W),$(Y),$(te)}function le(S){S.memoizedState!==null&&U(ee,S);var C=W.current,j=h2e(C,S.type);C!==j&&(U(Y,S),U(W,j))}function X(S){Y.current===S&&($(W),$(Y)),ee.current===S&&($(ee),vR._currentValue=H)}var ne,se;function de(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 ue=!1;function ye(S,C){if(!S||ue)return"";ue=!0;var j=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var P={DetermineComponentFrameRoot:function(){try{if(C){var Rt=function(){throw Error()};if(Object.defineProperty(Rt.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(Rt,[])}catch(gt){var ct=gt}Reflect.construct(S,[],Rt)}else{try{Rt.call()}catch(gt){ct=gt}S.call(Rt.prototype)}}else{try{throw Error()}catch(gt){ct=gt}(Rt=S())&&typeof Rt.catch=="function"&&Rt.catch(function(){})}}catch(gt){if(gt&&ct&&typeof gt.stack=="string")return[gt.stack,ct.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 Q=P.DetermineComponentFrameRoot(),ie=Q[0],we=Q[1];if(ie&&we){var He=ie.split(`
|
|
@@ -231,7 +231,7 @@ attempted value: ${i}
|
|
|
231
231
|
\${}
|
|
232
232
|
}
|
|
233
233
|
}`,{label:"class",detail:"definition",type:"keyword"}),df('import {${names}} from "${module}"\n${}',{label:"import",detail:"named",type:"keyword"}),df('import ${name} from "${module}"\n${}',{label:"import",detail:"default",type:"keyword"})],eOt=AOe.concat([df("interface ${name} {\n ${}\n}",{label:"interface",detail:"definition",type:"keyword"}),df("type ${name} = ${type}",{label:"type",detail:"definition",type:"keyword"}),df("enum ${name} {\n ${}\n}",{label:"enum",detail:"definition",type:"keyword"})]),Z9e=new rSt,tOt=new Set(["Script","Block","FunctionExpression","FunctionDeclaration","ArrowFunction","MethodDeclaration","ForStatement"]);function ZR(e){return(t,n)=>{let r=t.node.getChild("VariableDefinition");return r&&n(r,e),!0}}const UVn=["FunctionDeclaration"],qVn={FunctionDeclaration:ZR("function"),ClassDeclaration:ZR("class"),ClassExpression:()=>!0,EnumDeclaration:ZR("constant"),TypeAliasDeclaration:ZR("type"),NamespaceDeclaration:ZR("namespace"),VariableDefinition(e,t){e.matchContext(UVn)||t(e,"variable")},TypeDefinition(e,t){t(e,"type")},__proto__:null};function nOt(e,t){let n=Z9e.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(Va.IncludeAnonymous).iterate(i=>{if(s)s=!1;else if(i.name){let l=qVn[i.name];if(l&&l(i,a)||tOt.has(i.name))return!1}else if(i.to-i.from>8192){for(let l of nOt(e,i.node))r.push(l);return!1}}),Z9e.set(t,r),r}const sU=/^[\w$\xa1-\uffff][\w$\d\xa1-\uffff]*$/,ROe=["TemplateString","String","RegExp","LineComment","BlockComment","VariableDefinition","TypeDefinition","Label","PropertyDefinition","PropertyName","PrivatePropertyDefinition","PrivatePropertyName","JSXText","JSXAttributeValue","JSXOpenTag","JSXCloseTag","JSXSelfClosingTag",".","?."];function rOt(e){let t=vi(e.state).resolveInner(e.pos,-1);if(ROe.indexOf(t.name)>-1)return null;let n=t.name=="VariableName"||t.to-t.from<20&&sU.test(e.state.sliceDoc(t.from,t.to));if(!n&&!e.explicit)return null;let r=[];for(let s=t;s;s=s.parent)tOt.has(s.name)&&(r=r.concat(nOt(e.state.doc,s)));return{options:r,from:n?t.from:e.pos,validFor:sU}}function vte(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 sOt(e){let t=r=>e.state.doc.sliceString(r.from,r.to),n=vi(e.state).resolveInner(e.pos,-1);return n.name=="PropertyName"?vte(t,n.parent,t(n)):(n.name=="."||n.name=="?.")&&n.parent.name=="MemberExpression"?vte(t,n.parent,""):ROe.indexOf(n.name)>-1?null:n.name=="VariableName"||n.to-n.from<20&&sU.test(t(n))?{path:[],name:t(n)}:n.name=="MemberExpression"?vte(t,n,""):e.explicit?{path:[],name:""}:null}function VVn(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 HVn(e){let t=new Map;return n=>{let r=sOt(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=VVn(s,!r.path.length)),{from:n.pos-r.name.length,options:a,validFor:sU}}}const im=tC.define({name:"javascript",parser:BVn.configure({props:[d_.add({IfStatement:mj({except:/^\s*({|else\b)/}),TryStatement:mj({except:/^\s*({|catch\b|finally\b)/}),LabeledStatement:F7n,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:L7n({closing:"}"}),ArrowFunction:e=>e.baseIndent+e.unit,"TemplateString BlockComment":()=>null,"Statement Property":mj({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}}),f_.add({"Block ClassBody SwitchBody EnumBody ObjectExpression ArrayExpression ObjectType":fOe,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:"$"}}),aOt={test:e=>/^JSX/.test(e.name),facet:gW({commentTokens:{block:{open:"{/*",close:"*/}"}}})},POe=im.configure({dialect:"ts"},"typescript"),$Oe=im.configure({dialect:"jsx",props:[cOe.add(e=>e.isTop?[aOt]:void 0)]}),MOe=im.configure({dialect:"jsx ts",props:[cOe.add(e=>e.isTop?[aOt]:void 0)]},"typescript");let iOt=e=>({label:e,type:"keyword"});const oOt="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(iOt),WVn=oOt.concat(["declare","implements","private","protected","public"].map(iOt));function aU(e={}){let t=e.jsx?e.typescript?MOe:$Oe:e.typescript?POe:im,n=e.typescript?eOt.concat(WVn):AOe.concat(oOt);return new rC(t,[im.data.of({autocomplete:OBn(ROe,akt(n))}),im.data.of({autocomplete:rOt}),e.jsx?lOt:[]])}function ZVn(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 G9e(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 GVn=typeof navigator=="object"&&/Android\b/.test(navigator.userAgent),lOt=At.inputHandler.of((e,t,n,r,s)=>{if((GVn?e.composing:e.compositionStarted)||e.state.readOnly||t!=n||r!=">"&&r!="/"||!im.isActiveAt(e.state,t,-1))return!1;let a=s(),{state:i}=a,l=i.changeByRange(c=>{var u;let{head:d}=c,f=vi(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=G9e(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=ZVn(f);if(p&&p.name=="JSXOpenTag"&&!/^\/?>|^<\//.test(i.doc.sliceString(d,d+2))&&(h=G9e(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 QVn(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 im.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(YVn(u,r.doc,c))}return s}}function Q9e(e,t,n,r){return n.line(e+r.line).from+t+(e==1?r.col-1:-1)}function YVn(e,t,n){let r=Q9e(e.line,e.column,t,n),s={from:r,to:e.endLine!=null&&e.endColumn!=1?Q9e(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 TF=Object.freeze(Object.defineProperty({__proto__:null,autoCloseTags:lOt,completionPath:sOt,esLint:QVn,javascript:aU,javascriptLanguage:im,jsxLanguage:$Oe,localCompletionSource:rOt,scopeCompletionSource:HVn,snippets:AOe,tsxLanguage:MOe,typescriptLanguage:POe,typescriptSnippets:eOt},Symbol.toStringTag,{value:"Module"})),GR=["_blank","_self","_top","_parent"],yte=["ascii","utf-8","utf-16","latin1","latin1"],bte=["get","post","put","delete"],xte=["application/x-www-form-urlencoded","multipart/form-data","text/plain"],hh=["true","false"],Jn={},KVn={a:{attrs:{href:null,ping:null,type:null,media:null,target:GR,hreflang:null}},abbr:Jn,address:Jn,area:{attrs:{alt:null,coords:null,href:null,target:null,ping:null,media:null,hreflang:null,type:null,shape:["default","rect","circle","poly"]}},article:Jn,aside:Jn,audio:{attrs:{src:null,mediagroup:null,crossorigin:["anonymous","use-credentials"],preload:["none","metadata","auto"],autoplay:["autoplay"],loop:["loop"],controls:["controls"]}},b:Jn,base:{attrs:{href:null,target:GR}},bdi:Jn,bdo:Jn,blockquote:{attrs:{cite:null}},body:Jn,br:Jn,button:{attrs:{form:null,formaction:null,name:null,value:null,autofocus:["autofocus"],disabled:["autofocus"],formenctype:xte,formmethod:bte,formnovalidate:["novalidate"],formtarget:GR,type:["submit","reset","button"]}},canvas:{attrs:{width:null,height:null}},caption:Jn,center:Jn,cite:Jn,code:Jn,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:Jn,del:{attrs:{cite:null,datetime:null}},details:{attrs:{open:["open"]}},dfn:Jn,div:Jn,dl:Jn,dt:Jn,em:Jn,embed:{attrs:{src:null,type:null,width:null,height:null}},eventsource:{attrs:{src:null}},fieldset:{attrs:{disabled:["disabled"],form:null,name:null}},figcaption:Jn,figure:Jn,footer:Jn,form:{attrs:{action:null,name:null,"accept-charset":yte,autocomplete:["on","off"],enctype:xte,method:bte,novalidate:["novalidate"],target:GR}},h1:Jn,h2:Jn,h3:Jn,h4:Jn,h5:Jn,h6:Jn,head:{children:["title","base","link","style","meta","script","noscript","command"]},header:Jn,hgroup:Jn,hr:Jn,html:{attrs:{manifest:null}},i:Jn,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:xte,formmethod:bte,formnovalidate:["novalidate"],formtarget:GR,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:Jn,keygen:{attrs:{challenge:null,form:null,name:null,autofocus:["autofocus"],disabled:["disabled"],keytype:["RSA"]}},label:{attrs:{for:null,form:null}},legend:Jn,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:Jn,menu:{attrs:{label:null,type:["list","context","toolbar"]}},meta:{attrs:{content:null,charset:yte,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:Jn,noscript:Jn,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:Jn,param:{attrs:{name:null,value:null}},pre:Jn,progress:{attrs:{value:null,max:null}},q:{attrs:{cite:null}},rp:Jn,rt:Jn,ruby:Jn,samp:Jn,script:{attrs:{type:["text/javascript"],src:null,async:["async"],defer:["defer"],charset:yte}},section:Jn,select:{attrs:{form:null,name:null,size:null,autofocus:["autofocus"],disabled:["disabled"],multiple:["multiple"]}},slot:{attrs:{name:null}},small:Jn,source:{attrs:{src:null,type:null,media:null}},span:Jn,strong:Jn,style:{attrs:{type:["text/css"],media:null,scoped:null}},sub:Jn,summary:Jn,sup:Jn,table:Jn,tbody:Jn,td:{attrs:{colspan:null,rowspan:null,headers:null}},template:Jn,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:Jn,th:{attrs:{colspan:null,rowspan:null,headers:null,scope:["row","col","rowgroup","colgroup"]}},thead:Jn,time:{attrs:{datetime:null}},title:Jn,tr:Jn,track:{attrs:{src:null,label:null,default:null,kind:["subtitles","captions","descriptions","chapters","metadata"],srclang:null}},ul:{children:["li","script","template","ul","ol"]},var:Jn,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:Jn},cOt={accesskey:null,class:null,contenteditable:hh,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:hh,autocorrect:hh,autocapitalize:hh,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":hh,"aria-autocomplete":["inline","list","both","none"],"aria-busy":hh,"aria-checked":["true","false","mixed","undefined"],"aria-controls":null,"aria-describedby":null,"aria-disabled":hh,"aria-dropeffect":null,"aria-expanded":["true","false","undefined"],"aria-flowto":null,"aria-grabbed":["true","false","undefined"],"aria-haspopup":hh,"aria-hidden":hh,"aria-invalid":["true","false","grammar","spelling"],"aria-label":null,"aria-labelledby":null,"aria-level":null,"aria-live":["off","polite","assertive"],"aria-multiline":hh,"aria-multiselectable":hh,"aria-owns":null,"aria-posinset":null,"aria-pressed":["true","false","mixed","undefined"],"aria-readonly":hh,"aria-relevant":null,"aria-required":hh,"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},uOt="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 uOt)cOt[e]=null;class V2{constructor(t,n){this.tags={...KVn,...t},this.globalAttrs={...cOt,...n},this.allTags=Object.keys(this.tags),this.globalAttrNames=Object.keys(this.globalAttrs)}}V2.default=new V2;function oN(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 lN(e,t=!1){for(;e;e=e.parent)if(e.name=="Element")if(t)t=!1;else return e;return null}function dOt(e,t,n){let r=n.tags[oN(e,lN(t))];return r?.children||n.allTags}function DOe(e,t){let n=[];for(let r=lN(t);r&&!r.type.isTop;r=lN(r.parent)){let s=oN(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 fOt=/^[:\-\.\w\u00b7-\uffff]*$/;function Y9e(e,t,n,r,s){let a=/\s*>/.test(e.sliceDoc(s,s+5))?"":">",i=lN(n,n.name=="StartTag"||n.name=="TagName");return{from:r,to:s,options:dOt(e.doc,i,t).map(l=>({label:l,type:"type"})).concat(DOe(e.doc,n).map((l,c)=>({label:"/"+l,apply:"/"+l+a,type:"type",boost:99-c}))),validFor:/^\/?[:\-\.\w\u00b7-\uffff]*$/}}function K9e(e,t,n,r){let s=/\s*>/.test(e.sliceDoc(r,r+5))?"":">";return{from:n,to:r,options:DOe(e.doc,t).map((a,i)=>({label:a,apply:a+s,type:"type",boost:99-i})),validFor:fOt}}function XVn(e,t,n,r){let s=[],a=0;for(let i of dOt(e.doc,n,t))s.push({label:"<"+i,type:"type"});for(let i of DOe(e.doc,n))s.push({label:"</"+i+">",type:"type",boost:99-a++});return{from:r,to:r,options:s,validFor:/^<\/?[:\-\.\w\u00b7-\uffff]*$/}}function JVn(e,t,n,r,s){let a=lN(n),i=a?t.tags[oN(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:fOt}}function eHn(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=lN(n),h=f?t.tags[oN(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 hOt(e,t){let{state:n,pos:r}=t,s=vi(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)?K9e(n,s,s.from,r):Y9e(n,e,s,s.from,r):s.name=="StartTag"||s.name=="IncompleteTag"?Y9e(n,e,s,r,r):s.name=="StartCloseTag"||s.name=="IncompleteCloseTag"?K9e(n,s,r,r):s.name=="OpenTag"||s.name=="SelfClosingTag"||s.name=="AttributeName"?JVn(n,e,s,s.name=="AttributeName"?s.from:r,r):s.name=="Is"||s.name=="AttributeValue"||s.name=="UnquotedAttributeValue"?eHn(n,e,s,s.name=="Is"?r:s.from,r):t.explicit&&(a.name=="Element"||a.name=="Text"||a.name=="Document")?XVn(n,e,s,r):null}function tHn(e){return hOt(V2.default,e)}function nHn(e){let{extraTags:t,extraGlobalAttributes:n}=e,r=n||t?new V2(t,n):V2.default;return s=>hOt(r,s)}const rHn=im.parser.configure({top:"SingleExpression"}),pOt=[{tag:"script",attrs:e=>e.type=="text/typescript"||e.lang=="ts",parser:POe.parser},{tag:"script",attrs:e=>e.type=="text/babel"||e.type=="text/jsx",parser:$Oe.parser},{tag:"script",attrs:e=>e.type=="text/typescript-jsx",parser:MOe.parser},{tag:"script",attrs(e){return/^(importmap|speculationrules|application\/(.+\+)?json)$/i.test(e.type)},parser:rHn},{tag:"script",attrs(e){return!e.type||/^(?:text|application)\/(?:x-)?(?:java|ecma)script$|^module$|^$/i.test(e.type)},parser:im.parser},{tag:"style",attrs(e){return(!e.lang||e.lang=="css")&&(!e.type||/^(text\/)?(x-)?(stylesheet|css)$/i.test(e.type))},parser:rU.parser}],mOt=[{name:"style",parser:rU.parser.configure({top:"Styles"})}].concat(uOt.map(e=>({name:e,parser:im.parser}))),gOt=tC.define({name:"html",parser:Tqn.configure({props:[d_.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}}),f_.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}}}),X1t.add({"OpenTag CloseTag":e=>e.getChild("TagName")})]}),languageData:{commentTokens:{block:{open:"<!--",close:"-->"}},indentOnInput:/^\s*<\/\w+\W$/,wordChars:"-_"}}),l9=gOt.configure({wrap:Zkt(pOt,mOt)});function sHn(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=Zkt((e.nestedLanguages||[]).concat(pOt),(e.nestedAttributes||[]).concat(mOt)));let r=n?gOt.configure({wrap:n,dialect:t}):t?l9.configure({dialect:t}):l9;return new rC(r,[l9.data.of({autocomplete:nHn(e)}),e.autoCloseTags!==!1?aHn:[],aU().support,uVn().support])}const X9e=new Set("area base br col command embed frame hr img input keygen link meta param source track wbr menuitem".split(" ")),aHn=At.inputHandler.of((e,t,n,r,s)=>{if(e.composing||e.state.readOnly||t!=n||r!=">"&&r!="/"||!l9.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=vi(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=oN(i.doc,y.parent,p))&&!X9e.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=oN(i.doc,y,p))&&!X9e.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)}),vOt=gW({commentTokens:{block:{open:"<!--",close:"-->"}}}),yOt=new Mr,bOt=NUn.configure({props:[f_.add(e=>!e.is("Block")||e.is("Document")||Fve(e)!=null||iHn(e)?void 0:(t,n)=>({from:n.doc.lineAt(t.from).to,to:t.to})),yOt.add(Fve),d_.add({Document:()=>null}),Dw.add({Document:vOt})]});function Fve(e){let t=/^(?:ATX|Setext)Heading(\d)$/.exec(e.name);return t?+t[1]:void 0}function iHn(e){return e.name=="OrderedList"||e.name=="BulletList"}function oHn(e,t){let n=e;for(;;){let r=n.nextSibling,s;if(!r||(s=Fve(r.type))!=null&&s<=t)break;n=r}return n.to}const lHn=z1t.of((e,t,n)=>{for(let r=vi(e).resolveInner(n,-1);r&&!(r.from<t);r=r.parent){let s=r.type.prop(yOt);if(s==null)continue;let a=oHn(r,s);if(a>n)return{from:n,to:a}}return null});function LOe(e){return new Rh(vOt,e,[],"markdown")}const xOt=LOe(bOt),cHn=bOt.configure([BUn,qUn,UUn,VUn,{props:[f_.add({Table:(e,t)=>({from:t.doc.lineAt(e.from).to,to:e.to})})]}]),iC=LOe(cHn);function uHn(e,t){return n=>{if(n&&e){let r=null;if(n=/\S*/.exec(n)[0],typeof e=="function"?r=e(n):r=mg.matchLanguageName(e,n,!0),r instanceof mg)return r.support?r.support.language.parser:nC.getSkippingParser(r.load());if(r)return r.parser}return t?t.parser:null}}class wte{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(+SOt(this.item,t)[2]+n):"";return this.spaceBefore+r+this.type+this.spaceAfter}}function wOt(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 wte(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 wte(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 wte(a.parent,c,c+d,i[1],u,f,a))}}return r}function SOt(e,t){return/^(\s*)(\d+)(?=[.)])/.exec(t.sliceString(e.from,e.from+10))}function Ste(e,t,n,r=0){for(let s=-1,a=e;;){if(a.name=="ListItem"){let l=SOt(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 FOe(e,t){let n=/^[ \t]*/.exec(e)[0].length;if(!n||t.facet(II)!=" ")return e;let r=Ug(e,4,n),s="";for(let a=r;a>0;)a>=4?(s+=" ",a-=4):(s+=" ",a--);return s+e.slice(n)}const kOt=(e={})=>({state:t,dispatch:n})=>{let r=vi(t),{doc:s}=t,a=null,i=t.changeByRange(l=>{if(!l.empty||!iC.isActiveAt(t,l.from,-1)&&!iC.isActiveAt(t,l.from,1))return a={range:l};let c=l.from,u=s.lineAt(c),d=wOt(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"&&Ste(f.item,s,_,-2),w&&w.node.name=="OrderedList"&&Ste(w.item,s,_),{range:St.cursor(k+O.length),changes:_}}else{let w=e7e(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"&&Ste(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?Ug(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=FOe(v,t),dHn(f.node,t.doc)&&(v=e7e(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)},OOt=kOt();function J9e(e){return e.name=="QuoteMark"||e.name=="ListMark"}function dHn(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 e7e(e,t,n){let r="";for(let s=0,a=e.length-2;s<=a;s++)r+=e[s].blank(s<a?Ug(n.text,4,e[s+1].from)-r.length:null,s<a);return FOe(r,t)}function fHn(e,t){let n=e.resolveInner(t,-1),r=t;J9e(n)&&(r=n.from,n=n.parent);for(let s;s=n.childBefore(r);)if(J9e(s))r=s.from;else if(s.name=="OrderedList"||s.name=="BulletList")n=s.lastChild,r=n.to;else break;return n}const COt=({state:e,dispatch:t})=>{let n=vi(e),r=null,s=e.changeByRange(a=>{let i=a.from,{doc:l}=e;if(a.empty&&iC.isActiveAt(e,a.from)){let c=l.lineAt(i),u=wOt(fHn(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(Ug(c.text,4,d.to)-Ug(c.text,4,d.from));return h==c.from&&(p=FOe(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)},_Ot=[{key:"Enter",run:OOt},{key:"Backspace",run:COt}],EOt=sHn({matchClosingTags:!1});function zOe(e={}){let{codeLanguages:t,defaultCodeLanguage:n,addKeymap:r=!0,base:{parser:s}=xOt,completeHTMLTags:a=!0,pasteURLAsLink:i=!0,htmlTagLanguage:l=EOt}=e;if(!(s instanceof xW))throw new RangeError("Base parser provided to `markdown` should be a Markdown parser");let c=e.extensions?[e.extensions]:[],u=[l.support,lHn],d;i&&u.push(TOt),n instanceof rC?(u.push(n.support),d=n.language):n&&(d=n);let f=t||d?uHn(t,d):void 0;c.push(AUn({codeParser:f,htmlParser:l.language.parser})),r&&u.push(ip.high(NI.of(_Ot)));let h=LOe(s.configure(c));return a&&u.push(h.data.of({autocomplete:hHn})),new rC(h,u)}function hHn(e){let{state:t,pos:n}=e,r=/<[:\-\.\w\u00b7-\uffff]*$/.exec(t.sliceDoc(n-25,n));if(!r)return null;let s=vi(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:pHn(),validFor:/^<[:\-\.\w\u00b7-\uffff]*$/}}let kte=null;function pHn(){if(kte)return kte;let e=tHn(new gOe(gs.create({extensions:EOt}),0,!0));return kte=e?e.options:[]}const mHn=/code|horizontalrule|html|link|comment|processing|escape|entity|image|mark|url/i,TOt=At.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),!iC.isActiveAt(t.state,r.from,1)))return!1;let a=vi(t.state),i=!1;return a.iterate({from:r.from,to:r.to,enter:l=>{(l.from>r.from||mHn.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)}}),gHn=Object.freeze(Object.defineProperty({__proto__:null,commonmarkLanguage:xOt,deleteMarkupBackward:COt,insertNewlineContinueMarkup:OOt,insertNewlineContinueMarkupCommand:kOt,markdown:zOe,markdownKeymap:_Ot,markdownLanguage:iC,pasteURLAsLink:TOt},Symbol.toStringTag,{value:"Module"}));function oC(){return oC=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},oC.apply(null,arguments)}var vHn=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=At.theme(i,{dark:t==="dark"}),d=Kg.define(a),f=[u,h1(d)];return f},yHn={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)"},bHn=[{tag:fe.comment,color:"#6272a4"},{tag:fe.string,color:"#f1fa8c"},{tag:fe.atom,color:"#bd93f9"},{tag:fe.meta,color:"#f8f8f2"},{tag:[fe.keyword,fe.operator,fe.tagName],color:"#ff79c6"},{tag:[fe.function(fe.propertyName),fe.propertyName],color:"#66d9ef"},{tag:[fe.definition(fe.variableName),fe.function(fe.variableName),fe.className,fe.attributeName],color:"#50fa7b"},{tag:fe.atom,color:"#bd93f9"}],RI=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 vHn({theme:r,settings:oC({},yHn,a),styles:[...bHn,...l]})};RI();function jOt(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 xHn=e=>{let{state:t}=e,n=t.doc.lineAt(t.selection.main.from),r=UOe(e.state,n.from);return r.line?wHn(e):r.block?kHn(e):!1};function BOe(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 wHn=BOe(_Hn,0),SHn=BOe(NOt,0),kHn=BOe((e,t)=>NOt(e,t,CHn(t)),0);function UOe(e,t){let n=e.languageDataAt("commentTokens",t,1);return n.length?n[0]:{}}const QR=50;function OHn(e,{open:t,close:n},r,s){let a=e.sliceDoc(r-QR,r),i=e.sliceDoc(s,s+QR),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*QR?d=f=e.sliceDoc(r,s):(d=e.sliceDoc(r,r+QR),f=e.sliceDoc(s-QR,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 CHn(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 NOt(e,t,n=t.selection.ranges){let r=n.map(a=>UOe(t,a.from).block);if(!r.every(a=>a))return null;let s=n.map((a,i)=>OHn(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 _Hn(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=UOe(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 zve=Uy.define(),EHn=Uy.define(),THn=kn.define(),IOt=kn.define({combine(e){return qy(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)})}}),AOt=bl.define({create(){return ny.empty},update(e,t){let n=t.state.facet(IOt),r=t.annotation(zve);if(r){let c=Tf.fromTransaction(t,r.selection),u=r.side,d=u==0?e.undone:e.done;return c?d=iU(d,d.length,n.minDepth,c):d=$Ot(d,t.startState.selection),new ny(u==0?r.rest:d,u==0?d:r.rest)}let s=t.annotation(EHn);if((s=="full"||s=="before")&&(e=e.isolate()),t.annotation(Pl.addToHistory)===!1)return t.changes.empty?e:e.addMapping(t.changes.desc);let a=Tf.fromTransaction(t),i=t.annotation(Pl.time),l=t.annotation(Pl.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 ny(e.done.map(Tf.fromJSON),e.undone.map(Tf.fromJSON))}});function jHn(e={}){return[AOt,IOt.of(e),At.domEventHandlers({beforeinput(t,n){let r=t.inputType=="historyUndo"?ROt:t.inputType=="historyRedo"?Bve:null;return r?(t.preventDefault(),r(n)):!1}})]}function wW(e,t){return function({state:n,dispatch:r}){if(!t&&n.readOnly)return!1;let s=n.field(AOt,!1);if(!s)return!1;let a=s.pop(e,n,t);return a?(r(a),!0):!1}}const ROt=wW(0,!1),Bve=wW(1,!1),NHn=wW(0,!0),IHn=wW(1,!0);class Tf{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 Tf(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 Tf(t.changes&&Al.fromJSON(t.changes),[],t.mapped&&hy.fromJSON(t.mapped),t.startSelection&&St.fromJSON(t.startSelection),t.selectionsAfter.map(St.fromJSON))}static fromTransaction(t,n){let r=Kp;for(let s of t.startState.facet(THn)){let a=s(t);a.length&&(r=r.concat(a))}return!r.length&&t.changes.empty?null:new Tf(t.changes.invert(t.startState.doc),r,void 0,n||t.startState.selection,Kp)}static selection(t){return new Tf(void 0,Kp,void 0,void 0,t)}}function iU(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 AHn(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 RHn(e,t){return e.ranges.length==t.ranges.length&&e.ranges.filter((n,r)=>n.empty!=t.ranges[r].empty).length===0}function POt(e,t){return e.length?t.length?e.concat(t):e:t}const Kp=[],PHn=200;function $Ot(e,t){if(e.length){let n=e[e.length-1],r=n.selectionsAfter.slice(Math.max(0,n.selectionsAfter.length-PHn));return r.length&&r[r.length-1].eq(t)?e:(r.push(t),iU(e,e.length-1,1e9,n.setSelAfter(r)))}else return[Tf.selection([t])]}function $Hn(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 Ote(e,t){if(!e.length)return e;let n=e.length,r=Kp;for(;n;){let s=MHn(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?[Tf.selection(r)]:Kp}function MHn(e,t,n){let r=POt(e.selectionsAfter.length?e.selectionsAfter.map(l=>l.map(t)):Kp,n);if(!e.changes)return Tf.selection(r);let s=e.changes.map(t),a=t.mapDesc(e.changes,!0),i=e.mapped?e.mapped.composeDesc(a):a;return new Tf(s,hr.mapEffects(e.effects,t),i,e.startSelection.map(a),r)}const DHn=/^(input\.type|delete)($|\.)/;class ny{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 ny(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||DHn.test(r))&&(!l.selectionsAfter.length&&n-this.prevTime<s.newGroupDelay&&s.joinToEvent(a,AHn(l.changes,t.changes))||r=="input.type.compose")?i=iU(i,i.length-1,s.minDepth,new Tf(t.changes.compose(l.changes),POt(hr.mapEffects(t.effects,l.changes),l.effects),l.mapped,l.startSelection,Kp)):i=iU(i,i.length,s.minDepth,t),new ny(i,Kp,n,r)}addSelection(t,n,r,s){let a=this.done.length?this.done[this.done.length-1].selectionsAfter:Kp;return a.length>0&&n-this.prevTime<s&&r==this.prevUserEvent&&r&&/^select($|\.)/.test(r)&&RHn(a[a.length-1],t)?this:new ny($Ot(this.done,t),this.undone,n,r)}addMapping(t){return new ny(Ote(this.done,t),Ote(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:zve.of({side:t,rest:$Hn(s),selection:i}),userEvent:t==0?"select.undo":"select.redo",scrollIntoView:!0});if(a.changes){let l=s.length==1?Kp:s.slice(0,s.length-1);return a.mapped&&(l=Ote(l,a.mapped)),n.update({changes:a.changes,selection:a.startSelection,effects:a.effects,annotations:zve.of({side:t,rest:l,selection:i}),filter:!1,userEvent:t==0?"undo":"redo",scrollIntoView:!0})}else return null}}ny.empty=new ny(Kp,Kp);const LHn=[{key:"Mod-z",run:ROt,preventDefault:!0},{key:"Mod-y",mac:"Mod-Shift-z",run:Bve,preventDefault:!0},{linux:"Ctrl-Shift-z",run:Bve,preventDefault:!0},{key:"Mod-u",run:NHn,preventDefault:!0},{key:"Alt-u",mac:"Mod-Shift-u",run:IHn,preventDefault:!0}];function PI(e,t){return St.create(e.ranges.map(t),e.mainIndex)}function Xg(e,t){return e.update({selection:t,scrollIntoView:!0,userEvent:"select"})}function Jg({state:e,dispatch:t},n){let r=PI(e.selection,n);return r.eq(e.selection,!0)?!1:(t(Xg(e,r)),!0)}function SW(e,t){return St.cursor(t?e.to:e.from)}function MOt(e,t){return Jg(e,n=>n.empty?e.moveByChar(n,t):SW(n,t))}function ad(e){return e.textDirectionAt(e.state.selection.main.head)==Oi.LTR}const DOt=e=>MOt(e,!ad(e)),LOt=e=>MOt(e,ad(e));function FOt(e,t){return Jg(e,n=>n.empty?e.moveByGroup(n,t):SW(n,t))}const FHn=e=>FOt(e,!ad(e)),zHn=e=>FOt(e,ad(e));function BHn(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 kW(e,t,n){let r=vi(e).resolveInner(t.head),s=n?Mr.closedBy:Mr.openedBy;for(let c=t.head;;){let u=n?r.childAfter(c):r.childBefore(c);if(!u)break;BHn(e,u,s)?r=u:c=n?u.to:u.from}let a=r.type.prop(s),i,l;return a&&(i=n?ty(e,r.from,1):ty(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 UHn=e=>Jg(e,t=>kW(e.state,t,!ad(e))),qHn=e=>Jg(e,t=>kW(e.state,t,ad(e)));function zOt(e,t){return Jg(e,n=>{if(!n.empty)return SW(n,t);let r=e.moveVertically(n,t);return r.head!=n.head?r:e.moveToLineBoundary(n,t)})}const BOt=e=>zOt(e,!1),UOt=e=>zOt(e,!0);function qOt(e){let t=e.scrollDOM.clientHeight<e.scrollDOM.scrollHeight-2,n=0,r=0,s;if(t){for(let a of e.state.facet(At.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 VOt(e,t){let n=qOt(e),{state:r}=e,s=PI(r.selection,i=>i.empty?e.moveVertically(i,t,n.height):SW(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=At.scrollIntoView(s.main.head,{y:"start",yMargin:i.top-c}))}return e.dispatch(Xg(r,s),{effects:a}),!0}const t7e=e=>VOt(e,!1),Uve=e=>VOt(e,!0);function p1(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 VHn=e=>Jg(e,t=>p1(e,t,!0)),HHn=e=>Jg(e,t=>p1(e,t,!1)),WHn=e=>Jg(e,t=>p1(e,t,!ad(e))),ZHn=e=>Jg(e,t=>p1(e,t,ad(e))),GHn=e=>Jg(e,t=>St.cursor(e.lineBlockAt(t.head).from,1)),QHn=e=>Jg(e,t=>St.cursor(e.lineBlockAt(t.head).to,-1));function YHn(e,t,n){let r=!1,s=PI(e.selection,a=>{let i=ty(e,a.head,-1)||ty(e,a.head,1)||a.head>0&&ty(e,a.head-1,1)||a.head<e.doc.length&&ty(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(Xg(e,s)),!0):!1}const KHn=({state:e,dispatch:t})=>YHn(e,t);function Mm(e,t,n){let r=PI(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(Xg(e.state,r)),!0)}function HOt(e,t){return Mm(e,t,n=>e.moveByChar(n,t))}const WOt=e=>HOt(e,!ad(e)),ZOt=e=>HOt(e,ad(e));function GOt(e,t){return Mm(e,t,n=>e.moveByGroup(n,t))}const XHn=e=>GOt(e,!ad(e)),JHn=e=>GOt(e,ad(e)),eWn=e=>{let t=!ad(e);return Mm(e,t,n=>kW(e.state,n,t))},tWn=e=>{let t=ad(e);return Mm(e,t,n=>kW(e.state,n,t))};function QOt(e,t){return Mm(e,t,n=>e.moveVertically(n,t))}const YOt=e=>QOt(e,!1),KOt=e=>QOt(e,!0);function XOt(e,t){return Mm(e,t,n=>e.moveVertically(n,t,qOt(e).height))}const n7e=e=>XOt(e,!1),r7e=e=>XOt(e,!0),nWn=e=>Mm(e,!0,t=>p1(e,t,!0)),rWn=e=>Mm(e,!1,t=>p1(e,t,!1)),sWn=e=>{let t=!ad(e);return Mm(e,t,n=>p1(e,n,t))},aWn=e=>{let t=ad(e);return Mm(e,t,n=>p1(e,n,t))},iWn=e=>Mm(e,!1,t=>St.cursor(e.lineBlockAt(t.head).from)),oWn=e=>Mm(e,!0,t=>St.cursor(e.lineBlockAt(t.head).to)),s7e=({state:e,dispatch:t})=>(t(Xg(e,{anchor:0})),!0),a7e=({state:e,dispatch:t})=>(t(Xg(e,{anchor:e.doc.length})),!0),i7e=({state:e,dispatch:t})=>(t(Xg(e,{anchor:e.selection.main.anchor,head:0})),!0),o7e=({state:e,dispatch:t})=>(t(Xg(e,{anchor:e.selection.main.anchor,head:e.doc.length})),!0),lWn=({state:e,dispatch:t})=>(t(e.update({selection:{anchor:0,head:e.doc.length},userEvent:"select"})),!0),cWn=({state:e,dispatch:t})=>{let n=OW(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},uWn=({state:e,dispatch:t})=>{let n=PI(e.selection,r=>{let s=vi(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(Xg(e,n)),!0)};function JOt(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(Xg(n,St.create(s,s.length-1))),!0)}const dWn=e=>JOt(e,!1),fWn=e=>JOt(e,!0),hWn=({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(Xg(e,r)),!0):!1};function cL(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"?At.announce.of(r.phrase("Selection deleted")):void 0})),!0)}function jF(e,t,n){if(e instanceof At)for(let r of e.state.facet(At.atomicRanges).map(s=>s(e)))r.between(t,t,(s,a)=>{s<t&&a>t&&(t=n?a:s)});return t}const eCt=(e,t,n)=>cL(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=Ug(l,a.tabSize),d=u%sC(a)||sC(a);for(let f=0;f<d&&l[l.length-1-f]==" ";f++)s--;c=s}else c=Tc(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=Tc(i.text,c-i.from,!1,!1)+i.from);return c}),qve=e=>eCt(e,!1,!0),tCt=e=>eCt(e,!0,!1),nCt=(e,t)=>cL(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=Tc(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}),rCt=e=>nCt(e,!1),pWn=e=>nCt(e,!0),mWn=e=>cL(e,t=>{let n=e.lineBlockAt(t.head).to;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),gWn=e=>cL(e,t=>{let n=e.moveToLineBoundary(t,!1).head;return t.head>n?n:Math.max(0,t.head-1)}),vWn=e=>cL(e,t=>{let n=e.moveToLineBoundary(t,!0).head;return t.head<n?n:Math.min(e.state.doc.length,t.head+1)}),yWn=({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},bWn=({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:Tc(a.text,s-a.from,!1)+a.from,l=s==a.to?s+1:Tc(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 OW(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 sCt(e,t,n){if(e.readOnly)return!1;let r=[],s=[];for(let a of OW(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 xWn=({state:e,dispatch:t})=>sCt(e,t,!1),wWn=({state:e,dispatch:t})=>sCt(e,t,!0);function aCt(e,t,n){if(e.readOnly)return!1;let r=[];for(let a of OW(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 SWn=({state:e,dispatch:t})=>aCt(e,t,!1),kWn=({state:e,dispatch:t})=>aCt(e,t,!0),OWn=e=>{if(e.state.readOnly)return!1;let{state:t}=e,n=t.changes(OW(t).map(({from:s,to:a})=>(s>0?s--:a<t.doc.length&&a++,{from:s,to:a}))),r=PI(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 CWn(e,t){if(/\(\)|\[\]|\{\}/.test(e.sliceDoc(t-1,t+1)))return{from:t,to:t};let n=vi(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(Mr.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 l7e=iCt(!1),_Wn=iCt(!0);function iCt(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&&CWn(t,a);e&&(a=i=(i<=l.to?l:t.doc.lineAt(i)).to);let u=new vW(t,{simulateBreak:a,simulateDoubleBreak:!!c}),d=uOe(u,a);for(d==null&&(d=Ug(/^\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=["",M2(t,d)];return c&&f.push(M2(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 qOe(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 EWn=({state:e,dispatch:t})=>{if(e.readOnly)return!1;let n=Object.create(null),r=new vW(e,{overrideIndentation:a=>{let i=n[a];return i??-1}}),s=qOe(e,(a,i,l)=>{let c=uOe(r,a.from);if(c==null)return;/\S/.test(a.text)||(c=0);let u=/^\s*/.exec(a.text)[0],d=M2(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},oCt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(qOe(e,(n,r)=>{r.push({from:n.from,insert:e.facet(II)})}),{userEvent:"input.indent"})),!0),lCt=({state:e,dispatch:t})=>e.readOnly?!1:(t(e.update(qOe(e,(n,r)=>{let s=/^\s*/.exec(n.text)[0];if(!s)return;let a=Ug(s,e.tabSize),i=0,l=M2(e,Math.max(0,a-sC(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),TWn=e=>(e.setTabFocusMode(),!0),jWn=[{key:"Ctrl-b",run:DOt,shift:WOt,preventDefault:!0},{key:"Ctrl-f",run:LOt,shift:ZOt},{key:"Ctrl-p",run:BOt,shift:YOt},{key:"Ctrl-n",run:UOt,shift:KOt},{key:"Ctrl-a",run:GHn,shift:iWn},{key:"Ctrl-e",run:QHn,shift:oWn},{key:"Ctrl-d",run:tCt},{key:"Ctrl-h",run:qve},{key:"Ctrl-k",run:mWn},{key:"Ctrl-Alt-h",run:rCt},{key:"Ctrl-o",run:yWn},{key:"Ctrl-t",run:bWn},{key:"Ctrl-v",run:Uve}],NWn=[{key:"ArrowLeft",run:DOt,shift:WOt,preventDefault:!0},{key:"Mod-ArrowLeft",mac:"Alt-ArrowLeft",run:FHn,shift:XHn,preventDefault:!0},{mac:"Cmd-ArrowLeft",run:WHn,shift:sWn,preventDefault:!0},{key:"ArrowRight",run:LOt,shift:ZOt,preventDefault:!0},{key:"Mod-ArrowRight",mac:"Alt-ArrowRight",run:zHn,shift:JHn,preventDefault:!0},{mac:"Cmd-ArrowRight",run:ZHn,shift:aWn,preventDefault:!0},{key:"ArrowUp",run:BOt,shift:YOt,preventDefault:!0},{mac:"Cmd-ArrowUp",run:s7e,shift:i7e},{mac:"Ctrl-ArrowUp",run:t7e,shift:n7e},{key:"ArrowDown",run:UOt,shift:KOt,preventDefault:!0},{mac:"Cmd-ArrowDown",run:a7e,shift:o7e},{mac:"Ctrl-ArrowDown",run:Uve,shift:r7e},{key:"PageUp",run:t7e,shift:n7e},{key:"PageDown",run:Uve,shift:r7e},{key:"Home",run:HHn,shift:rWn,preventDefault:!0},{key:"Mod-Home",run:s7e,shift:i7e},{key:"End",run:VHn,shift:nWn,preventDefault:!0},{key:"Mod-End",run:a7e,shift:o7e},{key:"Enter",run:l7e,shift:l7e},{key:"Mod-a",run:lWn},{key:"Backspace",run:qve,shift:qve,preventDefault:!0},{key:"Delete",run:tCt,preventDefault:!0},{key:"Mod-Backspace",mac:"Alt-Backspace",run:rCt,preventDefault:!0},{key:"Mod-Delete",mac:"Alt-Delete",run:pWn,preventDefault:!0},{mac:"Mod-Backspace",run:gWn,preventDefault:!0},{mac:"Mod-Delete",run:vWn,preventDefault:!0}].concat(jWn.map(e=>({mac:e.key,run:e.run,shift:e.shift}))),IWn=[{key:"Alt-ArrowLeft",mac:"Ctrl-ArrowLeft",run:UHn,shift:eWn},{key:"Alt-ArrowRight",mac:"Ctrl-ArrowRight",run:qHn,shift:tWn},{key:"Alt-ArrowUp",run:xWn},{key:"Shift-Alt-ArrowUp",run:SWn},{key:"Alt-ArrowDown",run:wWn},{key:"Shift-Alt-ArrowDown",run:kWn},{key:"Mod-Alt-ArrowUp",run:dWn},{key:"Mod-Alt-ArrowDown",run:fWn},{key:"Escape",run:hWn},{key:"Mod-Enter",run:_Wn},{key:"Alt-l",mac:"Ctrl-l",run:cWn},{key:"Mod-i",run:uWn,preventDefault:!0},{key:"Mod-[",run:lCt},{key:"Mod-]",run:oCt},{key:"Mod-Alt-\\",run:EWn},{key:"Shift-Mod-k",run:OWn},{key:"Shift-Mod-\\",run:KHn},{key:"Mod-/",run:xHn},{key:"Alt-A",run:SHn},{key:"Ctrl-m",mac:"Shift-Alt-m",run:TWn}].concat(NWn),AWn={key:"Tab",run:oCt,shift:lCt},c7e=typeof String.prototype.normalize=="function"?e=>e.normalize("NFKD"):e=>e;class Fx{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(c7e(l)):c7e,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 bf(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=Hke(t),r=this.bufferStart+this.bufferPos;this.bufferPos+=Vv(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"&&(Fx.prototype[Symbol.iterator]=function(){return this});const cCt={from:-1,to:-1,match:/.*/.exec(""),precise:!0},VOe="gm"+(/x/.unicode==null?"":"u");class uCt{constructor(t,n,r,s=0,a=t.length){if(this.text=t,this.to=a,this.curLine="",this.done=!1,this.value=cCt,/\\[sWDnr]|\n|\r|\[\^/.test(n))return new dCt(t,n,r,s,a);this.re=new RegExp(n,VOe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.iter=t.iter();let i=t.lineAt(s);this.curLineStart=i.from,this.matchPos=oU(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=oU(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 Cte=new WeakMap;class vj{constructor(t,n){this.from=t,this.text=n}get to(){return this.from+this.text.length}static get(t,n,r){let s=Cte.get(t);if(!s||s.from>=r||s.to<=n){let l=new vj(n,t.sliceString(n,r));return Cte.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)),Cte.set(t,new vj(i,a)),new vj(n,a.slice(n-i,r-i))}}class dCt{constructor(t,n,r,s,a){this.text=t,this.to=a,this.done=!1,this.value=cCt,this.matchPos=oU(t,s),this.re=new RegExp(n,VOe+(r?.ignoreCase?"i":"")),this.test=r?.test,this.flat=vj.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=oU(this.text,s+(r==s?1:0)),this}if(this.flat.to==this.to)return this.done=!0,this;this.flat=vj.get(this.text,this.flat.from,this.chunkEnd(this.flat.from+this.flat.text.length*2))}}}typeof Symbol<"u"&&(uCt.prototype[Symbol.iterator]=dCt.prototype[Symbol.iterator]=function(){return this});function RWn(e){try{return new RegExp(e,VOe),!0}catch{return!1}}function oU(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 PWn=e=>{let{state:t}=e,n=String(t.doc.lineAt(e.state.selection.main.head).number),{close:r,result:s}=g7n(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,At.scrollIntoView(v.from,{y:"center"})],selection:v})}),!0},$Wn={highlightWordAroundCursor:!1,minSelectionLength:1,maxMatches:100,wholeWords:!1},MWn=kn.define({combine(e){return qy(e,$Wn,{highlightWordAroundCursor:(t,n)=>t||n,minSelectionLength:Math.min,maxMatches:Math.min})}});function DWn(e){return[UWn,BWn]}const LWn=Tn.mark({class:"cm-selectionMatch"}),FWn=Tn.mark({class:"cm-selectionMatch cm-selectionMatch-main"});function u7e(e,t,n,r){return(n==0||e(t.sliceDoc(n-1,n))!=bo.Word)&&(r==t.doc.length||e(t.sliceDoc(r,r+1))!=bo.Word)}function zWn(e,t,n,r){return e(t.sliceDoc(n,n+1))==bo.Word&&e(t.sliceDoc(r-1,r))==bo.Word}const BWn=So.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(MWn),{state:n}=e,r=n.selection;if(r.ranges.length>1)return Tn.none;let s=r.main,a,i=null;if(s.empty){if(!t.highlightWordAroundCursor)return Tn.none;let c=n.wordAt(s.head);if(!c)return Tn.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 Tn.none;if(t.wholeWords){if(a=n.sliceDoc(s.from,s.to),i=n.charCategorizer(s.head),!(u7e(i,n,s.from,s.to)&&zWn(i,n,s.from,s.to)))return Tn.none}else if(a=n.sliceDoc(s.from,s.to),!a)return Tn.none}let l=[];for(let c of e.visibleRanges){let u=new Fx(n.doc,a,c.from,c.to);for(;!u.next().done;){let{from:d,to:f}=u.value;if((!i||u7e(i,n,d,f))&&(s.empty&&d<=s.from&&f>=s.to?l.push(FWn.range(d,f)):(d>=s.to||f<=s.from)&&l.push(LWn.range(d,f)),l.length>t.maxMatches))return Tn.none}}return Tn.set(l)}},{decorations:e=>e.decorations}),UWn=At.baseTheme({".cm-selectionMatch":{backgroundColor:"#99ff7780"},".cm-searchMatch .cm-selectionMatch":{backgroundColor:"transparent"}}),qWn=({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 VWn(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 Fx(e.doc,t,r[r.length-1].to);;)if(l.next(),l.done){if(i)return null;l=new Fx(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 HWn=({state:e,dispatch:t})=>{let{ranges:n}=e.selection;if(n.some(a=>a.from===a.to))return qWn({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=VWn(e,r);return s?(t(e.update({selection:e.selection.addRange(St.range(s.from,s.to),!1),effects:At.scrollIntoView(s.to)})),!0):!1},$I=kn.define({combine(e){return qy(e,{top:!1,caseSensitive:!1,literal:!1,regexp:!1,wholeWord:!1,createPanel:t=>new aZn(t),scrollToMatch:t=>At.scrollIntoView(t)})}});class fCt{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||RWn(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 KWn(this):new GWn(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?uT(this,s,n,r):cT(this,s,n,r)}}class hCt{constructor(t){this.spec=t}}function WWn(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 cT(e,t,n,r){let s;return e.wholeWord&&(s=ZWn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=WWn(e.test,t,s)),new Fx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function ZWn(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(lU(s,n-a))!=bo.Word||t(cU(s,n-a))!=bo.Word)&&(t(cU(s,r-a))!=bo.Word||t(lU(s,r-a))!=bo.Word))}class GWn extends hCt{constructor(t){super(t)}nextMatch(t,n,r){let s=cT(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=cT(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=cT(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=cT(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=cT(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 QWn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function uT(e,t,n,r){let s;return e.wholeWord&&(s=YWn(t.charCategorizer(t.selection.main.head))),e.test&&(s=QWn(e.test,t,s)),new uCt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function lU(e,t){return e.slice(Tc(e,t,!1),t)}function cU(e,t){return e.slice(t,Tc(e,t))}function YWn(e){return(t,n,r)=>!r[0].length||(e(lU(r.input,r.index))!=bo.Word||e(cU(r.input,r.index))!=bo.Word)&&(e(cU(r.input,r.index+r[0].length))!=bo.Word||e(lU(r.input,r.index+r[0].length))!=bo.Word)}class KWn extends hCt{nextMatch(t,n,r){let s=uT(this.spec,t,r,t.doc.length).next();return s.done&&(s=uT(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=uT(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=uT(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=uT(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 H2=hr.define(),HOe=hr.define(),Jw=bl.define({create(e){return new _te(Vve(e).create(),null)},update(e,t){for(let n of t.effects)n.is(H2)?e=new _te(n.value.create(),e.panel):n.is(HOe)&&(e=new _te(e.query,n.value?WOe:null));return e},provide:e=>$2.from(e,t=>t.panel)});class _te{constructor(t,n){this.query=t,this.panel=n}}const XWn=Tn.mark({class:"cm-searchMatch"}),JWn=Tn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),eZn=So.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Jw))}update(e){let t=e.state.field(Jw);(t!=e.startState.field(Jw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Tn.none;let{view:n}=this,r=new td;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?JWn:XWn)})}return r.finish()}},{decorations:e=>e.decorations});function uL(e){return t=>{let n=t.state.field(Jw,!1);return n&&n.query.spec.valid?e(t,n):gCt(t)}}const uU=uL((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($I);return e.dispatch({selection:s,effects:[ZOe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),mCt(e),!0}),dU=uL((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($I);return e.dispatch({selection:a,effects:[ZOe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),mCt(e),!0}),tZn=uL((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)}),nZn=({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 Fx(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},d7e=uL((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(At.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(ZOe(e,i)),d.push(n.facet($I).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),rZn=uL((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:At.announce.of(r),userEvent:"input.replace.all"}),!0});function WOe(e){return e.state.facet($I).createPanel(e)}function Vve(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($I);return new fCt({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 pCt(e){let t=lOe(e,WOe);return t&&t.dom.querySelector("[main-field]")}function mCt(e){let t=pCt(e);t&&t==e.root.activeElement&&t.select()}const gCt=e=>{let t=e.state.field(Jw,!1);if(t&&t.panel){let n=pCt(e);if(n&&n!=e.root.activeElement){let r=Vve(e.state,t.query.spec);r.valid&&e.dispatch({effects:H2.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[HOe.of(!0),t?H2.of(Vve(e.state,t.query.spec)):hr.appendConfig.of(oZn)]});return!0},vCt=e=>{let t=e.state.field(Jw,!1);if(!t||!t.panel)return!1;let n=lOe(e,WOe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:HOe.of(!1)}),!0},sZn=[{key:"Mod-f",run:gCt,scope:"editor search-panel"},{key:"F3",run:uU,shift:dU,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:uU,shift:dU,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:vCt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:nZn},{key:"Mod-Alt-g",run:PWn},{key:"Mod-d",run:HWn,preventDefault:!0}];class aZn{constructor(t){this.view=t;let n=this.query=t.state.field(Jw).query.spec;this.commit=this.commit.bind(this),this.searchField=fi("input",{value:n.search,placeholder:ph(t,"Find"),"aria-label":ph(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=fi("input",{value:n.replace,placeholder:ph(t,"Replace"),"aria-label":ph(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=fi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=fi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=fi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return fi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=fi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>uU(t),[ph(t,"next")]),r("prev",()=>dU(t),[ph(t,"previous")]),r("select",()=>tZn(t),[ph(t,"all")]),fi("label",null,[this.caseField,ph(t,"match case")]),fi("label",null,[this.reField,ph(t,"regexp")]),fi("label",null,[this.wordField,ph(t,"by word")]),...t.state.readOnly?[]:[fi("br"),this.replaceField,r("replace",()=>d7e(t),[ph(t,"replace")]),r("replaceAll",()=>rZn(t),[ph(t,"replace all")])],fi("button",{name:"close",onclick:()=>vCt(t),"aria-label":ph(t,"close"),type:"button"},["×"])])}commit(){let t=new fCt({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:H2.of(t)}))}keydown(t){_9n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?dU:uU)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),d7e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(H2)&&!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($I).top}}function ph(e,t){return e.state.phrase(t)}const NF=30,IF=/[\s\.,:;?!]/;function ZOe(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-NF),i=Math.min(s,n+NF),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<NF;c++)if(!IF.test(l[c+1])&&IF.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-NF;c--)if(!IF.test(l[c-1])&&IF.test(l[c])){l=l.slice(0,c);break}}return At.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const iZn=At.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"}}),oZn=[Jw,ip.low(eZn),iZn];class f7e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Lk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(W2).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new td,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=xZn(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,Tn.widget({widget:new gZn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(h,p,Tn.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 Lk(u,n,cN(u))}}function cN(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 f7e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new f7e(r.from,a,r.diagnostic)}}),r}function lZn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(W2).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(yCt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function cZn(e,t){return e.field(Ph,!1)?t:t.concat(hr.appendConfig.of(wZn))}const yCt=hr.define(),GOe=hr.define(),bCt=hr.define(),Ph=bl.define({create(){return new Lk(Tn.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=cN(n,e.selected.diagnostic,a)||cN(n,null,a)}!n.size&&s&&t.state.facet(W2).autoPanel&&(s=null),e=new Lk(n,s,r)}for(let n of t.effects)if(n.is(yCt)){let r=t.state.facet(W2).autoPanel?n.value.length?Z2.open:null:e.panel;e=Lk.init(n.value,r,t.state)}else n.is(GOe)?e=new Lk(e.diagnostics,n.value?Z2.open:null,e.selected):n.is(bCt)&&(e=new Lk(e.diagnostics,e.panel,n.value));return e},provide:e=>[$2.from(e,t=>t.panel),At.decorations.from(e,t=>t.diagnostics)]}),uZn=Tn.mark({class:"cm-lintRange cm-lintRange-active"});function dZn(e,t,n){let{diagnostics:r}=e.state.field(Ph),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(W2).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:fZn(e,s)}}}:null}function fZn(e,t){return fi("ul",{class:"cm-tooltip-lint"},t.map(n=>wCt(e,n,!1)))}const hZn=e=>{let t=e.state.field(Ph,!1);(!t||!t.panel)&&e.dispatch({effects:cZn(e.state,[GOe.of(!0)])});let n=lOe(e,Z2.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},h7e=e=>{let t=e.state.field(Ph,!1);return!t||!t.panel?!1:(e.dispatch({effects:GOe.of(!1)}),!0)},pZn=e=>{let t=e.state.field(Ph,!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)},mZn=[{key:"Mod-Shift-m",run:hZn,preventDefault:!0},{key:"F8",run:pZn}],W2=kn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...qy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:p7e,tooltipFilter:p7e,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 p7e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function xCt(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 wCt(e,t,n){var r;let s=n?xCt(t.actions):[];return fi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},fi("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=cN(e.state.field(Ph).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),fi("u",u.slice(d,d+1)),u.slice(d+1)],h=a.markClass?" "+a.markClass:"";return fi("button",{type:"button",class:"cm-diagnosticAction"+h,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&fi("div",{class:"cm-diagnosticSource"},t.source))}class gZn extends op{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return fi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class m7e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=wCt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class Z2{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)h7e(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=xCt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=cN(this.view.state.field(Ph).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=fi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=fi("div",{class:"cm-panel-lint"},this.list,fi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>h7e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ph).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(Ph),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 m7e(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 m7e(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(Ph),r=cN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:bCt.of(r)})}static open(t){return new Z2(t)}}function vZn(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 AF(e){return vZn(`<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 yZn=At.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:AF("#d11")},".cm-lintRange-warning":{backgroundImage:AF("orange")},".cm-lintRange-info":{backgroundImage:AF("#999")},".cm-lintRange-hint":{backgroundImage:AF("#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 bZn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function xZn(e){let t="hint",n=1;for(let r of e){let s=bZn(r.severity);s>n&&(n=s,t=r.severity)}return t}const wZn=[Ph,At.decorations.compute([Ph],e=>{let{selected:t,panel:n}=e.field(Ph);return!t||!n||t.from==t.to?Tn.none:Tn.set([uZn.range(t.from,t.to)])}),p7n(dZn,{hideOn:lZn}),yZn];var g7e=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(uUn)),t.defaultKeymap!==!1&&(a=a.concat(IWn)),t.searchKeymap!==!1&&(a=a.concat(sZn)),t.historyKeymap!==!1&&(a=a.concat(LHn)),t.foldKeymap!==!1&&(a=a.concat(Q7n)),t.completionKeymap!==!1&&(a=a.concat(mkt)),t.lintKeymap!==!1&&(a=a.concat(mZn));var i=[];return t.lineNumbers!==!1&&i.push(M1t()),t.highlightActiveLineGutter!==!1&&i.push(T7n()),t.highlightSpecialChars!==!1&&i.push(U9n()),t.history!==!1&&i.push(jHn()),t.foldGutter!==!1&&i.push(J7n()),t.drawSelection!==!1&&i.push(A9n()),t.dropCursor!==!1&&i.push(D9n()),t.allowMultipleSelections!==!1&&i.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(B7n()),t.syntaxHighlighting!==!1&&i.push(h1(rBn,{fallback:!0})),t.bracketMatching!==!1&&i.push(uBn()),t.closeBrackets!==!1&&i.push(iUn()),t.autocompletion!==!1&&i.push(pkt()),t.rectangularSelection!==!1&&i.push(n7n()),s!==!1&&i.push(a7n()),t.highlightActiveLine!==!1&&i.push(G9n()),t.highlightSelectionMatches!==!1&&i.push(DWn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(II.of(" ".repeat(t.tabSize))),i.concat([NI.of(a.flat())]).filter(Boolean)};const SZn="#e5c07b",v7e="#e06c75",kZn="#56b6c2",OZn="#ffffff",c9="#abb2bf",Hve="#7d8799",CZn="#61afef",_Zn="#98c379",y7e="#d19a66",EZn="#c678dd",TZn="#21252b",b7e="#2c313a",x7e="#282c34",Ete="#353a42",jZn="#3E4451",w7e="#528bff",NZn=At.theme({"&":{color:c9,backgroundColor:x7e},".cm-content":{caretColor:w7e},".cm-cursor, .cm-dropCursor":{borderLeftColor:w7e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:jZn},".cm-panels":{backgroundColor:TZn,color:c9},".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:x7e,color:Hve,border:"none"},".cm-activeLineGutter":{backgroundColor:b7e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Ete},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Ete,borderBottomColor:Ete},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:b7e,color:c9}}},{dark:!0}),IZn=Kg.define([{tag:fe.keyword,color:EZn},{tag:[fe.name,fe.deleted,fe.character,fe.propertyName,fe.macroName],color:v7e},{tag:[fe.function(fe.variableName),fe.labelName],color:CZn},{tag:[fe.color,fe.constant(fe.name),fe.standard(fe.name)],color:y7e},{tag:[fe.definition(fe.name),fe.separator],color:c9},{tag:[fe.typeName,fe.className,fe.number,fe.changed,fe.annotation,fe.modifier,fe.self,fe.namespace],color:SZn},{tag:[fe.operator,fe.operatorKeyword,fe.url,fe.escape,fe.regexp,fe.link,fe.special(fe.string)],color:kZn},{tag:[fe.meta,fe.comment],color:Hve},{tag:fe.strong,fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.link,color:Hve,textDecoration:"underline"},{tag:fe.heading,fontWeight:"bold",color:v7e},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:y7e},{tag:[fe.processingInstruction,fe.string,fe.inserted],color:_Zn},{tag:fe.invalid,color:OZn}]),AZn=[NZn,h1(IZn)];var RZn=At.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),PZn=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(NI.of([AWn])),m&&(typeof m=="boolean"?v.unshift(g7e()):v.unshift(g7e(m))),h&&v.unshift(X9n(h)),d){case"light":v.push(RZn);break;case"dark":v.push(AZn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(At.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},$Zn=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 MZn{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 S7e{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 Tte=null,DZn=()=>typeof window>"u"?new S7e:(Tte||(Tte=new S7e),Tte),LZn=At.theme({"& .cm-scroller":{height:"100% !important"}}),k7e=null,jte=null;function FZn(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===k7e||(k7e=i,jte=At.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),jte}var O7e=Uy.define(),zZn=200,BZn=[];function UZn(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?BZn: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,E=_===void 0?null:_,T=e.placeholder,N=T===void 0?"":T,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,M=e.indentWithTab,B=M===void 0?!0:M,V=e.basicSetup,q=V===void 0?!0:V,F=e.root,H=e.initialState,D=g.useState(),G=D[0],z=D[1],$=g.useState(),U=$[0],W=$[1],Y=g.useState(),te=Y[0],ee=Y[1],J=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],le=FZn(p,v,b,w,O,E),X=At.updateListener.of(de=>{if(de.docChanged&&typeof r=="function"&&!de.transactions.some(he=>he.annotation(O7e))){J.current?J.current.reset():(J.current=new MZn(()=>{if(re.current){var he=re.current;re.current=null,he()}J.current=null},zZn),DZn().add(J.current));var ue=de.state.doc,ye=ue.toString();r(ye,de)}s&&s($Zn(de))}),ne=PZn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:B,basicSetup:q}),se=[X,...le?[le]:[],LZn,...ne];return i&&typeof i=="function"&&se.push(At.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!te){var de={doc:t,selection:n,extensions:se},ue=H?gs.fromJSON(H.json,de,H.fields):gs.create(de);if(ee(ue),!U){var ye=new At({state:ue,parent:G,root:F});W(ye),a&&a(ye,ue)}}return()=>{U&&(ee(void 0),W(void 0))}},[G,te]),g.useEffect(()=>{e.container&&z(e.container)},[e.container]),g.useEffect(()=>()=>{U&&(U.destroy(),W(void 0)),J.current&&(J.current.cancel(),J.current=null)},[U]),g.useEffect(()=>{u&&U&&U.focus()},[u,U]),g.useEffect(()=>{U&&U.dispatch({effects:hr.reconfigure.of(se)})},[f,c,p,v,b,w,O,E,N,A,L,B,q,r,i]),g.useEffect(()=>{if(t!==void 0){var de=U?U.state.doc.toString():"";if(U&&t!==de){var ue=J.current&&!J.current.isDone,ye=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[O7e.of(!0)]})};ue?re.current=ye:ye()}}},[t,U]),{state:te,setState:ee,view:U,setView:W,container:G,setContainer:z}}var qZn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],nd=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,E=e.indentWithTab,T=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=jOt(e,qZn),L=g.useRef(null),M=UZn({root:I,value:s,autoFocus:h,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:O,placeholder:_,indentWithTab:E,editable:T,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),B=M.state,V=M.view,q=M.container,F=M.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:B,view:V}),[L,q,B,V]);var H=g.useCallback(G=>{L.current=G,F(G)},[F]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var D=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",oC({ref:H,className:""+D+(n?" "+n:"")},R))});nd.displayName="CodeMirror";const SCt={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 Nte=null;function VZn(){return Nte||(Nte=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([qa(()=>import("./core-XzdCljR7.js"),__vite__mapDeps([0,1,2]),import.meta.url),qa(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[qa(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),qa(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[qa(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),qa(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),qa(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),qa(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),qa(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),qa(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),qa(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),qa(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),qa(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),qa(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),qa(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),qa(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),qa(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),qa(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Nte}async function HZn(e,t){const n=SCt[t?.toLowerCase()];if(!n)return null;const r=await VZn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function WZn(e){const t=e?.split(".").pop()?.toLowerCase();return t?SCt[t]:void 0}function ZZn(e){return new rC(hOe.define(e))}const kCt=[mg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return qa(()=>Promise.resolve().then(()=>TF),void 0,import.meta.url).then(e=>e.javascript())}}),mg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return qa(()=>Promise.resolve().then(()=>SBn),void 0,import.meta.url).then(e=>e.json())}}),mg.of({name:"JSX",extensions:["jsx"],load(){return qa(()=>Promise.resolve().then(()=>TF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),mg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return qa(()=>Promise.resolve().then(()=>gHn),void 0,import.meta.url).then(e=>e.markdown())}}),mg.of({name:"TSX",extensions:["tsx"],load(){return qa(()=>Promise.resolve().then(()=>TF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),mg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return qa(()=>Promise.resolve().then(()=>TF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),mg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return qa(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>ZZn(e.shell))}})];function GZn(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 QZn(e){const t=GZn(e);return pkt({override:[YZn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function YZn(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 KZn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,XZn=Tn.mark({class:"cm-variable-highlight"}),C7e=new E1t({regexp:KZn,decoration:()=>XZn}),JZn=So.fromClass(class{decorations;constructor(e){this.decorations=C7e.createDeco(e)}update(e){this.decorations=C7e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),eGn=JZn;function tGn(){const e=RI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[fe.className,fe.propertyName],color:"var(--neutral6)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:fe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=At.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:"0.7rem",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 nGn(){const e=At.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.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:"0.7rem",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=Kg.define([{tag:[fe.comment,fe.bracket],color:"var(--neutral2)"},{tag:[fe.string,fe.meta,fe.regexp],color:"var(--accent1)"},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:"var(--accent6)"},{tag:[fe.keyword,fe.operator,fe.tagName],color:"var(--accent2)"},{tag:[fe.function(fe.propertyName),fe.propertyName],color:"var(--accent5)"},{tag:[fe.definition(fe.variableName),fe.function(fe.variableName),fe.className,fe.attributeName],color:"var(--accent3)"},{tag:[fe.variableName,fe.number],color:"var(--accent5)"},{tag:[fe.name,fe.quote],color:"var(--accent1)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[fe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:[fe.deleted],color:"var(--accent2)"},{tag:fe.invalid,color:"var(--error)"},{tag:[fe.standard(fe.tagName)],color:"var(--accent1)"}]);return[e,h1(t)]}const o0=()=>{const e=c_().resolvedTheme==="dark";return g.useMemo(()=>e?tGn():nGn(),[e])},rGn=io(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"}}),sGn=ip.highest(At.editorAttributes.of({style:"outline: none"})),aGn=ip.highest(At.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),iGn=[sGn,aGn],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=o0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const w=[...iGn];return f&&w.push(At.lineWrapping),a==="json"?w.push(Uh):a==="markdown"&&w.push(zOe({base:iC,codeLanguages:kCt})),i&&a==="markdown"&&w.push(eGn),c&&a==="markdown"&&w.push(QZn(c)),h===!1&&w.push(gs.readOnly.of(!0)),w},[a,i,c,h,f]);return o.jsxs("div",{className:K(rGn({variant:p}),s),...m,children:[r&&o.jsx(Da,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(nd,{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}})]})}),oGn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},lGn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=o0(),{settings:r,setSettings:s}=YH(),a=r?.tracingOptions,i=g.useMemo(()=>oGn(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(nd,{value:l,onChange:d,theme:n,extensions:[Uh],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(oe,{type:"button",onClick:f,children:"Save"})})]})},cGn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(gn,{children:[o.jsx(fn,{asChild:!0,children:o.jsx(oe,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(Je,{children:o.jsx(nwe,{})})})}),o.jsx(hn,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(fr,{children:"Run Options"}),o.jsx($s,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Pr,{children:o.jsx(lGn,{onSaved:()=>t(!1)})})]})})]})};function uGn({status:e}){switch(e){case"running":return o.jsx(Vt,{});case"failed":return o.jsx(or,{className:"text-accent2"});case"canceled":return o.jsx(ks,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(lS,{className:"text-neutral3"});case"suspended":return o.jsx(FV,{className:"text-accent3"});case"success":return o.jsx(Dr,{className:"text-accent1"});default:return o.jsx(lS,{className:"text-neutral3"})}}function OCt({status:e}){return o.jsxs(gn,{children:[o.jsx(fn,{asChild:!0,children:o.jsx(Je,{"aria-label":e,className:"shrink-0",children:o.jsx(uGn,{status:e})})}),o.jsx(hn,{children:e})]})}var Ite,_7e;function QOe(){if(_7e)return Ite;_7e=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 Ite=r,Ite}var Ate,E7e;function dGn(){return E7e||(E7e=1,Ate="2.2.4"),Ate}var Rte,T7e;function fGn(){return T7e||(T7e=1,Rte={Graph:QOe(),version:dGn()}),Rte}var Pte,j7e;function hGn(){if(j7e)return Pte;j7e=1;var e=QOe();Pte={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 Pte}var $te,N7e;function pGn(){if(N7e)return $te;N7e=1,$te=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 $te}var Mte,I7e;function CCt(){if(I7e)return Mte;I7e=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 Mte=e,Mte}var Dte,A7e;function _Ct(){if(A7e)return Dte;A7e=1;var e=CCt();Dte=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 Dte}var Lte,R7e;function mGn(){if(R7e)return Lte;R7e=1;var e=_Ct();Lte=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Lte}var Fte,P7e;function ECt(){if(P7e)return Fte;P7e=1,Fte=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 Fte}var zte,$7e;function gGn(){if($7e)return zte;$7e=1;var e=ECt();zte=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return zte}var Bte,M7e;function vGn(){if(M7e)return Bte;M7e=1,Bte=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 Bte}var Ute,D7e;function TCt(){if(D7e)return Ute;D7e=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 Ute=e,e.CycleException=t,Ute}var qte,L7e;function yGn(){if(L7e)return qte;L7e=1;var e=TCt();qte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return qte}var Vte,F7e;function jCt(){if(F7e)return Vte;F7e=1,Vte=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 Vte}var Hte,z7e;function bGn(){if(z7e)return Hte;z7e=1;var e=jCt();Hte=t;function t(n,r){return e(n,r,"post")}return Hte}var Wte,B7e;function xGn(){if(B7e)return Wte;B7e=1;var e=jCt();Wte=t;function t(n,r){return e(n,r,"pre")}return Wte}var Zte,U7e;function wGn(){if(U7e)return Zte;U7e=1;var e=QOe(),t=CCt();Zte=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 Zte}var Gte,q7e;function SGn(){return q7e||(q7e=1,Gte={components:pGn(),dijkstra:_Ct(),dijkstraAll:mGn(),findCycles:gGn(),floydWarshall:vGn(),isAcyclic:yGn(),postorder:bGn(),preorder:xGn(),prim:wGn(),tarjan:ECt(),topsort:TCt()}),Gte}var Qte,V7e;function Vg(){if(V7e)return Qte;V7e=1;var e=fGn();return Qte={Graph:e.Graph,json:hGn(),alg:SGn(),version:e.version},Qte}var Yte,H7e;function kGn(){if(H7e)return Yte;H7e=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 Yte=e,Yte}var Kte,W7e;function OGn(){if(W7e)return Kte;W7e=1;let e=Vg().Graph,t=kGn();Kte=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 Kte}var Xte,Z7e;function $l(){if(Z7e)return Xte;Z7e=1;let e=Vg().Graph;Xte={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:E};function t(T,N,I,A){for(var R=A;T.hasNode(R);)R=w(A);return I.dummy=N,T.setNode(R,I),R}function n(T){let N=new e().setGraph(T.graph());return T.nodes().forEach(I=>N.setNode(I,T.node(I))),T.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=T.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(T){let N=new e({multigraph:T.isMultigraph()}).setGraph(T.graph());return T.nodes().forEach(I=>{T.children(I).length||N.setNode(I,T.node(I))}),T.edges().forEach(I=>{N.setEdge(I,T.edge(I))}),N}function s(T){let N=T.nodes().map(I=>{let A={};return T.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function a(T){let N=T.nodes().map(I=>{let A={};return T.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function i(T,N){let I=T.x,A=T.y,R=N.x-I,L=N.y-A,M=T.width/2,B=T.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let V,q;return Math.abs(L)*M>Math.abs(R)*B?(L<0&&(B=-B),V=B*R/L,q=B):(R<0&&(M=-M),V=M,q=M*L/R),{x:I+V,y:A+q}}function l(T){let N=k(m(T)+1).map(()=>[]);return T.nodes().forEach(I=>{let A=T.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(T){let N=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=p(Math.min,N);T.nodes().forEach(A=>{let R=T.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(T){let N=T.nodes().map(M=>T.node(M).rank),I=p(Math.min,N),A=[];T.nodes().forEach(M=>{let B=T.node(M).rank-I;A[B]||(A[B]=[]),A[B].push(M)});let R=0,L=T.graph().nodeRankFactor;Array.from(A).forEach((M,B)=>{M===void 0&&B%L!==0?--R:M!==void 0&&R&&M.forEach(V=>T.node(V).rank+=R)})}function d(T,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(T,"border",R,N)}function f(T,N=h){const I=[];for(let A=0;A<T.length;A+=N){const R=T.slice(A,A+N);I.push(R)}return I}const h=65535;function p(T,N){if(N.length>h){const I=f(N);return T.apply(null,I.map(A=>T.apply(null,A)))}else return T.apply(null,N)}function m(T){const I=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return p(Math.max,I)}function v(T,N){let I={lhs:[],rhs:[]};return T.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(T,N){let I=Date.now();try{return N()}finally{console.log(T+" time: "+(Date.now()-I)+"ms")}}function b(T,N){return N()}let x=0;function w(T){var N=++x;return T+(""+N)}function k(T,N,I=1){N==null&&(N=T,T=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=T;A(L);L+=I)R.push(L);return R}function O(T,N){const I={};for(const A of N)T[A]!==void 0&&(I[A]=T[A]);return I}function _(T,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(T).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(T,N){return T.reduce((I,A,R)=>(I[A]=N[R],I),{})}return Xte}var Jte,G7e;function CGn(){if(G7e)return Jte;G7e=1;let e=OGn(),t=$l().uniqueId;Jte={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 Jte}var ene,Q7e;function _Gn(){if(Q7e)return ene;Q7e=1;let e=$l();ene={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 ene}var tne,Y7e;function fU(){if(Y7e)return tne;Y7e=1;const{applyWithChunking:e}=$l();tne={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 tne}var nne,K7e;function NCt(){if(K7e)return nne;K7e=1;var e=Vg().Graph,t=fU().slack;nne=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 nne}var rne,X7e;function EGn(){if(X7e)return rne;X7e=1;var e=NCt(),t=fU().slack,n=fU().longestPath,r=Vg().alg.preorder,s=Vg().alg.postorder,a=$l().simplify;rne=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,E=!0,T=w.edge(k,_),N=0;return T||(E=!1,T=w.edge(_,k)),N=T.weight,w.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==_){var L=A===E,M=w.edge(I).weight;if(N+=L?M:-M,y(x,k,R)){var B=x.edge(k,R).cutvalue;N+=L?-B:B}}}),N}function d(x,w){arguments.length<2&&(w=x.nodes()[0]),f(x,{},1,w)}function f(x,w,k,O,_){var E=k,T=x.node(O);return w[O]=!0,x.neighbors(O).forEach(N=>{Object.hasOwn(w,N)||(k=f(x,w,k,N,O))}),T.low=E,T.lim=k++,_?T.parent=_:delete T.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 E=x.node(O),T=x.node(_),N=E,I=!1;E.lim>T.lim&&(N=T,I=!0);var A=w.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(w,L)<t(w,R)?L:R)}function m(x,w,k,O){var _=k.v,E=k.w;x.removeEdge(_,E),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 E=x.node(_).parent,T=w.edge(_,E),N=!1;T||(T=w.edge(E,_),N=!0),w.node(_).rank=w.node(E).rank+(N?T.minlen:-T.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 rne}var sne,J7e;function TGn(){if(J7e)return sne;J7e=1;var e=fU(),t=e.longestPath,n=NCt(),r=EGn();sne=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 sne}var ane,eBe;function jGn(){if(eBe)return ane;eBe=1,ane=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 ane}var ine,tBe;function NGn(){if(tBe)return ine;tBe=1;let e=$l();ine={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 ine}var one,nBe;function IGn(){if(nBe)return one;nBe=1;let e=$l();one=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 one}var lne,rBe;function AGn(){if(rBe)return lne;rBe=1,lne={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 lne}var cne,sBe;function RGn(){if(sBe)return cne;sBe=1;let e=$l();cne=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 cne}var une,aBe;function PGn(){if(aBe)return une;aBe=1;let e=$l().zipObject;une=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 une}var dne,iBe;function $Gn(){if(iBe)return dne;iBe=1,dne=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 dne}var fne,oBe;function MGn(){if(oBe)return fne;oBe=1;let e=$l();fne=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 fne}var hne,lBe;function DGn(){if(lBe)return hne;lBe=1;let e=$l();hne=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 hne}var pne,cBe;function LGn(){if(cBe)return pne;cBe=1;let e=$Gn(),t=MGn(),n=DGn();pne=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 pne}var mne,uBe;function FGn(){if(uBe)return mne;uBe=1;let e=Vg().Graph,t=$l();mne=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 mne}var gne,dBe;function zGn(){if(dBe)return gne;dBe=1,gne=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 gne}var vne,fBe;function BGn(){if(fBe)return vne;fBe=1;let e=RGn(),t=PGn(),n=LGn(),r=FGn(),s=zGn(),a=Vg().Graph,i=$l();vne=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 vne}var yne,hBe;function UGn(){if(hBe)return yne;hBe=1;let e=Vg().Graph,t=$l();yne={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,E=0,T=k.length,N=O[O.length-1];return O.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:T;(R||I===N)&&(O.slice(E,A+1).forEach(M=>{y.predecessors(M).forEach(B=>{let V=y.node(B),q=V.order;(q<_||L<q)&&!(V.dummy&&y.node(M).dummy)&&a(x,B,M)})}),E=A+1,_=L)}),O}return b.length&&b.reduce(w),x}function r(y,b){let x={};function w(O,_,E,T,N){let I;t.range(_,E).forEach(A=>{I=O[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<T||L.order>N)&&a(x,R,I)})})}function k(O,_){let E=-1,T,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(T=y.node(R[0]).order,w(_,N,A,E,T),N=A,E=T)}w(_,N,_.length,T,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(E=>{E.forEach((T,N)=>{k[T]=T,O[T]=T,_[T]=N})}),b.forEach(E=>{let T=-1;E.forEach(N=>{let I=w(N);if(I.length){I=I.sort((R,L)=>_[R]-_[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let M=I[R];O[N]===N&&T<_[M]&&!i(x,N,M)&&(O[M]=N,O[N]=k[N]=k[M],T=_[M])}}})}),{root:k,align:O}}function c(y,b,x,w,k){let O={},_=u(y,b,x,k),E=k?"borderLeft":"borderRight";function T(A,R){let L=_.nodes(),M=L.pop(),B={};for(;M;)B[M]?A(M):(B[M]=!0,L.push(M),L=L.concat(R(M))),M=L.pop()}function N(A){O[A]=_.inEdges(A).reduce((R,L)=>Math.max(R,O[L.v]+_.edge(L)),0)}function I(A){let R=_.outEdges(A).reduce((M,B)=>Math.min(M,O[B.w]-_.edge(B)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(O[A]=Math.max(O[A],R))}return T(N,_.predecessors.bind(_)),T(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(E=>{let T;E.forEach(N=>{let I=x[N];if(k.setNode(I),T){var A=x[T],R=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,T),R||0))}T=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(([E,T])=>{let N=v(y,E)/2;k=Math.max(T+N,k),O=Math.min(T-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 E=O+_,T=y[E];if(T===b)return;let N=Object.values(T),I=w-t.applyWithChunking(Math.min,N);_!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[E]=t.mapValues(T,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(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let T=(_==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,T),I=c(y,k,N.root,N.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),w[_+E]=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),E=w.node(O),T=0,N;if(T+=_.width/2,Object.hasOwn(_,"labelpos"))switch(_.labelpos.toLowerCase()){case"l":N=-_.width/2;break;case"r":N=_.width/2;break}if(N&&(T+=x?N:-N),N=0,T+=(_.dummy?b:y)/2,T+=(E.dummy?b:y)/2,T+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":N=E.width/2;break;case"r":N=-E.width/2;break}return N&&(T+=x?N:-N),N=0,T}}function v(y,b){return y.node(b).width}return yne}var bne,pBe;function qGn(){if(pBe)return bne;pBe=1;let e=$l(),t=UGn().positionX;bne=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 bne}var xne,mBe;function VGn(){if(mBe)return xne;mBe=1;let e=CGn(),t=_Gn(),n=TGn(),r=$l().normalizeRanks,s=jGn(),a=$l().removeEmptyRanks,i=NGn(),l=IGn(),c=AGn(),u=BGn(),d=qGn(),f=$l(),h=Vg().Graph;xne=p;function p($,U){let W=U&&U.debugTiming?f.time:f.notime;W("layout",()=>{let Y=W(" buildLayoutGraph",()=>T($));W(" runLayout",()=>m(Y,W,U)),W(" updateInputGraph",()=>v($,Y))})}function m($,U,W){U(" makeSpaceForEdgeLabels",()=>N($)),U(" removeSelfEdges",()=>F($)),U(" acyclic",()=>e.run($)),U(" nestingGraph.run",()=>i.run($)),U(" rank",()=>n(f.asNonCompoundGraph($))),U(" injectEdgeLabelProxies",()=>I($)),U(" removeEmptyRanks",()=>a($)),U(" nestingGraph.cleanup",()=>i.cleanup($)),U(" normalizeRanks",()=>r($)),U(" assignRankMinMax",()=>A($)),U(" removeEdgeLabelProxies",()=>R($)),U(" normalize.run",()=>t.run($)),U(" parentDummyChains",()=>s($)),U(" addBorderSegments",()=>l($)),U(" order",()=>u($,W)),U(" insertSelfEdges",()=>H($)),U(" adjustCoordinateSystem",()=>c.adjust($)),U(" position",()=>d($)),U(" positionSelfEdges",()=>D($)),U(" removeBorderNodes",()=>q($)),U(" normalize.undo",()=>t.undo($)),U(" fixupEdgeLabelCoords",()=>B($)),U(" undoCoordinateSystem",()=>c.undo($)),U(" translateGraph",()=>L($)),U(" assignNodeIntersects",()=>M($)),U(" reversePoints",()=>V($)),U(" acyclic.undo",()=>e.undo($))}function v($,U){$.nodes().forEach(W=>{let Y=$.node(W),te=U.node(W);Y&&(Y.x=te.x,Y.y=te.y,Y.rank=te.rank,U.children(W).length&&(Y.width=te.width,Y.height=te.height))}),$.edges().forEach(W=>{let Y=$.edge(W),te=U.edge(W);Y.points=te.points,Object.hasOwn(te,"x")&&(Y.x=te.x,Y.y=te.y)}),$.graph().width=U.graph().width,$.graph().height=U.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"},E=["labelpos"];function T($){let U=new h({multigraph:!0,compound:!0}),W=z($.graph());return U.setGraph(Object.assign({},b,G(W,y),f.pick(W,x))),$.nodes().forEach(Y=>{let te=z($.node(Y));const ee=G(te,w);Object.keys(k).forEach(J=>{ee[J]===void 0&&(ee[J]=k[J])}),U.setNode(Y,ee),U.setParent(Y,$.parent(Y))}),$.edges().forEach(Y=>{let te=z($.edge(Y));U.setEdge(Y,Object.assign({},_,G(te,O),f.pick(te,E)))}),U}function N($){let U=$.graph();U.ranksep/=2,$.edges().forEach(W=>{let Y=$.edge(W);Y.minlen*=2,Y.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?Y.width+=Y.labeloffset:Y.height+=Y.labeloffset)})}function I($){$.edges().forEach(U=>{let W=$.edge(U);if(W.width&&W.height){let Y=$.node(U.v),ee={rank:($.node(U.w).rank-Y.rank)/2+Y.rank,e:U};f.addDummyNode($,"edge-proxy",ee,"_ep")}})}function A($){let U=0;$.nodes().forEach(W=>{let Y=$.node(W);Y.borderTop&&(Y.minRank=$.node(Y.borderTop).rank,Y.maxRank=$.node(Y.borderBottom).rank,U=Math.max(U,Y.maxRank))}),$.graph().maxRank=U}function R($){$.nodes().forEach(U=>{let W=$.node(U);W.dummy==="edge-proxy"&&($.edge(W.e).labelRank=W.rank,$.removeNode(U))})}function L($){let U=Number.POSITIVE_INFINITY,W=0,Y=Number.POSITIVE_INFINITY,te=0,ee=$.graph(),J=ee.marginx||0,re=ee.marginy||0;function le(X){let ne=X.x,se=X.y,de=X.width,ue=X.height;U=Math.min(U,ne-de/2),W=Math.max(W,ne+de/2),Y=Math.min(Y,se-ue/2),te=Math.max(te,se+ue/2)}$.nodes().forEach(X=>le($.node(X))),$.edges().forEach(X=>{let ne=$.edge(X);Object.hasOwn(ne,"x")&&le(ne)}),U-=J,Y-=re,$.nodes().forEach(X=>{let ne=$.node(X);ne.x-=U,ne.y-=Y}),$.edges().forEach(X=>{let ne=$.edge(X);ne.points.forEach(se=>{se.x-=U,se.y-=Y}),Object.hasOwn(ne,"x")&&(ne.x-=U),Object.hasOwn(ne,"y")&&(ne.y-=Y)}),ee.width=W-U+J,ee.height=te-Y+re}function M($){$.edges().forEach(U=>{let W=$.edge(U),Y=$.node(U.v),te=$.node(U.w),ee,J;W.points?(ee=W.points[0],J=W.points[W.points.length-1]):(W.points=[],ee=te,J=Y),W.points.unshift(f.intersectRect(Y,ee)),W.points.push(f.intersectRect(te,J))})}function B($){$.edges().forEach(U=>{let W=$.edge(U);if(Object.hasOwn(W,"x"))switch((W.labelpos==="l"||W.labelpos==="r")&&(W.width-=W.labeloffset),W.labelpos){case"l":W.x-=W.width/2+W.labeloffset;break;case"r":W.x+=W.width/2+W.labeloffset;break}})}function V($){$.edges().forEach(U=>{let W=$.edge(U);W.reversed&&W.points.reverse()})}function q($){$.nodes().forEach(U=>{if($.children(U).length){let W=$.node(U),Y=$.node(W.borderTop),te=$.node(W.borderBottom),ee=$.node(W.borderLeft[W.borderLeft.length-1]),J=$.node(W.borderRight[W.borderRight.length-1]);W.width=Math.abs(J.x-ee.x),W.height=Math.abs(te.y-Y.y),W.x=ee.x+W.width/2,W.y=Y.y+W.height/2}}),$.nodes().forEach(U=>{$.node(U).dummy==="border"&&$.removeNode(U)})}function F($){$.edges().forEach(U=>{if(U.v===U.w){var W=$.node(U.v);W.selfEdges||(W.selfEdges=[]),W.selfEdges.push({e:U,label:$.edge(U)}),$.removeEdge(U)}})}function H($){var U=f.buildLayerMatrix($);U.forEach(W=>{var Y=0;W.forEach((te,ee)=>{var J=$.node(te);J.order=ee+Y,(J.selfEdges||[]).forEach(re=>{f.addDummyNode($,"selfedge",{width:re.label.width,height:re.label.height,rank:J.rank,order:ee+ ++Y,e:re.e,label:re.label},"_se")}),delete J.selfEdges})})}function D($){$.nodes().forEach(U=>{var W=$.node(U);if(W.dummy==="selfedge"){var Y=$.node(W.e.v),te=Y.x+Y.width/2,ee=Y.y,J=W.x-te,re=Y.height/2;$.setEdge(W.e,W.label),$.removeNode(U),W.label.points=[{x:te+2*J/3,y:ee-re},{x:te+5*J/6,y:ee-re},{x:te+J,y:ee},{x:te+5*J/6,y:ee+re},{x:te+2*J/3,y:ee+re}],W.label.x=W.x,W.label.y=W.y}})}function G($,U){return f.mapValues(f.pick($,U),Number)}function z($){var U={};return $&&Object.entries($).forEach(([W,Y])=>{typeof W=="string"&&(W=W.toLowerCase()),U[W]=Y}),U}return xne}var wne,gBe;function HGn(){if(gBe)return wne;gBe=1;let e=$l(),t=Vg().Graph;wne={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 wne}var Sne,vBe;function WGn(){return vBe||(vBe=1,Sne="1.1.8"),Sne}var kne,yBe;function ZGn(){return yBe||(yBe=1,kne={graphlib:Vg(),layout:VGn(),debug:HGn(),util:{time:$l().time,notime:$l().notime},version:WGn()}),kne}var GGn=ZGn();const bBe=ql(GGn);function Zl(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=Zl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var QGn={value:()=>{}};function CW(){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 u9(n)}function u9(e){this._=e}function YGn(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}})}u9.prototype=CW.prototype={constructor:u9,on:function(e,t){var n=this._,r=YGn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=KGn(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]=xBe(n[s],e.name,t);else if(t==null)for(s in n)n[s]=xBe(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 u9(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 KGn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function xBe(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=QGn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Wve="http://www.w3.org/1999/xhtml";const wBe={svg:"http://www.w3.org/2000/svg",xhtml:Wve,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function _W(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),wBe.hasOwnProperty(t)?{space:wBe[t],local:e}:e}function XGn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Wve&&t.documentElement.namespaceURI===Wve?t.createElement(e):t.createElementNS(n,e)}}function JGn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function ICt(e){var t=_W(e);return(t.local?JGn:XGn)(t)}function eQn(){}function YOe(e){return e==null?eQn:function(){return this.querySelector(e)}}function tQn(e){typeof e!="function"&&(e=YOe(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 ep(r,this._parents)}function nQn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function rQn(){return[]}function ACt(e){return e==null?rQn:function(){return this.querySelectorAll(e)}}function sQn(e){return function(){return nQn(e.apply(this,arguments))}}function aQn(e){typeof e=="function"?e=sQn(e):e=ACt(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 ep(r,s)}function RCt(e){return function(){return this.matches(e)}}function PCt(e){return function(t){return t.matches(e)}}var iQn=Array.prototype.find;function oQn(e){return function(){return iQn.call(this.children,e)}}function lQn(){return this.firstElementChild}function cQn(e){return this.select(e==null?lQn:oQn(typeof e=="function"?e:PCt(e)))}var uQn=Array.prototype.filter;function dQn(){return Array.from(this.children)}function fQn(e){return function(){return uQn.call(this.children,e)}}function hQn(e){return this.selectAll(e==null?dQn:fQn(typeof e=="function"?e:PCt(e)))}function pQn(e){typeof e!="function"&&(e=RCt(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 ep(r,this._parents)}function $Ct(e){return new Array(e.length)}function mQn(){return new ep(this._enter||this._groups.map($Ct),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 gQn(e){return function(){return e}}function vQn(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 yQn(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 bQn(e){return e.__data__}function xQn(e,t){if(!arguments.length)return Array.from(this,bQn);var n=t?yQn:vQn,r=this._parents,s=this._groups;typeof e!="function"&&(e=gQn(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=wQn(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 ep(i,r),i._enter=l,i._exit=c,i}function wQn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function SQn(){return new ep(this._exit||this._groups.map($Ct),this._parents)}function kQn(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 OQn(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 ep(l,this._parents)}function CQn(){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 _Qn(e){e||(e=EQn);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 ep(s,this._parents).order()}function EQn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function TQn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function jQn(){return Array.from(this)}function NQn(){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 IQn(){let e=0;for(const t of this)++e;return e}function AQn(){return!this.node()}function RQn(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 PQn(e){return function(){this.removeAttribute(e)}}function $Qn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function MQn(e,t){return function(){this.setAttribute(e,t)}}function DQn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function LQn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function FQn(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 zQn(e,t){var n=_W(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?$Qn:PQn:typeof t=="function"?n.local?FQn:LQn:n.local?DQn:MQn)(n,t))}function MCt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function BQn(e){return function(){this.style.removeProperty(e)}}function UQn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function qQn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function VQn(e,t,n){return arguments.length>1?this.each((t==null?BQn:typeof t=="function"?qQn:UQn)(e,t,n??"")):uN(this.node(),e)}function uN(e,t){return e.style.getPropertyValue(t)||MCt(e).getComputedStyle(e,null).getPropertyValue(t)}function HQn(e){return function(){delete this[e]}}function WQn(e,t){return function(){this[e]=t}}function ZQn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function GQn(e,t){return arguments.length>1?this.each((t==null?HQn:typeof t=="function"?ZQn:WQn)(e,t)):this.node()[e]}function DCt(e){return e.trim().split(/^|\s+/)}function KOe(e){return e.classList||new LCt(e)}function LCt(e){this._node=e,this._names=DCt(e.getAttribute("class")||"")}LCt.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 FCt(e,t){for(var n=KOe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function zCt(e,t){for(var n=KOe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function QQn(e){return function(){FCt(this,e)}}function YQn(e){return function(){zCt(this,e)}}function KQn(e,t){return function(){(t.apply(this,arguments)?FCt:zCt)(this,e)}}function XQn(e,t){var n=DCt(e+"");if(arguments.length<2){for(var r=KOe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?KQn:t?QQn:YQn)(n,t))}function JQn(){this.textContent=""}function eYn(e){return function(){this.textContent=e}}function tYn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function nYn(e){return arguments.length?this.each(e==null?JQn:(typeof e=="function"?tYn:eYn)(e)):this.node().textContent}function rYn(){this.innerHTML=""}function sYn(e){return function(){this.innerHTML=e}}function aYn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function iYn(e){return arguments.length?this.each(e==null?rYn:(typeof e=="function"?aYn:sYn)(e)):this.node().innerHTML}function oYn(){this.nextSibling&&this.parentNode.appendChild(this)}function lYn(){return this.each(oYn)}function cYn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function uYn(){return this.each(cYn)}function dYn(e){var t=typeof e=="function"?e:ICt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function fYn(){return null}function hYn(e,t){var n=typeof e=="function"?e:ICt(e),r=t==null?fYn:typeof t=="function"?t:YOe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function pYn(){var e=this.parentNode;e&&e.removeChild(this)}function mYn(){return this.each(pYn)}function gYn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function vYn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function yYn(e){return this.select(e?vYn:gYn)}function bYn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function xYn(e){return function(t){e.call(this,t,this.__data__)}}function wYn(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 SYn(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 kYn(e,t,n){return function(){var r=this.__on,s,a=xYn(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 OYn(e,t,n){var r=wYn(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?kYn:SYn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function BCt(e,t,n){var r=MCt(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 CYn(e,t){return function(){return BCt(this,e,t)}}function _Yn(e,t){return function(){return BCt(this,e,t.apply(this,arguments))}}function EYn(e,t){return this.each((typeof t=="function"?_Yn:CYn)(e,t))}function*TYn(){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 UCt=[null];function ep(e,t){this._groups=e,this._parents=t}function dL(){return new ep([[document.documentElement]],UCt)}function jYn(){return this}ep.prototype=dL.prototype={constructor:ep,select:tQn,selectAll:aQn,selectChild:cQn,selectChildren:hQn,filter:pQn,data:xQn,enter:mQn,exit:SQn,join:kQn,merge:OQn,selection:jYn,order:CQn,sort:_Qn,call:TQn,nodes:jQn,node:NQn,size:IQn,empty:AQn,each:RQn,attr:zQn,style:VQn,property:GQn,classed:XQn,text:nYn,html:iYn,raise:lYn,lower:uYn,append:dYn,insert:hYn,remove:mYn,clone:yYn,datum:bYn,on:OYn,dispatch:EYn,[Symbol.iterator]:TYn};function Th(e){return typeof e=="string"?new ep([[document.querySelector(e)]],[document.documentElement]):new ep([[e]],UCt)}function NYn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function gg(e,t){if(e=NYn(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 IYn={passive:!1},G2={capture:!0,passive:!1};function One(e){e.stopImmediatePropagation()}function yj(e){e.preventDefault(),e.stopImmediatePropagation()}function qCt(e){var t=e.document.documentElement,n=Th(e).on("dragstart.drag",yj,G2);"onselectstart"in t?n.on("selectstart.drag",yj,G2):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function VCt(e,t){var n=e.document.documentElement,r=Th(e).on("dragstart.drag",null);t&&(r.on("click.drag",yj,G2),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 RF=e=>()=>e;function Zve(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}})}Zve.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function AYn(e){return!e.ctrlKey&&!e.button}function RYn(){return this.parentNode}function PYn(e,t){return t??{x:e.x,y:e.y}}function $Yn(){return navigator.maxTouchPoints||"ontouchstart"in this}function HCt(){var e=AYn,t=RYn,n=PYn,r=$Yn,s={},a=CW("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,IYn).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");_&&(Th(k.view).on("mousemove.drag",m,G2).on("mouseup.drag",v,G2),qCt(k.view),One(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(yj(k),!u){var O=k.clientX-l,_=k.clientY-c;u=O*O+_*_>f}s.mouse("drag",k)}function v(k){Th(k.view).on("mousemove.drag mouseup.drag",null),VCt(k.view,u),yj(k),s.mouse("end",k)}function y(k,O){if(e.call(this,k,O)){var _=k.changedTouches,E=t.call(this,k,O),T=_.length,N,I;for(N=0;N<T;++N)(I=w(this,E,k,O,_[N].identifier,_[N]))&&(One(k),I("start",k,_[N]))}}function b(k){var O=k.changedTouches,_=O.length,E,T;for(E=0;E<_;++E)(T=s[O[E].identifier])&&(yj(k),T("drag",k,O[E]))}function x(k){var O=k.changedTouches,_=O.length,E,T;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<_;++E)(T=s[O[E].identifier])&&(One(k),T("end",k,O[E]))}function w(k,O,_,E,T,N){var I=a.copy(),A=gg(N||_,O),R,L,M;if((M=n.call(k,new Zve("beforestart",{sourceEvent:_,target:h,identifier:T,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=M.x-A[0]||0,L=M.y-A[1]||0,function B(V,q,F){var H=A,D;switch(V){case"start":s[T]=B,D=i++;break;case"end":delete s[T],--i;case"drag":A=gg(F||q,O),D=i;break}I.call(V,k,new Zve(V,{sourceEvent:q,subject:M,target:h,identifier:T,active:D,x:A[0]+R,y:A[1]+L,dx:A[0]-H[0],dy:A[1]-H[1],dispatch:I}),E)}}return h.filter=function(k){return arguments.length?(e=typeof k=="function"?k:RF(!!k),h):e},h.container=function(k){return arguments.length?(t=typeof k=="function"?k:RF(k),h):t},h.subject=function(k){return arguments.length?(n=typeof k=="function"?k:RF(k),h):n},h.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:RF(!!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 XOe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function WCt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function fL(){}var Q2=.7,pU=1/Q2,bj="\\s*([+-]?\\d+)\\s*",Y2="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",py="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",MYn=/^#([0-9a-f]{3,8})$/,DYn=new RegExp(`^rgb\\(${bj},${bj},${bj}\\)$`),LYn=new RegExp(`^rgb\\(${py},${py},${py}\\)$`),FYn=new RegExp(`^rgba\\(${bj},${bj},${bj},${Y2}\\)$`),zYn=new RegExp(`^rgba\\(${py},${py},${py},${Y2}\\)$`),BYn=new RegExp(`^hsl\\(${Y2},${py},${py}\\)$`),UYn=new RegExp(`^hsla\\(${Y2},${py},${py},${Y2}\\)$`),SBe={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};XOe(fL,lC,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:kBe,formatHex:kBe,formatHex8:qYn,formatHsl:VYn,formatRgb:OBe,toString:OBe});function kBe(){return this.rgb().formatHex()}function qYn(){return this.rgb().formatHex8()}function VYn(){return ZCt(this).formatHsl()}function OBe(){return this.rgb().formatRgb()}function lC(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=MYn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?CBe(t):n===3?new jf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?PF(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?PF(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=DYn.exec(e))?new jf(t[1],t[2],t[3],1):(t=LYn.exec(e))?new jf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=FYn.exec(e))?PF(t[1],t[2],t[3],t[4]):(t=zYn.exec(e))?PF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=BYn.exec(e))?TBe(t[1],t[2]/100,t[3]/100,1):(t=UYn.exec(e))?TBe(t[1],t[2]/100,t[3]/100,t[4]):SBe.hasOwnProperty(e)?CBe(SBe[e]):e==="transparent"?new jf(NaN,NaN,NaN,0):null}function CBe(e){return new jf(e>>16&255,e>>8&255,e&255,1)}function PF(e,t,n,r){return r<=0&&(e=t=n=NaN),new jf(e,t,n,r)}function HYn(e){return e instanceof fL||(e=lC(e)),e?(e=e.rgb(),new jf(e.r,e.g,e.b,e.opacity)):new jf}function Gve(e,t,n,r){return arguments.length===1?HYn(e):new jf(e,t,n,r??1)}function jf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}XOe(jf,Gve,WCt(fL,{brighter(e){return e=e==null?pU:Math.pow(pU,e),new jf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Q2:Math.pow(Q2,e),new jf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new jf(pO(this.r),pO(this.g),pO(this.b),mU(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:_Be,formatHex:_Be,formatHex8:WYn,formatRgb:EBe,toString:EBe}));function _Be(){return`#${Gk(this.r)}${Gk(this.g)}${Gk(this.b)}`}function WYn(){return`#${Gk(this.r)}${Gk(this.g)}${Gk(this.b)}${Gk((isNaN(this.opacity)?1:this.opacity)*255)}`}function EBe(){const e=mU(this.opacity);return`${e===1?"rgb(":"rgba("}${pO(this.r)}, ${pO(this.g)}, ${pO(this.b)}${e===1?")":`, ${e})`}`}function mU(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function pO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Gk(e){return e=pO(e),(e<16?"0":"")+e.toString(16)}function TBe(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new kg(e,t,n,r)}function ZCt(e){if(e instanceof kg)return new kg(e.h,e.s,e.l,e.opacity);if(e instanceof fL||(e=lC(e)),!e)return new kg;if(e instanceof kg)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 kg(i,l,c,e.opacity)}function ZYn(e,t,n,r){return arguments.length===1?ZCt(e):new kg(e,t,n,r??1)}function kg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}XOe(kg,ZYn,WCt(fL,{brighter(e){return e=e==null?pU:Math.pow(pU,e),new kg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Q2:Math.pow(Q2,e),new kg(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 jf(Cne(e>=240?e-240:e+120,s,r),Cne(e,s,r),Cne(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new kg(jBe(this.h),$F(this.s),$F(this.l),mU(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=mU(this.opacity);return`${e===1?"hsl(":"hsla("}${jBe(this.h)}, ${$F(this.s)*100}%, ${$F(this.l)*100}%${e===1?")":`, ${e})`}`}}));function jBe(e){return e=(e||0)%360,e<0?e+360:e}function $F(e){return Math.max(0,Math.min(1,e||0))}function Cne(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 JOe=e=>()=>e;function GYn(e,t){return function(n){return e+n*t}}function QYn(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 YYn(e){return(e=+e)==1?GCt:function(t,n){return n-t?QYn(t,n,e):JOe(isNaN(t)?n:t)}}function GCt(e,t){var n=t-e;return n?GYn(e,n):JOe(isNaN(e)?t:e)}const gU=(function e(t){var n=YYn(t);function r(s,a){var i=n((s=Gve(s)).r,(a=Gve(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=GCt(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 KYn(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 XYn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function JYn(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]=bx(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 eKn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function yg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function tKn(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]=bx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Qve=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,_ne=new RegExp(Qve.source,"g");function nKn(e){return function(){return e}}function rKn(e){return function(t){return e(t)+""}}function QCt(e,t){var n=Qve.lastIndex=_ne.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Qve.exec(e))&&(s=_ne.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:yg(r,s)})),n=_ne.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?rKn(c[0].x):nKn(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 bx(e,t){var n=typeof t,r;return t==null||n==="boolean"?JOe(t):(n==="number"?yg:n==="string"?(r=lC(t))?(t=r,gU):QCt:t instanceof lC?gU:t instanceof Date?eKn:XYn(t)?KYn:Array.isArray(t)?JYn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?tKn:yg)(e,t)}function eCe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var NBe=180/Math.PI,Yve={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function YCt(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)*NBe,skewX:Math.atan(c)*NBe,scaleX:i,scaleY:l}}var MF;function sKn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Yve:YCt(t.a,t.b,t.c,t.d,t.e,t.f)}function aKn(e){return e==null||(MF||(MF=document.createElementNS("http://www.w3.org/2000/svg","g")),MF.setAttribute("transform",e),!(e=MF.transform.baseVal.consolidate()))?Yve:(e=e.matrix,YCt(e.a,e.b,e.c,e.d,e.e,e.f))}function KCt(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:yg(u,f)},{i:v-2,x:yg(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:yg(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:yg(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:yg(u,f)},{i:v-2,x:yg(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 iKn=KCt(sKn,"px, ","px)","deg)"),oKn=KCt(aKn,", ",")",")"),lKn=1e-12;function IBe(e){return((e=Math.exp(e))+1/e)/2}function cKn(e){return((e=Math.exp(e))-1/e)/2}function uKn(e){return((e=Math.exp(2*e))-1)/(e+1)}const d9=(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<lKn)b=Math.log(h/u)/t,y=function(E){return[l+E*p,c+E*m,u*Math.exp(t*E*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(E){var T=E*b,N=IBe(O),I=u/(n*x)*(N*uKn(t*T+O)-cKn(O));return[l+I*p,c+I*m,u*N/IBe(t*T+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 dKn(e,t){t===void 0&&(t=e,e=bx);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 dN=0,u$=0,YR=0,XCt=1e3,vU,d$,yU=0,cC=0,EW=0,K2=typeof performance=="object"&&performance.now?performance:Date,JCt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function tCe(){return cC||(JCt(fKn),cC=K2.now()+EW)}function fKn(){cC=0}function bU(){this._call=this._time=this._next=null}bU.prototype=e_t.prototype={constructor:bU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?tCe():+n)+(t==null?0:+t),!this._next&&d$!==this&&(d$?d$._next=this:vU=this,d$=this),this._call=e,this._time=n,Kve()},stop:function(){this._call&&(this._call=null,this._time=1/0,Kve())}};function e_t(e,t,n){var r=new bU;return r.restart(e,t,n),r}function hKn(){tCe(),++dN;for(var e=vU,t;e;)(t=cC-e._time)>=0&&e._call.call(void 0,t),e=e._next;--dN}function ABe(){cC=(yU=K2.now())+EW,dN=u$=0;try{hKn()}finally{dN=0,mKn(),cC=0}}function pKn(){var e=K2.now(),t=e-yU;t>XCt&&(EW-=t,yU=e)}function mKn(){for(var e,t=vU,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:vU=n);d$=e,Kve(r)}function Kve(e){if(!dN){u$&&(u$=clearTimeout(u$));var t=e-cC;t>24?(e<1/0&&(u$=setTimeout(ABe,e-K2.now()-EW)),YR&&(YR=clearInterval(YR))):(YR||(yU=K2.now(),YR=setInterval(pKn,XCt)),dN=1,JCt(ABe))}}function RBe(e,t,n){var r=new bU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var gKn=CW("start","end","cancel","interrupt"),vKn=[],t_t=0,PBe=1,Xve=2,f9=3,$Be=4,Jve=5,h9=6;function TW(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;yKn(e,n,{name:t,index:r,group:s,on:gKn,tween:vKn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:t_t})}function nCe(e,t){var n=ev(e,t);if(n.state>t_t)throw new Error("too late; already scheduled");return n}function Vy(e,t){var n=ev(e,t);if(n.state>f9)throw new Error("too late; already running");return n}function ev(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function yKn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=e_t(a,0,n.time);function a(u){n.state=PBe,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!==PBe)return c();for(d in r)if(p=r[d],p.name===n.name){if(p.state===f9)return RBe(i);p.state===$Be?(p.state=h9,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[d]):+d<t&&(p.state=h9,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[d])}if(RBe(function(){n.state===f9&&(n.state=$Be,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Xve,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Xve){for(n.state=f9,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=Jve,1),f=-1,h=s.length;++f<h;)s[f].call(e,d);n.state===Jve&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=h9,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function p9(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>Xve&&r.state<Jve,r.state=h9,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function bKn(e){return this.each(function(){p9(this,e)})}function xKn(e,t){var n,r;return function(){var s=Vy(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 wKn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Vy(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 SKn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=ev(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?xKn:wKn)(n,e,t))}function rCe(e,t,n){var r=e._id;return e.each(function(){var s=Vy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return ev(s,r).value[t]}}function n_t(e,t){var n;return(typeof t=="number"?yg:t instanceof lC?gU:(n=lC(t))?(t=n,gU):QCt)(e,t)}function kKn(e){return function(){this.removeAttribute(e)}}function OKn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function CKn(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 _Kn(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 EKn(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 TKn(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 jKn(e,t){var n=_W(e),r=n==="transform"?oKn:n_t;return this.attrTween(e,typeof t=="function"?(n.local?TKn:EKn)(n,r,rCe(this,"attr."+e,t)):t==null?(n.local?OKn:kKn)(n):(n.local?_Kn:CKn)(n,r,t))}function NKn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function IKn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function AKn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&IKn(e,a)),n}return s._value=t,s}function RKn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&NKn(e,a)),n}return s._value=t,s}function PKn(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=_W(e);return this.tween(n,(r.local?AKn:RKn)(r,t))}function $Kn(e,t){return function(){nCe(this,e).delay=+t.apply(this,arguments)}}function MKn(e,t){return t=+t,function(){nCe(this,e).delay=t}}function DKn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?$Kn:MKn)(t,e)):ev(this.node(),t).delay}function LKn(e,t){return function(){Vy(this,e).duration=+t.apply(this,arguments)}}function FKn(e,t){return t=+t,function(){Vy(this,e).duration=t}}function zKn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?LKn:FKn)(t,e)):ev(this.node(),t).duration}function BKn(e,t){if(typeof t!="function")throw new Error;return function(){Vy(this,e).ease=t}}function UKn(e){var t=this._id;return arguments.length?this.each(BKn(t,e)):ev(this.node(),t).ease}function qKn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Vy(this,e).ease=n}}function VKn(e){if(typeof e!="function")throw new Error;return this.each(qKn(this._id,e))}function HKn(e){typeof e!="function"&&(e=RCt(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 zx(r,this._parents,this._name,this._id)}function WKn(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 zx(i,this._parents,this._name,this._id)}function ZKn(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 GKn(e,t,n){var r,s,a=ZKn(t)?nCe:Vy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function QKn(e,t){var n=this._id;return arguments.length<2?ev(this.node(),n).on.on(e):this.each(GKn(n,e,t))}function YKn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function KKn(){return this.on("end.remove",YKn(this._id))}function XKn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=YOe(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,TW(u[h],t,n,h,u,ev(d,n)));return new zx(a,this._parents,t,n)}function JKn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=ACt(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=ev(d,n),v=0,y=h.length;v<y;++v)(p=h[v])&&TW(p,t,n,v,h,m);a.push(h),i.push(d)}return new zx(a,i,t,n)}var eXn=dL.prototype.constructor;function tXn(){return new eXn(this._groups,this._parents)}function nXn(e,t){var n,r,s;return function(){var a=uN(this,e),i=(this.style.removeProperty(e),uN(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function r_t(e){return function(){this.style.removeProperty(e)}}function rXn(e,t,n){var r,s=n+"",a;return function(){var i=uN(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function sXn(e,t,n){var r,s,a;return function(){var i=uN(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),uN(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function aXn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Vy(this,e),u=c.on,d=c.value[a]==null?l||(l=r_t(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function iXn(e,t,n){var r=(e+="")=="transform"?iKn:n_t;return t==null?this.styleTween(e,nXn(e,r)).on("end.style."+e,r_t(e)):typeof t=="function"?this.styleTween(e,sXn(e,r,rCe(this,"style."+e,t))).each(aXn(this._id,e)):this.styleTween(e,rXn(e,r,t),n).on("end.style."+e,null)}function oXn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function lXn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&oXn(e,i,n)),r}return a._value=t,a}function cXn(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,lXn(e,t,n??""))}function uXn(e){return function(){this.textContent=e}}function dXn(e){return function(){var t=e(this);this.textContent=t??""}}function fXn(e){return this.tween("text",typeof e=="function"?dXn(rCe(this,"text",e)):uXn(e==null?"":e+""))}function hXn(e){return function(t){this.textContent=e.call(this,t)}}function pXn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&hXn(s)),t}return r._value=e,r}function mXn(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,pXn(e))}function gXn(){for(var e=this._name,t=this._id,n=s_t(),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=ev(c,t);TW(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new zx(r,this._parents,e,n)}function vXn(){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=Vy(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 yXn=0;function zx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function s_t(){return++yXn}var _b=dL.prototype;zx.prototype={constructor:zx,select:XKn,selectAll:JKn,selectChild:_b.selectChild,selectChildren:_b.selectChildren,filter:HKn,merge:WKn,selection:tXn,transition:gXn,call:_b.call,nodes:_b.nodes,node:_b.node,size:_b.size,empty:_b.empty,each:_b.each,on:QKn,attr:jKn,attrTween:PKn,style:iXn,styleTween:cXn,text:fXn,textTween:mXn,remove:KKn,tween:SKn,delay:DKn,duration:zKn,ease:UKn,easeVarying:VKn,end:vXn,[Symbol.iterator]:_b[Symbol.iterator]};function bXn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var xXn={time:null,delay:0,duration:250,ease:bXn};function wXn(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 SXn(e){var t,n;e instanceof zx?(t=e._id,e=e._name):(t=s_t(),(n=xXn).time=tCe(),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])&&TW(c,e,t,u,i,n||wXn(c,t));return new zx(r,this._parents,e,t)}dL.prototype.interrupt=bKn;dL.prototype.transition=SXn;const DF=e=>()=>e;function kXn(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 ax(e,t,n){this.k=e,this.x=t,this.y=n}ax.prototype={constructor:ax,scale:function(e){return e===1?this:new ax(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new ax(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 jW=new ax(1,0,0);a_t.prototype=ax.prototype;function a_t(e){for(;!e.__zoom;)if(!(e=e.parentNode))return jW;return e.__zoom}function Ene(e){e.stopImmediatePropagation()}function KR(e){e.preventDefault(),e.stopImmediatePropagation()}function OXn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function CXn(){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 MBe(){return this.__zoom||jW}function _Xn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function EXn(){return navigator.maxTouchPoints||"ontouchstart"in this}function TXn(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 i_t(){var e=OXn,t=CXn,n=TXn,r=_Xn,s=EXn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=d9,u=CW("start","zoom","end"),d,f,h,p=500,m=150,v=0,y=10;function b(M){M.property("__zoom",MBe).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(M,B,V,q){var F=M.selection?M.selection():M;F.property("__zoom",MBe),M!==F?O(M,B,V,q):F.interrupt().each(function(){_(this,arguments).event(q).start().zoom(null,typeof B=="function"?B.apply(this,arguments):B).end()})},b.scaleBy=function(M,B,V,q){b.scaleTo(M,function(){var F=this.__zoom.k,H=typeof B=="function"?B.apply(this,arguments):B;return F*H},V,q)},b.scaleTo=function(M,B,V,q){b.transform(M,function(){var F=t.apply(this,arguments),H=this.__zoom,D=V==null?k(F):typeof V=="function"?V.apply(this,arguments):V,G=H.invert(D),z=typeof B=="function"?B.apply(this,arguments):B;return n(w(x(H,z),D,G),F,i)},V,q)},b.translateBy=function(M,B,V,q){b.transform(M,function(){return n(this.__zoom.translate(typeof B=="function"?B.apply(this,arguments):B,typeof V=="function"?V.apply(this,arguments):V),t.apply(this,arguments),i)},null,q)},b.translateTo=function(M,B,V,q,F){b.transform(M,function(){var H=t.apply(this,arguments),D=this.__zoom,G=q==null?k(H):typeof q=="function"?q.apply(this,arguments):q;return n(jW.translate(G[0],G[1]).scale(D.k).translate(typeof B=="function"?-B.apply(this,arguments):-B,typeof V=="function"?-V.apply(this,arguments):-V),H,i)},q,F)};function x(M,B){return B=Math.max(a[0],Math.min(a[1],B)),B===M.k?M:new ax(B,M.x,M.y)}function w(M,B,V){var q=B[0]-V[0]*M.k,F=B[1]-V[1]*M.k;return q===M.x&&F===M.y?M:new ax(M.k,q,F)}function k(M){return[(+M[0][0]+ +M[1][0])/2,(+M[0][1]+ +M[1][1])/2]}function O(M,B,V,q){M.on("start.zoom",function(){_(this,arguments).event(q).start()}).on("interrupt.zoom end.zoom",function(){_(this,arguments).event(q).end()}).tween("zoom",function(){var F=this,H=arguments,D=_(F,H).event(q),G=t.apply(F,H),z=V==null?k(G):typeof V=="function"?V.apply(F,H):V,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=F.__zoom,W=typeof B=="function"?B.apply(F,H):B,Y=c(U.invert(z).concat($/U.k),W.invert(z).concat($/W.k));return function(te){if(te===1)te=W;else{var ee=Y(te),J=$/ee[2];te=new ax(J,z[0]-ee[0]*J,z[1]-ee[1]*J)}D.zoom(null,te)}})}function _(M,B,V){return!V&&M.__zooming||new E(M,B)}function E(M,B){this.that=M,this.args=B,this.active=0,this.sourceEvent=null,this.extent=t.apply(M,B),this.taps=0}E.prototype={event:function(M){return M&&(this.sourceEvent=M),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(M,B){return this.mouse&&M!=="mouse"&&(this.mouse[1]=B.invert(this.mouse[0])),this.touch0&&M!=="touch"&&(this.touch0[1]=B.invert(this.touch0[0])),this.touch1&&M!=="touch"&&(this.touch1[1]=B.invert(this.touch1[0])),this.that.__zoom=B,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(M){var B=Th(this.that).datum();u.call(M,this.that,new kXn(M,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),B)}};function T(M,...B){if(!e.apply(this,arguments))return;var V=_(this,B).event(M),q=this.__zoom,F=Math.max(a[0],Math.min(a[1],q.k*Math.pow(2,r.apply(this,arguments)))),H=gg(M);if(V.wheel)(V.mouse[0][0]!==H[0]||V.mouse[0][1]!==H[1])&&(V.mouse[1]=q.invert(V.mouse[0]=H)),clearTimeout(V.wheel);else{if(q.k===F)return;V.mouse=[H,q.invert(H)],p9(this),V.start()}KR(M),V.wheel=setTimeout(D,m),V.zoom("mouse",n(w(x(q,F),V.mouse[0],V.mouse[1]),V.extent,i));function D(){V.wheel=null,V.end()}}function N(M,...B){if(h||!e.apply(this,arguments))return;var V=M.currentTarget,q=_(this,B,!0).event(M),F=Th(M.view).on("mousemove.zoom",z,!0).on("mouseup.zoom",$,!0),H=gg(M,V),D=M.clientX,G=M.clientY;qCt(M.view),Ene(M),q.mouse=[H,this.__zoom.invert(H)],p9(this),q.start();function z(U){if(KR(U),!q.moved){var W=U.clientX-D,Y=U.clientY-G;q.moved=W*W+Y*Y>v}q.event(U).zoom("mouse",n(w(q.that.__zoom,q.mouse[0]=gg(U,V),q.mouse[1]),q.extent,i))}function $(U){F.on("mousemove.zoom mouseup.zoom",null),VCt(U.view,q.moved),KR(U),q.event(U).end()}}function I(M,...B){if(e.apply(this,arguments)){var V=this.__zoom,q=gg(M.changedTouches?M.changedTouches[0]:M,this),F=V.invert(q),H=V.k*(M.shiftKey?.5:2),D=n(w(x(V,H),q,F),t.apply(this,B),i);KR(M),l>0?Th(this).transition().duration(l).call(O,D,q,M):Th(this).call(b.transform,D,q,M)}}function A(M,...B){if(e.apply(this,arguments)){var V=M.touches,q=V.length,F=_(this,B,M.changedTouches.length===q).event(M),H,D,G,z;for(Ene(M),D=0;D<q;++D)G=V[D],z=gg(G,this),z=[z,this.__zoom.invert(z),G.identifier],F.touch0?!F.touch1&&F.touch0[2]!==z[2]&&(F.touch1=z,F.taps=0):(F.touch0=z,H=!0,F.taps=1+!!d);d&&(d=clearTimeout(d)),H&&(F.taps<2&&(f=z[0],d=setTimeout(function(){d=null},p)),p9(this),F.start())}}function R(M,...B){if(this.__zooming){var V=_(this,B).event(M),q=M.changedTouches,F=q.length,H,D,G,z;for(KR(M),H=0;H<F;++H)D=q[H],G=gg(D,this),V.touch0&&V.touch0[2]===D.identifier?V.touch0[0]=G:V.touch1&&V.touch1[2]===D.identifier&&(V.touch1[0]=G);if(D=V.that.__zoom,V.touch1){var $=V.touch0[0],U=V.touch0[1],W=V.touch1[0],Y=V.touch1[1],te=(te=W[0]-$[0])*te+(te=W[1]-$[1])*te,ee=(ee=Y[0]-U[0])*ee+(ee=Y[1]-U[1])*ee;D=x(D,Math.sqrt(te/ee)),G=[($[0]+W[0])/2,($[1]+W[1])/2],z=[(U[0]+Y[0])/2,(U[1]+Y[1])/2]}else if(V.touch0)G=V.touch0[0],z=V.touch0[1];else return;V.zoom("touch",n(w(D,G,z),V.extent,i))}}function L(M,...B){if(this.__zooming){var V=_(this,B).event(M),q=M.changedTouches,F=q.length,H,D;for(Ene(M),h&&clearTimeout(h),h=setTimeout(function(){h=null},p),H=0;H<F;++H)D=q[H],V.touch0&&V.touch0[2]===D.identifier?delete V.touch0:V.touch1&&V.touch1[2]===D.identifier&&delete V.touch1;if(V.touch1&&!V.touch0&&(V.touch0=V.touch1,delete V.touch1),V.touch0)V.touch0[1]=this.__zoom.invert(V.touch0[0]);else if(V.end(),V.taps===2&&(D=gg(D,this),Math.hypot(f[0]-D[0],f[1]-D[1])<y)){var G=Th(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(M){return arguments.length?(r=typeof M=="function"?M:DF(+M),b):r},b.filter=function(M){return arguments.length?(e=typeof M=="function"?M:DF(!!M),b):e},b.touchable=function(M){return arguments.length?(s=typeof M=="function"?M:DF(!!M),b):s},b.extent=function(M){return arguments.length?(t=typeof M=="function"?M:DF([[+M[0][0],+M[0][1]],[+M[1][0],+M[1][1]]]),b):t},b.scaleExtent=function(M){return arguments.length?(a[0]=+M[0],a[1]=+M[1],b):[a[0],a[1]]},b.translateExtent=function(M){return arguments.length?(i[0][0]=+M[0][0],i[1][0]=+M[1][0],i[0][1]=+M[0][1],i[1][1]=+M[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(M){return arguments.length?(n=M,b):n},b.duration=function(M){return arguments.length?(l=+M,b):l},b.interpolate=function(M){return arguments.length?(c=M,b):c},b.on=function(){var M=u.on.apply(u,arguments);return M===u?b:M},b.clickDistance=function(M){return arguments.length?(v=(M=+M)*M,b):Math.sqrt(v)},b.tapDistance=function(M){return arguments.length?(y=+M,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."},X2=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],o_t=["Enter"," ","Escape"],l_t={"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 fN;(function(e){e.Strict="strict",e.Loose="loose"})(fN||(fN={}));var mO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(mO||(mO={}));var J2;(function(e){e.Partial="partial",e.Full="full"})(J2||(J2={}));const c_t={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Tw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Tw||(Tw={}));var eD;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(eD||(eD={}));var nr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(nr||(nr={}));const DBe={[nr.Left]:nr.Right,[nr.Right]:nr.Left,[nr.Top]:nr.Bottom,[nr.Bottom]:nr.Top};function u_t(e){return e===null?null:e?"valid":"invalid"}const d_t=e=>"id"in e&&"source"in e&&"target"in e,jXn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),sCe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),hL=(e,t=[0,0])=>{const{width:n,height:r}=l0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},NXn=(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):sCe(s)?s:t.nodeLookup.get(s.id));const l=i?xU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return NW(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return IW(n)},pL=(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=NW(n,xU(s)),r=!0)}),r?IW(n):{x:0,y:0,width:0,height:0}},aCe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...gL(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=tD(l,pN(u)),y=(p??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},IXn=(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 AXn(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 RXn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=AXn(e,i),c=pL(l),u=iCe(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 f_t({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&&mN(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=mN(f)?uC(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 PXn({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=IXn(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 hN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),uC=(e={x:0,y:0},t,n)=>({x:hN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:hN(e.y,t[0][1],t[1][1]-(n?.height??0))});function h_t(e,t,n){const{width:r,height:s}=l0(n),{x:a,y:i}=n.internals.positionAbsolute;return uC(e,[[a,i],[a+r,i+s]],t)}const LBe=(e,t,n)=>e<t?hN(Math.abs(e-t),1,t)/t:e>n?-hN(Math.abs(e-n),1,t)/t:0,p_t=(e,t,n=15,r=40)=>{const s=LBe(e.x,r,t.width-r)*n,a=LBe(e.y,r,t.height-r)*n;return[s,a]},NW=(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)}),eye=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),IW=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),pN=(e,t=[0,0])=>{const{x:n,y:r}=sCe(e)?e.internals.positionAbsolute:hL(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}=sCe(e)?e.internals.positionAbsolute:hL(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)}},m_t=(e,t)=>IW(NW(eye(e),eye(t))),tD=(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)},FBe=e=>Eg(e.width)&&Eg(e.height)&&Eg(e.x)&&Eg(e.y),Eg=e=>!isNaN(e)&&isFinite(e),$Xn=(e,t)=>{},mL=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),gL=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?mL(l,i):l},wU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function CE(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 MXn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=CE(e,n),s=CE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=CE(e.top??e.y??0,n),s=CE(e.bottom??e.y??0,n),a=CE(e.left??e.x??0,t),i=CE(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 DXn(e,t,n,r,s,a){const{x:i,y:l}=wU(e,[t,n,r]),{x:c,y:u}=wU({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 iCe=(e,t,n,r,s,a)=>{const i=MXn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=hN(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=DXn(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}},nD=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function mN(e){return e!=null&&e!=="parent"}function l0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function g_t(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function v_t(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 zBe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function LXn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function FXn(e){return{...l_t,...e||{}}}function K$(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Tg(e),l=gL({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?mL(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const oCe=e=>({width:e.offsetWidth,height:e.offsetHeight}),y_t=e=>e?.getRootNode?.()||window?.document,zXn=["INPUT","SELECT","TEXTAREA"];function b_t(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:zXn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const x_t=e=>"clientX"in e,Tg=(e,t)=>{const n=x_t(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)}},BBe=(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,...oCe(i)}})};function w_t({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 LF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function UBe({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case nr.Left:return[t-LF(t-r,a),n];case nr.Right:return[t+LF(r-t,a),n];case nr.Top:return[t,n-LF(n-s,a)];case nr.Bottom:return[t,n+LF(s-n,a)]}}function lCe({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,curvature:i=.25}){const[l,c]=UBe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=UBe({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,h,p,m]=w_t({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 S_t({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 BXn({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 UXn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=NW(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 tD(i,IW(a))>0}const qXn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,VXn=(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)),HXn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||qXn;let s;return d_t(e)?s={...e}:s={...e,id:r(e)},VXn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function k_t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=S_t({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const qBe={[nr.Left]:{x:-1,y:0},[nr.Right]:{x:1,y:0},[nr.Top]:{x:0,y:-1},[nr.Bottom]:{x:0,y:1}},WXn=({source:e,sourcePosition:t=nr.Bottom,target:n})=>t===nr.Left||t===nr.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},VBe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function ZXn({source:e,sourcePosition:t=nr.Bottom,target:n,targetPosition:r=nr.Top,center:s,offset:a,stepPosition:i}){const l=qBe[t],c=qBe[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=WXn({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]=S_t({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 T=[{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"?T:N:m=h==="x"?N:T}else{const T=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(h==="x"?m=l.x===p?N:T:m=l.y===p?T:N,t===r){const M=Math.abs(e[h]-n[h]);if(M<=a){const B=Math.min(a-1,a-M);l[h]===p?b[h]=(u[h]>e[h]?-1:1)*B:x[h]=(d[h]>n[h]?-1:1)*B}}if(t!==r){const M=h==="x"?"y":"x",B=l[h]===c[M],V=u[M]>d[M],q=u[M]<d[M];(l[h]===1&&(!B&&V||B&&q)||l[h]!==1&&(!B&&q||B&&V))&&(m=h==="x"?T:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(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 GXn(e,t,n,r){const s=Math.min(VBe(e,t)/2,VBe(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 tye({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,h,p,m,v]=ZXn({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+=GXn(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 HBe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function QXn(e){const{sourceNode:t,targetNode:n}=e;if(!HBe(t)||!HBe(n))return null;const r=t.internals.handleBounds||WBe(t.handles),s=n.internals.handleBounds||WBe(n.handles),a=ZBe(r?.source??[],e.sourceHandle),i=ZBe(e.connectionMode===fN.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||nr.Bottom,c=i?.position||nr.Top,u=dC(t,a,l),d=dC(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function WBe(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 dC(e,t,n=nr.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??l0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case nr.Top:return{x:s+i/2,y:a};case nr.Right:return{x:s+i,y:a+l/2};case nr.Bottom:return{x:s+i/2,y:a+l};case nr.Left:return{x:s,y:a+l/2}}}function ZBe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function nye(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function YXn(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=nye(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 O_t=1e3,KXn=10,cCe={nodeOrigin:[0,0],nodeExtent:X2,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},XXn={...cCe,checkEquality:!0};function uCe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function JXn(e,t,n){const r=uCe(cCe,n);for(const s of e.values())if(s.parentId)fCe(s,e,t,r);else{const a=hL(s,r.nodeOrigin),i=mN(s.extent)?s.extent:r.nodeExtent,l=uC(a,i,l0(s));s.internals.positionAbsolute=l}}function eJn(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 dCe(e){return e==="manual"}function rye(e,t,n,r={}){const s=uCe(XXn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!dCe(s.zIndexMode)?O_t: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=hL(d,s.nodeOrigin),p=mN(d.extent)?d.extent:s.nodeExtent,m=uC(h,p,l0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:eJn(d,f),z:C_t(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&&fCe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function tJn(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 fCe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=uCe(cCe,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}tJn(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*KXn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!dCe(c)?O_t:0,{x:h,y:p,z:m}=nJn(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 C_t(e,t,n){const r=Eg(e.zIndex)?e.zIndex:0;return dCe(n)?r:r+(e.selected?t:0)}function nJn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=l0(e),u=hL(e,n),d=mN(e.extent)?uC(u,e.extent,c):u;let f=uC({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=h_t(f,c,t));const h=C_t(e,s,a),p=t.internals.z??0;return{x:f.x,y:f.y,z:p>=h?p+1:h}}function hCe(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??pN(l),u=m_t(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=l0(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 rJn(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=oCe(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=mN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=h_t(k,v,t.get(m.parentId)):w&&(k=uC(k,w,v));const O={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:BBe("source",p.nodeElement,x,f,m.id),target:BBe("target",p.nodeElement,x,f,m.id)}}};t.set(m.id,O),m.parentId&&fCe(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:pN(O,s)}))}}if(h.length>0){const p=hCe(h,t,n,s);u.push(...p)}return{changes:u,updatedInternals:c}}async function sJn({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 GBe(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 __t(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}`;GBe("source",c,d,e,s,i),GBe("target",c,u,e,a,l),t.set(r.id,r)}}function E_t(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:E_t(n,t):!1}function QBe(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 aJn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!E_t(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 Tne({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 iJn({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=mL(a,t);return{x:i.x-a.x,y:i.y-a.y}}function oJn({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:E=0}){h=Th(k);function T({x:R,y:L}){const{nodeLookup:M,nodeExtent:B,snapGrid:V,snapToGrid:q,nodeOrigin:F,onNodeDrag:H,onSelectionDrag:D,onError:G,updateNodePositions:z}=t();a={x:R,y:L};let $=!1;const U=l.size>1,W=U&&B?eye(pL(l)):null,Y=U&&q?iJn({dragItems:l,snapGrid:V,x:R,y:L}):null;for(const[te,ee]of l){if(!M.has(te))continue;let J={x:R-ee.distance.x,y:L-ee.distance.y};q&&(J=Y?{x:Math.round(J.x+Y.x),y:Math.round(J.y+Y.y)}:mL(J,V));let re=null;if(U&&B&&!ee.extent&&W){const{positionAbsolute:ne}=ee.internals,se=ne.x-W.x+B[0][0],de=ne.x+ee.measured.width-W.x2+B[1][0],ue=ne.y-W.y+B[0][1],ye=ne.y+ee.measured.height-W.y2+B[1][1];re=[[se,ue],[de,ye]]}const{position:le,positionAbsolute:X}=f_t({nodeId:te,nextPosition:J,nodeLookup:M,nodeExtent:re||B,nodeOrigin:F,onError:G});$=$||ee.position.x!==le.x||ee.position.y!==le.y,ee.position=le,ee.internals.positionAbsolute=X}if(m=m||$,!!$&&(z(l,!0),v&&(r||H||!_&&D))){const[te,ee]=Tne({nodeId:_,dragItems:l,nodeLookup:M});r?.(v,l,te,ee),H?.(v,te,ee),_||D?.(v,ee)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:M,autoPanOnNodeDrag:B}=t();if(!B){c=!1,cancelAnimationFrame(i);return}const[V,q]=p_t(u,d,M);(V!==0||q!==0)&&(a.x=(a.x??0)-V/R[2],a.y=(a.y??0)-q/R[2],await L({x:V,y:q})&&T(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:M,nodesDraggable:B,transform:V,snapGrid:q,snapToGrid:F,selectNodesOnDrag:H,onNodeDragStart:D,onSelectionDragStart:G,unselectNodesAndEdges:z}=t();f=!0,(!H||!O)&&!M&&_&&(L.get(_)?.selected||z()),O&&H&&_&&e?.(_);const $=K$(R.sourceEvent,{transform:V,snapGrid:q,snapToGrid:F,containerBounds:d});if(a=$,l=aJn(L,B,$,_),l.size>0&&(n||D||!_&&G)){const[U,W]=Tne({nodeId:_,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,U,W),D?.(R.sourceEvent,U,W),_||G?.(R.sourceEvent,W)}}const A=HCt().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:M,transform:B,snapGrid:V,snapToGrid:q}=t();d=L?.getBoundingClientRect()||null,p=!1,m=!1,v=R.sourceEvent,M===0&&I(R),a=K$(R.sourceEvent,{transform:B,snapGrid:V,snapToGrid:q,containerBounds:d}),u=Tg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:M,snapGrid:B,snapToGrid:V,nodeDragThreshold:q,nodeLookup:F}=t(),H=K$(R.sourceEvent,{transform:M,snapGrid:B,snapToGrid:V,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||_&&!F.has(_))&&(p=!0),!p){if(!c&&L&&f&&(c=!0,N()),!f){const D=Tg(R.sourceEvent,d),G=D.x-u.x,z=D.y-u.y;Math.sqrt(G*G+z*z)>q&&I(R)}(a.x!==H.xSnapped||a.y!==H.ySnapped)&&l&&f&&(u=Tg(R.sourceEvent,d),T(H))}}).on("end",R=>{if(!(!f||p)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:M,onNodeDragStop:B,onSelectionDragStop:V}=t();if(m&&(M(l,!1),m=!1),s||B||!_&&V){const[q,F]=Tne({nodeId:_,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,q,F),B?.(R.sourceEvent,q,F),_||V?.(R.sourceEvent,F)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!QBe(L,`.${x}`,k))&&(!w||QBe(L,w,k))});h.call(A)}function b(){h?.on(".drag",null)}return{update:y,destroy:b}}function lJn(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())tD(s,pN(a))>0&&r.push(a);return r}const cJn=250;function uJn(e,t,n,r){let s=[],a=1/0;const i=lJn(e,n,t+cJn);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}=dC(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 T_t(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,...dC(i,c,c.position,!0)}:c}function j_t(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function dJn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const N_t=()=>!0;function fJn(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=N_t,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:O,autoPanSpeed:_,dragThreshold:E=1,handleDomNode:T}){const N=y_t(e.target);let I=0,A;const{x:R,y:L}=Tg(e),M=j_t(a,T),B=l?.getBoundingClientRect();let V=!1;if(!B||!M)return;const q=T_t(s,M,r,c,t);if(!q)return;let F=Tg(e,B),H=!1,D=null,G=!1,z=null;function $(){if(!d||!B)return;const[le,X]=p_t(F,B,_);h({x:le,y:X}),I=requestAnimationFrame($)}const U={...q,nodeId:s,type:M,position:q.position},W=c.get(s);let te={inProgress:!0,isValid:null,from:dC(W,U,nr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:W,to:F,toHandle:null,toPosition:DBe[U.position],toNode:null,pointer:F};function ee(){V=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:M})}E===0&&ee();function J(le){if(!V){const{x:ye,y:he}=Tg(le),xe=ye-R,Ne=he-L;if(!(xe*xe+Ne*Ne>E*E))return;ee()}if(!O()||!U){re(le);return}const X=k();F=Tg(le,B),A=uJn(gL(F,X,!1,[1,1]),n,c,U),H||($(),H=!0);const ne=I_t(le,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});z=ne.handleDomNode,D=ne.connection,G=dJn(!!A,ne.isValid);const se=c.get(s),de=se?dC(se,U,nr.Left,!0):te.from,ue={...te,from:de,isValid:G,to:ne.toHandle&&G?wU({x:ne.toHandle.x,y:ne.toHandle.y},X):F,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:DBe[U.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:F};w(ue),te=ue}function re(le){if(!("touches"in le&&le.touches.length>0)){if(V){(A||z)&&D&&G&&v?.(D);const{inProgress:X,...ne}=te,se={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(le,se),a&&x?.(le,se)}p(),cancelAnimationFrame(I),H=!1,G=!1,D=null,z=null,N.removeEventListener("mousemove",J),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",J),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",J),N.addEventListener("mouseup",re),N.addEventListener("touchmove",J),N.addEventListener("touchend",re)}function I_t(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=N_t,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}=Tg(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=j_t(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 E={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=E;const N=O&&_&&(n===fN.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=N&&u(E),b.toHandle=T_t(w,x,k,d,n,!0)}return b}const sye={onPointerDown:fJn,isValid:I_t};function hJn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Th(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&&nD()?10:1,_=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,_*O);t.scaleTo(E)};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 E=r()*Math.max(k[2],Math.log(k[2]))*(p?-1:1),T={x:k[0]-_[0]*E,y:k[1]-_[1]*E},N=[[0,0],[c,u]];t.setViewportConstrained({x:T.x,y:T.y,zoom:k[2]},N,l)},x=i_t().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:gg}}const AW=e=>({x:e.x,y:e.y,zoom:e.k}),jne=({x:e,y:t,zoom:n})=>jW.translate(e,t).scale(n),AT=(e,t)=>e.target.closest(`.${t}`),A_t=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),pJn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Nne=(e,t=0,n=pJn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},R_t=e=>{const t=e.ctrlKey&&nD()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function mJn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(AT(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=gg(d),b=R_t(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const h=d.deltaMode===1?20:1;let p=s===mO.Vertical?0:d.deltaX*h,m=s===mO.Horizontal?0:d.deltaY*h;!nD()&&d.shiftKey&&s!==mO.Vertical&&(p=d.deltaY*h,m=0),r.translateBy(n,-(p/f)*a,-(m/f)*a,{internal:!0});const v=AW(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 gJn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=AT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function vJn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=AW(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 yJn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&A_t(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,AW(a.transform))}}function bJn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&A_t(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=AW(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function xJn({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"&&(AT(f,`${u}-flow__node`)||AT(f,`${u}-flow__edge`)))return!0;if(!r&&!h&&!s&&!a&&!n||i||d&&!m||AT(f,l)&&m||AT(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 wJn({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=i_t().scaleExtent([t,n]).translateExtent(r),h=Th(e).call(f);x({x:s.x,y:s.y,zoom:hN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const p=h.on("wheel.zoom"),m=h.on("dblclick.zoom");f.wheelDelta(R_t);function v(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?bx:d9).transform(Nne(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:M,panOnScroll:B,panOnDrag:V,panOnScrollMode:q,panOnScrollSpeed:F,preventScrolling:H,zoomOnPinch:D,zoomOnScroll:G,zoomOnDoubleClick:z,zoomActivationKeyPressed:$,lib:U,onTransformChange:W,connectionInProgress:Y,paneClickDistance:te,selectionOnDrag:ee}){M&&!u.isZoomingOrPanning&&b();const J=B&&!$&&!M;f.clickDistance(ee?1/0:!Eg(te)||te<0?0:te);const re=J?mJn({zoomPanValues:u,noWheelClassName:A,d3Selection:h,d3Zoom:f,panOnScrollMode:q,panOnScrollSpeed:F,zoomOnPinch:D,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):gJn({noWheelClassName:A,preventScrolling:H,d3ZoomHandler:p});if(h.on("wheel.zoom",re,{passive:!1}),!M){const X=vJn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const ne=yJn({zoomPanValues:u,panOnDrag:V,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:W});f.on("zoom",ne);const se=bJn({zoomPanValues:u,panOnDrag:V,panOnScroll:B,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const le=xJn({zoomActivationKeyPressed:$,panOnDrag:V,zoomOnScroll:G,panOnScroll:B,zoomOnDoubleClick:z,zoomOnPinch:D,userSelectionActive:M,noPanClassName:R,noWheelClassName:A,lib:U,connectionInProgress:Y});f.filter(le),z?h.on("dblclick.zoom",m):h.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const M=jne(A),B=f?.constrain()(M,R,L);return B&&await v(B),new Promise(V=>V(B))}async function w(A,R){const L=jne(A);return await v(L,R),new Promise(M=>M(L))}function k(A){if(h){const R=jne(A),L=h.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(h,R,null,{sync:!0})}}function O(){const A=h?a_t(h.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?bx:d9).scaleTo(Nne(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?bx:d9).scaleBy(Nne(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!Eg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:O,scaleTo:_,scaleBy:E,setScaleExtent:T,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var gN;(function(e){e.Line="line",e.Handle="handle"})(gN||(gN={}));function SJn({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 YBe(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 rw(e,t){return Math.max(0,t-e)}function sw(e,t){return Math.max(0,e-t)}function FF(e,t,n){return Math.max(0,t-e,e-n)}function KBe(e,t){return e?!t:t}function kJn(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:E}=e;let T=Math.floor(d?p-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=O+(c?-T:T),A=_+(u?-N:N),R=-a[0]*O,L=-a[1]*_;let M=FF(I,v,y),B=FF(A,b,x);if(i){let F=0,H=0;c&&T<0?F=rw(w+T+R,i[0][0]):!c&&T>0&&(F=sw(w+I+R,i[1][0])),u&&N<0?H=rw(k+N+L,i[0][1]):!u&&N>0&&(H=sw(k+A+L,i[1][1])),M=Math.max(M,F),B=Math.max(B,H)}if(l){let F=0,H=0;c&&T>0?F=sw(w+T,l[0][0]):!c&&T<0&&(F=rw(w+I,l[1][0])),u&&N>0?H=sw(k+N,l[0][1]):!u&&N<0&&(H=rw(k+A,l[1][1])),M=Math.max(M,F),B=Math.max(B,H)}if(s){if(d){const F=FF(I/E,b,x)*E;if(M=Math.max(M,F),i){let H=0;!c&&!u||c&&!u&&h?H=sw(k+L+I/E,i[1][1])*E:H=rw(k+L+(c?T:-T)/E,i[0][1])*E,M=Math.max(M,H)}if(l){let H=0;!c&&!u||c&&!u&&h?H=rw(k+I/E,l[1][1])*E:H=sw(k+(c?T:-T)/E,l[0][1])*E,M=Math.max(M,H)}}if(f){const F=FF(A*E,v,y)/E;if(B=Math.max(B,F),i){let H=0;!c&&!u||u&&!c&&h?H=sw(w+A*E+R,i[1][0])/E:H=rw(w+(u?N:-N)*E+R,i[0][0])/E,B=Math.max(B,H)}if(l){let H=0;!c&&!u||u&&!c&&h?H=rw(w+A*E,l[1][0])/E:H=sw(w+(u?N:-N)*E,l[0][0])/E,B=Math.max(B,H)}}}N=N+(N<0?B:-B),T=T+(T<0?M:-M),s&&(h?I>A*E?N=(KBe(c,u)?-T:T)/E:T=(KBe(c,u)?-N:N)*E:d?(N=T/E,u=c):(T=N*E,c=u));const V=c?w+T:w,q=u?k+N:k;return{width:O+(c?-T:T),height:_+(u?-N:N),x:a[0]*T*(c?-1:1)+V,y:a[1]*N*(u?-1:1)+q}}const P_t={width:0,height:0,x:0,y:0},OJn={...P_t,pointerX:0,pointerY:0,aspectRatio:1};function CJn(e){return[[0,0],[e.measured.width,e.measured.height]]}function _Jn(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 EJn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Th(e);let i={controlDirection:YBe("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={...P_t},x={...OJn};i={boundaries:d,resizeDirection:h,keepAspectRatio:f,controlDirection:YBe(u)};let w,k=null,O=[],_,E,T,N=!1;const I=HCt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:M,snapToGrid:B,nodeOrigin:V,paneDomNode:q}=n();if(w=R.get(t),!w)return;k=q?.getBoundingClientRect()??null;const{xSnapped:F,ySnapped:H}=K$(A.sourceEvent,{transform:L,snapGrid:M,snapToGrid:B,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:F,pointerY:H,aspectRatio:b.width/b.height},_=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(_=R.get(w.parentId),E=_&&w.extent==="parent"?CJn(_):void 0),O=[],T=void 0;for(const[D,G]of R)if(G.parentId===t&&(O.push({id:D,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const z=_Jn(G,w,G.origin??V);T?T=[[Math.min(z[0][0],T[0][0]),Math.min(z[0][1],T[0][1])],[Math.max(z[1][0],T[1][0]),Math.max(z[1][1],T[1][1])]]:T=z}p?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:M,nodeOrigin:B}=n(),V=K$(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:M,containerBounds:k}),q=[];if(!w)return;const{x:F,y:H,width:D,height:G}=b,z={},$=w.origin??B,{width:U,height:W,x:Y,y:te}=kJn(x,i.controlDirection,V,i.boundaries,i.keepAspectRatio,$,E,T),ee=U!==D,J=W!==G,re=Y!==F&&ee,le=te!==H&&J;if(!re&&!le&&!ee&&!J)return;if((re||le||$[0]===1||$[1]===1)&&(z.x=re?Y:b.x,z.y=le?te:b.y,b.x=z.x,b.y=z.y,O.length>0)){const de=Y-F,ue=te-H;for(const ye of O)ye.position={x:ye.position.x-de+$[0]*(U-D),y:ye.position.y-ue+$[1]*(W-G)},q.push(ye)}if((ee||J)&&(z.width=ee&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,z.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?W:b.height,b.width=z.width,b.height=z.height),_&&w.expandParent){const de=$[0]*(z.width??0);z.x&&z.x<de&&(b.x=de,x.x=x.x-(z.x-de));const ue=$[1]*(z.height??0);z.y&&z.y<ue&&(b.y=ue,x.y=x.y-(z.y-ue))}const X=SJn({width:b.width,prevWidth:D,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(z,q))}).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 TJn={},XBe=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:()=>{(TJn?"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},jJn=e=>e?XBe(e):XBe,{useDebugValue:NJn}=qe,{useSyncExternalStoreWithSelector:IJn}=VIn,AJn=e=>e;function $_t(e,t=AJn,n){const r=IJn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return NJn(r),r}const JBe=(e,t)=>{const n=jJn(e),r=(s,a=t)=>$_t(n,s,a);return Object.assign(r,n),r},RJn=(e,t)=>e?JBe(e,t):JBe;function ro(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 RW=g.createContext(null),PJn=RW.Provider,M_t=_y.error001();function Ws(e,t){const n=g.useContext(RW);if(n===null)throw new Error(M_t);return $_t(n,e,t)}function Oo(){const e=g.useContext(RW);if(e===null)throw new Error(M_t);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const eUe={display:"none"},$Jn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},D_t="react-flow__node-desc",L_t="react-flow__edge-desc",MJn="react-flow__aria-live",DJn=e=>e.ariaLiveMessage,LJn=e=>e.ariaLabelConfig;function FJn({rfId:e}){const t=Ws(DJn);return o.jsx("div",{id:`${MJn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:$Jn,children:t})}function zJn({rfId:e,disableKeyboardA11y:t}){const n=Ws(LJn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${D_t}-${e}`,style:eUe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${L_t}-${e}`,style:eUe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(FJn,{rfId:e})]})}const vL=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Zl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});vL.displayName="Panel";function BJn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(vL,{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 UJn=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}},zF=e=>e.id;function qJn(e,t){return ro(e.selectedNodes.map(zF),t.selectedNodes.map(zF))&&ro(e.selectedEdges.map(zF),t.selectedEdges.map(zF))}function VJn({onSelectionChange:e}){const t=Oo(),{selectedNodes:n,selectedEdges:r}=Ws(UJn,qJn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const HJn=e=>!!e.onSelectionChangeHandlers;function WJn({onSelectionChange:e}){const t=Ws(HJn);return e||t?o.jsx(VJn,{onSelectionChange:e}):null}const aye=typeof window<"u"?g.useLayoutEffect:g.useEffect,F_t=[0,0],ZJn={x:0,y:0,zoom:1},GJn=["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"],tUe=[...GJn,"rfId"],QJn=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}),nUe={translateExtent:X2,nodeOrigin:F_t,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function YJn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Ws(QJn,ro),u=Oo();aye(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=nUe,l()}),[]);const d=g.useRef(nUe);return aye(()=>{for(const f of tUe){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:FXn(h)}):f==="fitView"?u.setState({fitViewQueued:h}):f==="fitViewOptions"?u.setState({fitViewOptions:h}):u.setState({[f]:h})))}d.current=e},tUe.map(f=>e[f])),null}function rUe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function KJn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=rUe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:rUe()?.matches?"dark":"light"}const sUe=typeof document<"u"?document:null;function rD(e=null,t={target:sUe,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 KWn(this):new GWn(this)}getCursor(t,n=0,r){let s=t.doc?t:gs.create({doc:t});return r==null&&(r=s.doc.length),this.regexp?uT(this,s,n,r):cT(this,s,n,r)}}class hCt{constructor(t){this.spec=t}}function WWn(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 cT(e,t,n,r){let s;return e.wholeWord&&(s=ZWn(t.doc,t.charCategorizer(t.selection.main.head))),e.test&&(s=WWn(e.test,t,s)),new Fx(t.doc,e.unquoted,n,r,e.caseSensitive?void 0:a=>a.toLowerCase(),s)}function ZWn(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(lU(s,n-a))!=bo.Word||t(cU(s,n-a))!=bo.Word)&&(t(cU(s,r-a))!=bo.Word||t(lU(s,r-a))!=bo.Word))}class GWn extends hCt{constructor(t){super(t)}nextMatch(t,n,r){let s=cT(this.spec,t,r,t.doc.length).nextOverlapping();if(s.done){let a=Math.min(t.doc.length,n+this.spec.unquoted.length);s=cT(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=cT(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=cT(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=cT(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 QWn(e,t,n){return(r,s,a)=>(!n||n(r,s,a))&&e(a[0],t,r,s)}function uT(e,t,n,r){let s;return e.wholeWord&&(s=YWn(t.charCategorizer(t.selection.main.head))),e.test&&(s=QWn(e.test,t,s)),new uCt(t.doc,e.search,{ignoreCase:!e.caseSensitive,test:s},n,r)}function lU(e,t){return e.slice(Tc(e,t,!1),t)}function cU(e,t){return e.slice(t,Tc(e,t))}function YWn(e){return(t,n,r)=>!r[0].length||(e(lU(r.input,r.index))!=bo.Word||e(cU(r.input,r.index))!=bo.Word)&&(e(cU(r.input,r.index+r[0].length))!=bo.Word||e(lU(r.input,r.index+r[0].length))!=bo.Word)}class KWn extends hCt{nextMatch(t,n,r){let s=uT(this.spec,t,r,t.doc.length).next();return s.done&&(s=uT(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=uT(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=uT(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=uT(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 H2=hr.define(),HOe=hr.define(),Jw=bl.define({create(e){return new _te(Vve(e).create(),null)},update(e,t){for(let n of t.effects)n.is(H2)?e=new _te(n.value.create(),e.panel):n.is(HOe)&&(e=new _te(e.query,n.value?WOe:null));return e},provide:e=>$2.from(e,t=>t.panel)});class _te{constructor(t,n){this.query=t,this.panel=n}}const XWn=Tn.mark({class:"cm-searchMatch"}),JWn=Tn.mark({class:"cm-searchMatch cm-searchMatch-selected"}),eZn=So.fromClass(class{constructor(e){this.view=e,this.decorations=this.highlight(e.state.field(Jw))}update(e){let t=e.state.field(Jw);(t!=e.startState.field(Jw)||e.docChanged||e.selectionSet||e.viewportChanged)&&(this.decorations=this.highlight(t))}highlight({query:e,panel:t}){if(!t||!e.spec.valid)return Tn.none;let{view:n}=this,r=new td;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?JWn:XWn)})}return r.finish()}},{decorations:e=>e.decorations});function uL(e){return t=>{let n=t.state.field(Jw,!1);return n&&n.query.spec.valid?e(t,n):gCt(t)}}const uU=uL((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($I);return e.dispatch({selection:s,effects:[ZOe(e,r),a.scrollToMatch(s.main,e)],userEvent:"select.search"}),mCt(e),!0}),dU=uL((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($I);return e.dispatch({selection:a,effects:[ZOe(e,s),i.scrollToMatch(a.main,e)],userEvent:"select.search"}),mCt(e),!0}),tZn=uL((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)}),nZn=({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 Fx(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},d7e=uL((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(At.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(ZOe(e,i)),d.push(n.facet($I).scrollToMatch(c.main,e))),e.dispatch({changes:f,selection:c,effects:d,userEvent:"input.replace"}),!0}),rZn=uL((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:At.announce.of(r),userEvent:"input.replace.all"}),!0});function WOe(e){return e.state.facet($I).createPanel(e)}function Vve(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($I);return new fCt({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 pCt(e){let t=lOe(e,WOe);return t&&t.dom.querySelector("[main-field]")}function mCt(e){let t=pCt(e);t&&t==e.root.activeElement&&t.select()}const gCt=e=>{let t=e.state.field(Jw,!1);if(t&&t.panel){let n=pCt(e);if(n&&n!=e.root.activeElement){let r=Vve(e.state,t.query.spec);r.valid&&e.dispatch({effects:H2.of(r)}),n.focus(),n.select()}}else e.dispatch({effects:[HOe.of(!0),t?H2.of(Vve(e.state,t.query.spec)):hr.appendConfig.of(oZn)]});return!0},vCt=e=>{let t=e.state.field(Jw,!1);if(!t||!t.panel)return!1;let n=lOe(e,WOe);return n&&n.dom.contains(e.root.activeElement)&&e.focus(),e.dispatch({effects:HOe.of(!1)}),!0},sZn=[{key:"Mod-f",run:gCt,scope:"editor search-panel"},{key:"F3",run:uU,shift:dU,scope:"editor search-panel",preventDefault:!0},{key:"Mod-g",run:uU,shift:dU,scope:"editor search-panel",preventDefault:!0},{key:"Escape",run:vCt,scope:"editor search-panel"},{key:"Mod-Shift-l",run:nZn},{key:"Mod-Alt-g",run:PWn},{key:"Mod-d",run:HWn,preventDefault:!0}];class aZn{constructor(t){this.view=t;let n=this.query=t.state.field(Jw).query.spec;this.commit=this.commit.bind(this),this.searchField=fi("input",{value:n.search,placeholder:ph(t,"Find"),"aria-label":ph(t,"Find"),class:"cm-textfield",name:"search",form:"","main-field":"true",onchange:this.commit,onkeyup:this.commit}),this.replaceField=fi("input",{value:n.replace,placeholder:ph(t,"Replace"),"aria-label":ph(t,"Replace"),class:"cm-textfield",name:"replace",form:"",onchange:this.commit,onkeyup:this.commit}),this.caseField=fi("input",{type:"checkbox",name:"case",form:"",checked:n.caseSensitive,onchange:this.commit}),this.reField=fi("input",{type:"checkbox",name:"re",form:"",checked:n.regexp,onchange:this.commit}),this.wordField=fi("input",{type:"checkbox",name:"word",form:"",checked:n.wholeWord,onchange:this.commit});function r(s,a,i){return fi("button",{class:"cm-button",name:s,onclick:a,type:"button"},i)}this.dom=fi("div",{onkeydown:s=>this.keydown(s),class:"cm-search"},[this.searchField,r("next",()=>uU(t),[ph(t,"next")]),r("prev",()=>dU(t),[ph(t,"previous")]),r("select",()=>tZn(t),[ph(t,"all")]),fi("label",null,[this.caseField,ph(t,"match case")]),fi("label",null,[this.reField,ph(t,"regexp")]),fi("label",null,[this.wordField,ph(t,"by word")]),...t.state.readOnly?[]:[fi("br"),this.replaceField,r("replace",()=>d7e(t),[ph(t,"replace")]),r("replaceAll",()=>rZn(t),[ph(t,"replace all")])],fi("button",{name:"close",onclick:()=>vCt(t),"aria-label":ph(t,"close"),type:"button"},["×"])])}commit(){let t=new fCt({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:H2.of(t)}))}keydown(t){_9n(this.view,t,"search-panel")?t.preventDefault():t.keyCode==13&&t.target==this.searchField?(t.preventDefault(),(t.shiftKey?dU:uU)(this.view)):t.keyCode==13&&t.target==this.replaceField&&(t.preventDefault(),d7e(this.view))}update(t){for(let n of t.transactions)for(let r of n.effects)r.is(H2)&&!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($I).top}}function ph(e,t){return e.state.phrase(t)}const NF=30,IF=/[\s\.,:;?!]/;function ZOe(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-NF),i=Math.min(s,n+NF),l=e.state.sliceDoc(a,i);if(a!=r.from){for(let c=0;c<NF;c++)if(!IF.test(l[c+1])&&IF.test(l[c])){l=l.slice(c);break}}if(i!=s){for(let c=l.length-1;c>l.length-NF;c--)if(!IF.test(l[c-1])&&IF.test(l[c])){l=l.slice(0,c);break}}return At.announce.of(`${e.state.phrase("current match")}. ${l} ${e.state.phrase("on line")} ${r.number}.`)}const iZn=At.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"}}),oZn=[Jw,ip.low(eZn),iZn];class f7e{constructor(t,n,r){this.from=t,this.to=n,this.diagnostic=r}}class Lk{constructor(t,n,r){this.diagnostics=t,this.panel=n,this.selected=r}static init(t,n,r){let s=r.facet(W2).markerFilter;s&&(t=s(t,r));let a=t.slice().sort((d,f)=>d.from-f.from||d.to-f.to),i=new td,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=xZn(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,Tn.widget({widget:new gZn(m),diagnostics:l.slice()}));else{let v=l.reduce((y,b)=>b.markClass?y+" "+b.markClass:y,"");i.add(h,p,Tn.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 Lk(u,n,cN(u))}}function cN(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 f7e(s,a,t||i.diagnostics[0]);else{if(i.diagnostics.indexOf(r.diagnostic)<0)return!1;r=new f7e(r.from,a,r.diagnostic)}}),r}function lZn(e,t){let n=t.pos,r=t.end||n,s=e.state.facet(W2).hideOn(e,n,r);if(s!=null)return s;let a=e.startState.doc.lineAt(t.pos);return!!(e.effects.some(i=>i.is(yCt))||e.changes.touchesRange(a.from,Math.max(a.to,r)))}function cZn(e,t){return e.field(Ph,!1)?t:t.concat(hr.appendConfig.of(wZn))}const yCt=hr.define(),GOe=hr.define(),bCt=hr.define(),Ph=bl.define({create(){return new Lk(Tn.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=cN(n,e.selected.diagnostic,a)||cN(n,null,a)}!n.size&&s&&t.state.facet(W2).autoPanel&&(s=null),e=new Lk(n,s,r)}for(let n of t.effects)if(n.is(yCt)){let r=t.state.facet(W2).autoPanel?n.value.length?Z2.open:null:e.panel;e=Lk.init(n.value,r,t.state)}else n.is(GOe)?e=new Lk(e.diagnostics,n.value?Z2.open:null,e.selected):n.is(bCt)&&(e=new Lk(e.diagnostics,e.panel,n.value));return e},provide:e=>[$2.from(e,t=>t.panel),At.decorations.from(e,t=>t.diagnostics)]}),uZn=Tn.mark({class:"cm-lintRange cm-lintRange-active"});function dZn(e,t,n){let{diagnostics:r}=e.state.field(Ph),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(W2).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:fZn(e,s)}}}:null}function fZn(e,t){return fi("ul",{class:"cm-tooltip-lint"},t.map(n=>wCt(e,n,!1)))}const hZn=e=>{let t=e.state.field(Ph,!1);(!t||!t.panel)&&e.dispatch({effects:cZn(e.state,[GOe.of(!0)])});let n=lOe(e,Z2.open);return n&&n.dom.querySelector(".cm-panel-lint ul").focus(),!0},h7e=e=>{let t=e.state.field(Ph,!1);return!t||!t.panel?!1:(e.dispatch({effects:GOe.of(!1)}),!0)},pZn=e=>{let t=e.state.field(Ph,!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)},mZn=[{key:"Mod-Shift-m",run:hZn,preventDefault:!0},{key:"F8",run:pZn}],W2=kn.define({combine(e){return{sources:e.map(t=>t.source).filter(t=>t!=null),...qy(e.map(t=>t.config),{delay:750,markerFilter:null,tooltipFilter:null,needsRefresh:null,hideOn:()=>null},{delay:Math.max,markerFilter:p7e,tooltipFilter:p7e,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 p7e(e,t){return e?t?(n,r)=>t(e(n,r),r):e:t}function xCt(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 wCt(e,t,n){var r;let s=n?xCt(t.actions):[];return fi("li",{class:"cm-diagnostic cm-diagnostic-"+t.severity},fi("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=cN(e.state.field(Ph).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),fi("u",u.slice(d,d+1)),u.slice(d+1)],h=a.markClass?" "+a.markClass:"";return fi("button",{type:"button",class:"cm-diagnosticAction"+h,onclick:c,onmousedown:c,"aria-label":` Action: ${u}${d<0?"":` (access key "${s[i]})"`}.`},f)}),t.source&&fi("div",{class:"cm-diagnosticSource"},t.source))}class gZn extends op{constructor(t){super(),this.sev=t}eq(t){return t.sev==this.sev}toDOM(){return fi("span",{class:"cm-lintPoint cm-lintPoint-"+this.sev})}}class m7e{constructor(t,n){this.diagnostic=n,this.id="item_"+Math.floor(Math.random()*4294967295).toString(16),this.dom=wCt(t,n,!0),this.dom.id=this.id,this.dom.setAttribute("role","option")}}class Z2{constructor(t){this.view=t,this.items=[];let n=s=>{if(s.keyCode==27)h7e(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=xCt(a.actions);for(let l=0;l<i.length;l++)if(i[l].toUpperCase().charCodeAt(0)==s.keyCode){let c=cN(this.view.state.field(Ph).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=fi("ul",{tabIndex:0,role:"listbox","aria-label":this.view.state.phrase("Diagnostics"),onkeydown:n,onclick:r}),this.dom=fi("div",{class:"cm-panel-lint"},this.list,fi("button",{type:"button",name:"close","aria-label":this.view.state.phrase("close"),onclick:()=>h7e(this.view)},"×")),this.update()}get selectedIndex(){let t=this.view.state.field(Ph).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(Ph),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 m7e(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 m7e(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(Ph),r=cN(n.diagnostics,this.items[t].diagnostic);r&&this.view.dispatch({selection:{anchor:r.from,head:r.to},scrollIntoView:!0,effects:bCt.of(r)})}static open(t){return new Z2(t)}}function vZn(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 AF(e){return vZn(`<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 yZn=At.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:AF("#d11")},".cm-lintRange-warning":{backgroundImage:AF("orange")},".cm-lintRange-info":{backgroundImage:AF("#999")},".cm-lintRange-hint":{backgroundImage:AF("#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 bZn(e){return e=="error"?4:e=="warning"?3:e=="info"?2:1}function xZn(e){let t="hint",n=1;for(let r of e){let s=bZn(r.severity);s>n&&(n=s,t=r.severity)}return t}const wZn=[Ph,At.decorations.compute([Ph],e=>{let{selected:t,panel:n}=e.field(Ph);return!t||!n||t.from==t.to?Tn.none:Tn.set([uZn.range(t.from,t.to)])}),p7n(dZn,{hideOn:lZn}),yZn];var g7e=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(uUn)),t.defaultKeymap!==!1&&(a=a.concat(IWn)),t.searchKeymap!==!1&&(a=a.concat(sZn)),t.historyKeymap!==!1&&(a=a.concat(LHn)),t.foldKeymap!==!1&&(a=a.concat(Q7n)),t.completionKeymap!==!1&&(a=a.concat(mkt)),t.lintKeymap!==!1&&(a=a.concat(mZn));var i=[];return t.lineNumbers!==!1&&i.push(M1t()),t.highlightActiveLineGutter!==!1&&i.push(T7n()),t.highlightSpecialChars!==!1&&i.push(U9n()),t.history!==!1&&i.push(jHn()),t.foldGutter!==!1&&i.push(J7n()),t.drawSelection!==!1&&i.push(A9n()),t.dropCursor!==!1&&i.push(D9n()),t.allowMultipleSelections!==!1&&i.push(gs.allowMultipleSelections.of(!0)),t.indentOnInput!==!1&&i.push(B7n()),t.syntaxHighlighting!==!1&&i.push(h1(rBn,{fallback:!0})),t.bracketMatching!==!1&&i.push(uBn()),t.closeBrackets!==!1&&i.push(iUn()),t.autocompletion!==!1&&i.push(pkt()),t.rectangularSelection!==!1&&i.push(n7n()),s!==!1&&i.push(a7n()),t.highlightActiveLine!==!1&&i.push(G9n()),t.highlightSelectionMatches!==!1&&i.push(DWn()),t.tabSize&&typeof t.tabSize=="number"&&i.push(II.of(" ".repeat(t.tabSize))),i.concat([NI.of(a.flat())]).filter(Boolean)};const SZn="#e5c07b",v7e="#e06c75",kZn="#56b6c2",OZn="#ffffff",c9="#abb2bf",Hve="#7d8799",CZn="#61afef",_Zn="#98c379",y7e="#d19a66",EZn="#c678dd",TZn="#21252b",b7e="#2c313a",x7e="#282c34",Ete="#353a42",jZn="#3E4451",w7e="#528bff",NZn=At.theme({"&":{color:c9,backgroundColor:x7e},".cm-content":{caretColor:w7e},".cm-cursor, .cm-dropCursor":{borderLeftColor:w7e},"&.cm-focused > .cm-scroller > .cm-selectionLayer .cm-selectionBackground, .cm-selectionBackground, .cm-content ::selection":{backgroundColor:jZn},".cm-panels":{backgroundColor:TZn,color:c9},".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:x7e,color:Hve,border:"none"},".cm-activeLineGutter":{backgroundColor:b7e},".cm-foldPlaceholder":{backgroundColor:"transparent",border:"none",color:"#ddd"},".cm-tooltip":{border:"none",backgroundColor:Ete},".cm-tooltip .cm-tooltip-arrow:before":{borderTopColor:"transparent",borderBottomColor:"transparent"},".cm-tooltip .cm-tooltip-arrow:after":{borderTopColor:Ete,borderBottomColor:Ete},".cm-tooltip-autocomplete":{"& > ul > li[aria-selected]":{backgroundColor:b7e,color:c9}}},{dark:!0}),IZn=Kg.define([{tag:fe.keyword,color:EZn},{tag:[fe.name,fe.deleted,fe.character,fe.propertyName,fe.macroName],color:v7e},{tag:[fe.function(fe.variableName),fe.labelName],color:CZn},{tag:[fe.color,fe.constant(fe.name),fe.standard(fe.name)],color:y7e},{tag:[fe.definition(fe.name),fe.separator],color:c9},{tag:[fe.typeName,fe.className,fe.number,fe.changed,fe.annotation,fe.modifier,fe.self,fe.namespace],color:SZn},{tag:[fe.operator,fe.operatorKeyword,fe.url,fe.escape,fe.regexp,fe.link,fe.special(fe.string)],color:kZn},{tag:[fe.meta,fe.comment],color:Hve},{tag:fe.strong,fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.link,color:Hve,textDecoration:"underline"},{tag:fe.heading,fontWeight:"bold",color:v7e},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:y7e},{tag:[fe.processingInstruction,fe.string,fe.inserted],color:_Zn},{tag:fe.invalid,color:OZn}]),AZn=[NZn,h1(IZn)];var RZn=At.theme({"&":{backgroundColor:"#fff"}},{dark:!1}),PZn=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(NI.of([AWn])),m&&(typeof m=="boolean"?v.unshift(g7e()):v.unshift(g7e(m))),h&&v.unshift(X9n(h)),d){case"light":v.push(RZn);break;case"dark":v.push(AZn);break;case"none":break;default:v.push(d);break}return i===!1&&v.push(At.editable.of(!1)),c&&v.push(gs.readOnly.of(!0)),[...v]},$Zn=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 MZn{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 S7e{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 Tte=null,DZn=()=>typeof window>"u"?new S7e:(Tte||(Tte=new S7e),Tte),LZn=At.theme({"& .cm-scroller":{height:"100% !important"}}),k7e=null,jte=null;function FZn(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===k7e||(k7e=i,jte=At.theme({"&":{height:e,minHeight:t,maxHeight:n,width:r,minWidth:s,maxWidth:a}})),jte}var O7e=Uy.define(),zZn=200,BZn=[];function UZn(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?BZn: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,E=_===void 0?null:_,T=e.placeholder,N=T===void 0?"":T,I=e.editable,A=I===void 0?!0:I,R=e.readOnly,L=R===void 0?!1:R,M=e.indentWithTab,B=M===void 0?!0:M,V=e.basicSetup,q=V===void 0?!0:V,F=e.root,H=e.initialState,D=g.useState(),G=D[0],z=D[1],$=g.useState(),U=$[0],W=$[1],Y=g.useState(),te=Y[0],ee=Y[1],J=g.useState(()=>({current:null}))[0],re=g.useState(()=>({current:null}))[0],le=FZn(p,v,b,w,O,E),X=At.updateListener.of(de=>{if(de.docChanged&&typeof r=="function"&&!de.transactions.some(he=>he.annotation(O7e))){J.current?J.current.reset():(J.current=new MZn(()=>{if(re.current){var he=re.current;re.current=null,he()}J.current=null},zZn),DZn().add(J.current));var ue=de.state.doc,ye=ue.toString();r(ye,de)}s&&s($Zn(de))}),ne=PZn({theme:f,editable:A,readOnly:L,placeholder:N,indentWithTab:B,basicSetup:q}),se=[X,...le?[le]:[],LZn,...ne];return i&&typeof i=="function"&&se.push(At.updateListener.of(i)),se=se.concat(c),g.useLayoutEffect(()=>{if(G&&!te){var de={doc:t,selection:n,extensions:se},ue=H?gs.fromJSON(H.json,de,H.fields):gs.create(de);if(ee(ue),!U){var ye=new At({state:ue,parent:G,root:F});W(ye),a&&a(ye,ue)}}return()=>{U&&(ee(void 0),W(void 0))}},[G,te]),g.useEffect(()=>{e.container&&z(e.container)},[e.container]),g.useEffect(()=>()=>{U&&(U.destroy(),W(void 0)),J.current&&(J.current.cancel(),J.current=null)},[U]),g.useEffect(()=>{u&&U&&U.focus()},[u,U]),g.useEffect(()=>{U&&U.dispatch({effects:hr.reconfigure.of(se)})},[f,c,p,v,b,w,O,E,N,A,L,B,q,r,i]),g.useEffect(()=>{if(t!==void 0){var de=U?U.state.doc.toString():"";if(U&&t!==de){var ue=J.current&&!J.current.isDone,ye=()=>{U&&t!==U.state.doc.toString()&&U.dispatch({changes:{from:0,to:U.state.doc.toString().length,insert:t||""},annotations:[O7e.of(!0)]})};ue?re.current=ye:ye()}}},[t,U]),{state:te,setState:ee,view:U,setView:W,container:G,setContainer:z}}var qZn=["className","value","selection","extensions","onChange","onStatistics","onCreateEditor","onUpdate","autoFocus","theme","height","minHeight","maxHeight","width","minWidth","maxWidth","basicSetup","placeholder","indentWithTab","editable","readOnly","root","initialState"],nd=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,E=e.indentWithTab,T=e.editable,N=e.readOnly,I=e.root,A=e.initialState,R=jOt(e,qZn),L=g.useRef(null),M=UZn({root:I,value:s,autoFocus:h,theme:m,height:v,minHeight:y,maxHeight:b,width:x,minWidth:w,maxWidth:k,basicSetup:O,placeholder:_,indentWithTab:E,editable:T,readOnly:N,selection:a,onChange:c,onStatistics:u,onCreateEditor:d,onUpdate:f,extensions:l,initialState:A}),B=M.state,V=M.view,q=M.container,F=M.setContainer;g.useImperativeHandle(t,()=>({editor:L.current,state:B,view:V}),[L,q,B,V]);var H=g.useCallback(G=>{L.current=G,F(G)},[F]);if(typeof s!="string")throw new Error("value must be typeof string but got "+typeof s);var D=typeof m=="string"?"cm-theme-"+m:"cm-theme";return o.jsx("div",oC({ref:H,className:""+D+(n?" "+n:"")},R))});nd.displayName="CodeMirror";const SCt={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 Nte=null;function VZn(){return Nte||(Nte=(async()=>{const[{createHighlighterCore:e},{createJavaScriptRegexEngine:t}]=await Promise.all([qa(()=>import("./core-DZ8VqGw4.js"),__vite__mapDeps([0,1,2]),import.meta.url),qa(()=>import("./engine-javascript-CSIo_1eZ.js"),__vite__mapDeps([3,1]),import.meta.url)]);return e({themes:[qa(()=>import("./github-light-DAi9KRSo.js"),[],import.meta.url),qa(()=>import("./github-dark-DHJKELXO.js"),[],import.meta.url)],langs:[qa(()=>import("./javascript-ySlJ1b_l.js"),[],import.meta.url),qa(()=>import("./typescript-Dj6nwHGl.js"),[],import.meta.url),qa(()=>import("./tsx-B6W0miNI.js"),[],import.meta.url),qa(()=>import("./jsx-BAng5TT0.js"),[],import.meta.url),qa(()=>import("./json-BQoSv7ci.js"),[],import.meta.url),qa(()=>import("./bash-atvbtKCR.js"),[],import.meta.url),qa(()=>import("./markdown-UIAJJxZW.js"),[],import.meta.url),qa(()=>import("./python-DhUJRlN_.js"),[],import.meta.url),qa(()=>import("./yaml-CVw76BM1.js"),[],import.meta.url),qa(()=>import("./diff-BgYniUM_.js"),[],import.meta.url),qa(()=>import("./css-BPhBrDlE.js"),[],import.meta.url),qa(()=>import("./html-C2L_23MC.js"),__vite__mapDeps([4,5,6]),import.meta.url),qa(()=>import("./xml-DGRTSKzu.js"),[],import.meta.url),qa(()=>import("./sql-COK4E0Yg.js"),[],import.meta.url)],engine:t()})})()),Nte}async function HZn(e,t){const n=SCt[t?.toLowerCase()];if(!n)return null;const r=await VZn(),{tokens:s}=r.codeToTokens(e,{lang:n,defaultColor:!1,themes:{light:"github-light",dark:"github-dark"}});return s}function WZn(e){const t=e?.split(".").pop()?.toLowerCase();return t?SCt[t]:void 0}function ZZn(e){return new rC(hOe.define(e))}const kCt=[mg.of({name:"JavaScript",alias:["ecmascript","js","node"],extensions:["js","mjs","cjs"],load(){return qa(()=>Promise.resolve().then(()=>TF),void 0,import.meta.url).then(e=>e.javascript())}}),mg.of({name:"JSON",alias:["json5"],extensions:["json","map"],load(){return qa(()=>Promise.resolve().then(()=>SBn),void 0,import.meta.url).then(e=>e.json())}}),mg.of({name:"JSX",extensions:["jsx"],load(){return qa(()=>Promise.resolve().then(()=>TF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0}))}}),mg.of({name:"Markdown",extensions:["md","markdown","mkd"],load(){return qa(()=>Promise.resolve().then(()=>gHn),void 0,import.meta.url).then(e=>e.markdown())}}),mg.of({name:"TSX",extensions:["tsx"],load(){return qa(()=>Promise.resolve().then(()=>TF),void 0,import.meta.url).then(e=>e.javascript({jsx:!0,typescript:!0}))}}),mg.of({name:"TypeScript",alias:["ts"],extensions:["ts","mts","cts"],load(){return qa(()=>Promise.resolve().then(()=>TF),void 0,import.meta.url).then(e=>e.javascript({typescript:!0}))}}),mg.of({name:"Shell",alias:["bash","sh","zsh"],extensions:["sh","ksh","bash"],filename:/^PKGBUILD$/,load(){return qa(()=>import("./shell-CjFT_Tl9.js"),[],import.meta.url).then(e=>ZZn(e.shell))}})];function GZn(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 QZn(e){const t=GZn(e);return pkt({override:[YZn(t)],defaultKeymap:!0,closeOnBlur:!0,icons:!1})}function YZn(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 KZn=/\{\{([a-zA-Z_][a-zA-Z0-9_]*(?:\.[a-zA-Z_][a-zA-Z0-9_]*)*)\}\}/g,XZn=Tn.mark({class:"cm-variable-highlight"}),C7e=new E1t({regexp:KZn,decoration:()=>XZn}),JZn=So.fromClass(class{decorations;constructor(e){this.decorations=C7e.createDeco(e)}update(e){this.decorations=C7e.updateDeco(e,this.decorations)}},{decorations:e=>e.decorations}),eGn=JZn;function tGn(){const e=RI({settings:{fontFamily:"var(--font-mono)",fontSize:"0.8rem",lineHighlight:"transparent",gutterBackground:"transparent",gutterForeground:"var(--neutral2)",background:"transparent",foreground:"var(--neutral6)",caret:"var(--neutral6)"},styles:[{tag:[fe.className,fe.propertyName],color:"var(--neutral6)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:fe.emphasis,fontStyle:"italic",color:"var(--neutral6)"},{tag:fe.strong,fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:fe.quote,fontStyle:"italic",color:"var(--neutral2)"}]}),t=At.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:"0.7rem",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 nGn(){const e=At.theme({"&":{backgroundColor:"transparent",color:"var(--neutral6)",fontSize:"0.8rem"},"&.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:"0.7rem",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=Kg.define([{tag:[fe.comment,fe.bracket],color:"var(--neutral2)"},{tag:[fe.string,fe.meta,fe.regexp],color:"var(--accent1)"},{tag:[fe.atom,fe.bool,fe.special(fe.variableName)],color:"var(--accent6)"},{tag:[fe.keyword,fe.operator,fe.tagName],color:"var(--accent2)"},{tag:[fe.function(fe.propertyName),fe.propertyName],color:"var(--accent5)"},{tag:[fe.definition(fe.variableName),fe.function(fe.variableName),fe.className,fe.attributeName],color:"var(--accent3)"},{tag:[fe.variableName,fe.number],color:"var(--accent5)"},{tag:[fe.name,fe.quote],color:"var(--accent1)"},{tag:fe.heading,color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.heading1,fe.heading2,fe.heading3,fe.heading4,fe.heading5,fe.heading6],color:"var(--accent3)",fontWeight:"bold"},{tag:[fe.emphasis],fontStyle:"italic",color:"var(--neutral6)"},{tag:[fe.strong],fontWeight:"bold",color:"var(--neutral6)"},{tag:fe.link,color:"var(--accent3)",textDecoration:"underline"},{tag:fe.url,color:"var(--accent3)"},{tag:fe.monospace,color:"var(--neutral6)"},{tag:fe.strikethrough,textDecoration:"line-through"},{tag:[fe.deleted],color:"var(--accent2)"},{tag:fe.invalid,color:"var(--error)"},{tag:[fe.standard(fe.tagName)],color:"var(--accent1)"}]);return[e,h1(t)]}const o0=()=>{const e=c_().resolvedTheme==="dark";return g.useMemo(()=>e?tGn():nGn(),[e])},rGn=io(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"}}),sGn=ip.highest(At.editorAttributes.of({style:"outline: none"})),aGn=ip.highest(At.theme({"&":{outline:"none"},"&.cm-focused":{outline:"none"},".cm-scroller":{outline:"none"},".cm-content":{outline:"none"},".cm-content:focus":{outline:"none"}})),iGn=[sGn,aGn],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=o0(),b=e?JSON.stringify(e,null,2):t??"",x=g.useMemo(()=>{const w=[...iGn];return f&&w.push(At.lineWrapping),a==="json"?w.push(Uh):a==="markdown"&&w.push(zOe({base:iC,codeLanguages:kCt})),i&&a==="markdown"&&w.push(eGn),c&&a==="markdown"&&w.push(QZn(c)),h===!1&&w.push(gs.readOnly.of(!0)),w},[a,i,c,h,f]);return o.jsxs("div",{className:K(rGn({variant:p}),s),...m,children:[r&&o.jsx(Da,{content:b,className:"absolute top-2 right-2 z-20"}),o.jsx(nd,{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}})]})}),oGn=e=>{try{return JSON.stringify(e??{},null,2)}catch{return"{}"}},lGn=({editorClassName:e="h-[240px] max-h-[40vh]",onSaved:t})=>{const n=o0(),{settings:r,setSettings:s}=YH(),a=r?.tracingOptions,i=g.useMemo(()=>oGn(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(nd,{value:l,onChange:d,theme:n,extensions:[Uh],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(oe,{type:"button",onClick:f,children:"Save"})})]})},cGn=()=>{const[e,t]=g.useState(!1);return o.jsxs(o.Fragment,{children:[o.jsxs(gn,{children:[o.jsx(fn,{asChild:!0,children:o.jsx(oe,{type:"button",variant:"ghost",size:"icon-md","aria-label":"Run Options",onClick:()=>t(!0),children:o.jsx(Je,{children:o.jsx(nwe,{})})})}),o.jsx(hn,{children:"Run Options"})]}),o.jsx(vr,{open:e,onOpenChange:t,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(fr,{children:"Run Options"}),o.jsx($s,{children:"Configure tracing and debug options for this workflow run"})]}),o.jsx(Pr,{children:o.jsx(lGn,{onSaved:()=>t(!1)})})]})})]})};function uGn({status:e}){switch(e){case"running":return o.jsx(Vt,{});case"failed":return o.jsx(or,{className:"text-accent2"});case"canceled":return o.jsx(ks,{className:"text-neutral3"});case"pending":case"waiting":return o.jsx(lS,{className:"text-neutral3"});case"suspended":return o.jsx(FV,{className:"text-accent3"});case"success":return o.jsx(Dr,{className:"text-accent1"});default:return o.jsx(lS,{className:"text-neutral3"})}}function OCt({status:e}){return o.jsxs(gn,{children:[o.jsx(fn,{asChild:!0,children:o.jsx(Je,{"aria-label":e,className:"shrink-0",children:o.jsx(uGn,{status:e})})}),o.jsx(hn,{children:e})]})}var Ite,_7e;function QOe(){if(_7e)return Ite;_7e=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 Ite=r,Ite}var Ate,E7e;function dGn(){return E7e||(E7e=1,Ate="2.2.4"),Ate}var Rte,T7e;function fGn(){return T7e||(T7e=1,Rte={Graph:QOe(),version:dGn()}),Rte}var Pte,j7e;function hGn(){if(j7e)return Pte;j7e=1;var e=QOe();Pte={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 Pte}var $te,N7e;function pGn(){if(N7e)return $te;N7e=1,$te=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 $te}var Mte,I7e;function CCt(){if(I7e)return Mte;I7e=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 Mte=e,Mte}var Dte,A7e;function _Ct(){if(A7e)return Dte;A7e=1;var e=CCt();Dte=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 Dte}var Lte,R7e;function mGn(){if(R7e)return Lte;R7e=1;var e=_Ct();Lte=t;function t(n,r,s){return n.nodes().reduce(function(a,i){return a[i]=e(n,i,r,s),a},{})}return Lte}var Fte,P7e;function ECt(){if(P7e)return Fte;P7e=1,Fte=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 Fte}var zte,$7e;function gGn(){if($7e)return zte;$7e=1;var e=ECt();zte=t;function t(n){return e(n).filter(function(r){return r.length>1||r.length===1&&n.hasEdge(r[0],r[0])})}return zte}var Bte,M7e;function vGn(){if(M7e)return Bte;M7e=1,Bte=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 Bte}var Ute,D7e;function TCt(){if(D7e)return Ute;D7e=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 Ute=e,e.CycleException=t,Ute}var qte,L7e;function yGn(){if(L7e)return qte;L7e=1;var e=TCt();qte=t;function t(n){try{e(n)}catch(r){if(r instanceof e.CycleException)return!1;throw r}return!0}return qte}var Vte,F7e;function jCt(){if(F7e)return Vte;F7e=1,Vte=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 Vte}var Hte,z7e;function bGn(){if(z7e)return Hte;z7e=1;var e=jCt();Hte=t;function t(n,r){return e(n,r,"post")}return Hte}var Wte,B7e;function xGn(){if(B7e)return Wte;B7e=1;var e=jCt();Wte=t;function t(n,r){return e(n,r,"pre")}return Wte}var Zte,U7e;function wGn(){if(U7e)return Zte;U7e=1;var e=QOe(),t=CCt();Zte=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 Zte}var Gte,q7e;function SGn(){return q7e||(q7e=1,Gte={components:pGn(),dijkstra:_Ct(),dijkstraAll:mGn(),findCycles:gGn(),floydWarshall:vGn(),isAcyclic:yGn(),postorder:bGn(),preorder:xGn(),prim:wGn(),tarjan:ECt(),topsort:TCt()}),Gte}var Qte,V7e;function Vg(){if(V7e)return Qte;V7e=1;var e=fGn();return Qte={Graph:e.Graph,json:hGn(),alg:SGn(),version:e.version},Qte}var Yte,H7e;function kGn(){if(H7e)return Yte;H7e=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 Yte=e,Yte}var Kte,W7e;function OGn(){if(W7e)return Kte;W7e=1;let e=Vg().Graph,t=kGn();Kte=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 Kte}var Xte,Z7e;function $l(){if(Z7e)return Xte;Z7e=1;let e=Vg().Graph;Xte={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:E};function t(T,N,I,A){for(var R=A;T.hasNode(R);)R=w(A);return I.dummy=N,T.setNode(R,I),R}function n(T){let N=new e().setGraph(T.graph());return T.nodes().forEach(I=>N.setNode(I,T.node(I))),T.edges().forEach(I=>{let A=N.edge(I.v,I.w)||{weight:0,minlen:1},R=T.edge(I);N.setEdge(I.v,I.w,{weight:A.weight+R.weight,minlen:Math.max(A.minlen,R.minlen)})}),N}function r(T){let N=new e({multigraph:T.isMultigraph()}).setGraph(T.graph());return T.nodes().forEach(I=>{T.children(I).length||N.setNode(I,T.node(I))}),T.edges().forEach(I=>{N.setEdge(I,T.edge(I))}),N}function s(T){let N=T.nodes().map(I=>{let A={};return T.outEdges(I).forEach(R=>{A[R.w]=(A[R.w]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function a(T){let N=T.nodes().map(I=>{let A={};return T.inEdges(I).forEach(R=>{A[R.v]=(A[R.v]||0)+T.edge(R).weight}),A});return E(T.nodes(),N)}function i(T,N){let I=T.x,A=T.y,R=N.x-I,L=N.y-A,M=T.width/2,B=T.height/2;if(!R&&!L)throw new Error("Not possible to find intersection inside of the rectangle");let V,q;return Math.abs(L)*M>Math.abs(R)*B?(L<0&&(B=-B),V=B*R/L,q=B):(R<0&&(M=-M),V=M,q=M*L/R),{x:I+V,y:A+q}}function l(T){let N=k(m(T)+1).map(()=>[]);return T.nodes().forEach(I=>{let A=T.node(I),R=A.rank;R!==void 0&&(N[R][A.order]=I)}),N}function c(T){let N=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MAX_VALUE:R}),I=p(Math.min,N);T.nodes().forEach(A=>{let R=T.node(A);Object.hasOwn(R,"rank")&&(R.rank-=I)})}function u(T){let N=T.nodes().map(M=>T.node(M).rank),I=p(Math.min,N),A=[];T.nodes().forEach(M=>{let B=T.node(M).rank-I;A[B]||(A[B]=[]),A[B].push(M)});let R=0,L=T.graph().nodeRankFactor;Array.from(A).forEach((M,B)=>{M===void 0&&B%L!==0?--R:M!==void 0&&R&&M.forEach(V=>T.node(V).rank+=R)})}function d(T,N,I,A){let R={width:0,height:0};return arguments.length>=4&&(R.rank=I,R.order=A),t(T,"border",R,N)}function f(T,N=h){const I=[];for(let A=0;A<T.length;A+=N){const R=T.slice(A,A+N);I.push(R)}return I}const h=65535;function p(T,N){if(N.length>h){const I=f(N);return T.apply(null,I.map(A=>T.apply(null,A)))}else return T.apply(null,N)}function m(T){const I=T.nodes().map(A=>{let R=T.node(A).rank;return R===void 0?Number.MIN_VALUE:R});return p(Math.max,I)}function v(T,N){let I={lhs:[],rhs:[]};return T.forEach(A=>{N(A)?I.lhs.push(A):I.rhs.push(A)}),I}function y(T,N){let I=Date.now();try{return N()}finally{console.log(T+" time: "+(Date.now()-I)+"ms")}}function b(T,N){return N()}let x=0;function w(T){var N=++x;return T+(""+N)}function k(T,N,I=1){N==null&&(N=T,T=0);let A=L=>L<N;I<0&&(A=L=>N<L);const R=[];for(let L=T;A(L);L+=I)R.push(L);return R}function O(T,N){const I={};for(const A of N)T[A]!==void 0&&(I[A]=T[A]);return I}function _(T,N){let I=N;return typeof N=="string"&&(I=A=>A[N]),Object.entries(T).reduce((A,[R,L])=>(A[R]=I(L,R),A),{})}function E(T,N){return T.reduce((I,A,R)=>(I[A]=N[R],I),{})}return Xte}var Jte,G7e;function CGn(){if(G7e)return Jte;G7e=1;let e=OGn(),t=$l().uniqueId;Jte={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 Jte}var ene,Q7e;function _Gn(){if(Q7e)return ene;Q7e=1;let e=$l();ene={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 ene}var tne,Y7e;function fU(){if(Y7e)return tne;Y7e=1;const{applyWithChunking:e}=$l();tne={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 tne}var nne,K7e;function NCt(){if(K7e)return nne;K7e=1;var e=Vg().Graph,t=fU().slack;nne=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 nne}var rne,X7e;function EGn(){if(X7e)return rne;X7e=1;var e=NCt(),t=fU().slack,n=fU().longestPath,r=Vg().alg.preorder,s=Vg().alg.postorder,a=$l().simplify;rne=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,E=!0,T=w.edge(k,_),N=0;return T||(E=!1,T=w.edge(_,k)),N=T.weight,w.nodeEdges(k).forEach(I=>{var A=I.v===k,R=A?I.w:I.v;if(R!==_){var L=A===E,M=w.edge(I).weight;if(N+=L?M:-M,y(x,k,R)){var B=x.edge(k,R).cutvalue;N+=L?-B:B}}}),N}function d(x,w){arguments.length<2&&(w=x.nodes()[0]),f(x,{},1,w)}function f(x,w,k,O,_){var E=k,T=x.node(O);return w[O]=!0,x.neighbors(O).forEach(N=>{Object.hasOwn(w,N)||(k=f(x,w,k,N,O))}),T.low=E,T.lim=k++,_?T.parent=_:delete T.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 E=x.node(O),T=x.node(_),N=E,I=!1;E.lim>T.lim&&(N=T,I=!0);var A=w.edges().filter(R=>I===b(x,x.node(R.v),N)&&I!==b(x,x.node(R.w),N));return A.reduce((R,L)=>t(w,L)<t(w,R)?L:R)}function m(x,w,k,O){var _=k.v,E=k.w;x.removeEdge(_,E),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 E=x.node(_).parent,T=w.edge(_,E),N=!1;T||(T=w.edge(E,_),N=!0),w.node(_).rank=w.node(E).rank+(N?T.minlen:-T.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 rne}var sne,J7e;function TGn(){if(J7e)return sne;J7e=1;var e=fU(),t=e.longestPath,n=NCt(),r=EGn();sne=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 sne}var ane,eBe;function jGn(){if(eBe)return ane;eBe=1,ane=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 ane}var ine,tBe;function NGn(){if(tBe)return ine;tBe=1;let e=$l();ine={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 ine}var one,nBe;function IGn(){if(nBe)return one;nBe=1;let e=$l();one=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 one}var lne,rBe;function AGn(){if(rBe)return lne;rBe=1,lne={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 lne}var cne,sBe;function RGn(){if(sBe)return cne;sBe=1;let e=$l();cne=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 cne}var une,aBe;function PGn(){if(aBe)return une;aBe=1;let e=$l().zipObject;une=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 une}var dne,iBe;function $Gn(){if(iBe)return dne;iBe=1,dne=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 dne}var fne,oBe;function MGn(){if(oBe)return fne;oBe=1;let e=$l();fne=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 fne}var hne,lBe;function DGn(){if(lBe)return hne;lBe=1;let e=$l();hne=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 hne}var pne,cBe;function LGn(){if(cBe)return pne;cBe=1;let e=$Gn(),t=MGn(),n=DGn();pne=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 pne}var mne,uBe;function FGn(){if(uBe)return mne;uBe=1;let e=Vg().Graph,t=$l();mne=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 mne}var gne,dBe;function zGn(){if(dBe)return gne;dBe=1,gne=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 gne}var vne,fBe;function BGn(){if(fBe)return vne;fBe=1;let e=RGn(),t=PGn(),n=LGn(),r=FGn(),s=zGn(),a=Vg().Graph,i=$l();vne=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 vne}var yne,hBe;function UGn(){if(hBe)return yne;hBe=1;let e=Vg().Graph,t=$l();yne={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,E=0,T=k.length,N=O[O.length-1];return O.forEach((I,A)=>{let R=s(y,I),L=R?y.node(R).order:T;(R||I===N)&&(O.slice(E,A+1).forEach(M=>{y.predecessors(M).forEach(B=>{let V=y.node(B),q=V.order;(q<_||L<q)&&!(V.dummy&&y.node(M).dummy)&&a(x,B,M)})}),E=A+1,_=L)}),O}return b.length&&b.reduce(w),x}function r(y,b){let x={};function w(O,_,E,T,N){let I;t.range(_,E).forEach(A=>{I=O[A],y.node(I).dummy&&y.predecessors(I).forEach(R=>{let L=y.node(R);L.dummy&&(L.order<T||L.order>N)&&a(x,R,I)})})}function k(O,_){let E=-1,T,N=0;return _.forEach((I,A)=>{if(y.node(I).dummy==="border"){let R=y.predecessors(I);R.length&&(T=y.node(R[0]).order,w(_,N,A,E,T),N=A,E=T)}w(_,N,_.length,T,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(E=>{E.forEach((T,N)=>{k[T]=T,O[T]=T,_[T]=N})}),b.forEach(E=>{let T=-1;E.forEach(N=>{let I=w(N);if(I.length){I=I.sort((R,L)=>_[R]-_[L]);let A=(I.length-1)/2;for(let R=Math.floor(A),L=Math.ceil(A);R<=L;++R){let M=I[R];O[N]===N&&T<_[M]&&!i(x,N,M)&&(O[M]=N,O[N]=k[N]=k[M],T=_[M])}}})}),{root:k,align:O}}function c(y,b,x,w,k){let O={},_=u(y,b,x,k),E=k?"borderLeft":"borderRight";function T(A,R){let L=_.nodes(),M=L.pop(),B={};for(;M;)B[M]?A(M):(B[M]=!0,L.push(M),L=L.concat(R(M))),M=L.pop()}function N(A){O[A]=_.inEdges(A).reduce((R,L)=>Math.max(R,O[L.v]+_.edge(L)),0)}function I(A){let R=_.outEdges(A).reduce((M,B)=>Math.min(M,O[B.w]-_.edge(B)),Number.POSITIVE_INFINITY),L=y.node(A);R!==Number.POSITIVE_INFINITY&&L.borderType!==E&&(O[A]=Math.max(O[A],R))}return T(N,_.predecessors.bind(_)),T(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(E=>{let T;E.forEach(N=>{let I=x[N];if(k.setNode(I),T){var A=x[T],R=k.edge(A,I);k.setEdge(A,I,Math.max(_(y,N,T),R||0))}T=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(([E,T])=>{let N=v(y,E)/2;k=Math.max(T+N,k),O=Math.min(T-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 E=O+_,T=y[E];if(T===b)return;let N=Object.values(T),I=w-t.applyWithChunking(Math.min,N);_!=="l"&&(I=k-t.applyWithChunking(Math.max,N)),I&&(y[E]=t.mapValues(T,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(E=>{E==="r"&&(k=k.map(A=>Object.values(A).reverse()));let T=(_==="u"?y.predecessors:y.successors).bind(y),N=l(y,k,x,T),I=c(y,k,N.root,N.align,E==="r");E==="r"&&(I=t.mapValues(I,A=>-A)),w[_+E]=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),E=w.node(O),T=0,N;if(T+=_.width/2,Object.hasOwn(_,"labelpos"))switch(_.labelpos.toLowerCase()){case"l":N=-_.width/2;break;case"r":N=_.width/2;break}if(N&&(T+=x?N:-N),N=0,T+=(_.dummy?b:y)/2,T+=(E.dummy?b:y)/2,T+=E.width/2,Object.hasOwn(E,"labelpos"))switch(E.labelpos.toLowerCase()){case"l":N=E.width/2;break;case"r":N=-E.width/2;break}return N&&(T+=x?N:-N),N=0,T}}function v(y,b){return y.node(b).width}return yne}var bne,pBe;function qGn(){if(pBe)return bne;pBe=1;let e=$l(),t=UGn().positionX;bne=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 bne}var xne,mBe;function VGn(){if(mBe)return xne;mBe=1;let e=CGn(),t=_Gn(),n=TGn(),r=$l().normalizeRanks,s=jGn(),a=$l().removeEmptyRanks,i=NGn(),l=IGn(),c=AGn(),u=BGn(),d=qGn(),f=$l(),h=Vg().Graph;xne=p;function p($,U){let W=U&&U.debugTiming?f.time:f.notime;W("layout",()=>{let Y=W(" buildLayoutGraph",()=>T($));W(" runLayout",()=>m(Y,W,U)),W(" updateInputGraph",()=>v($,Y))})}function m($,U,W){U(" makeSpaceForEdgeLabels",()=>N($)),U(" removeSelfEdges",()=>F($)),U(" acyclic",()=>e.run($)),U(" nestingGraph.run",()=>i.run($)),U(" rank",()=>n(f.asNonCompoundGraph($))),U(" injectEdgeLabelProxies",()=>I($)),U(" removeEmptyRanks",()=>a($)),U(" nestingGraph.cleanup",()=>i.cleanup($)),U(" normalizeRanks",()=>r($)),U(" assignRankMinMax",()=>A($)),U(" removeEdgeLabelProxies",()=>R($)),U(" normalize.run",()=>t.run($)),U(" parentDummyChains",()=>s($)),U(" addBorderSegments",()=>l($)),U(" order",()=>u($,W)),U(" insertSelfEdges",()=>H($)),U(" adjustCoordinateSystem",()=>c.adjust($)),U(" position",()=>d($)),U(" positionSelfEdges",()=>D($)),U(" removeBorderNodes",()=>q($)),U(" normalize.undo",()=>t.undo($)),U(" fixupEdgeLabelCoords",()=>B($)),U(" undoCoordinateSystem",()=>c.undo($)),U(" translateGraph",()=>L($)),U(" assignNodeIntersects",()=>M($)),U(" reversePoints",()=>V($)),U(" acyclic.undo",()=>e.undo($))}function v($,U){$.nodes().forEach(W=>{let Y=$.node(W),te=U.node(W);Y&&(Y.x=te.x,Y.y=te.y,Y.rank=te.rank,U.children(W).length&&(Y.width=te.width,Y.height=te.height))}),$.edges().forEach(W=>{let Y=$.edge(W),te=U.edge(W);Y.points=te.points,Object.hasOwn(te,"x")&&(Y.x=te.x,Y.y=te.y)}),$.graph().width=U.graph().width,$.graph().height=U.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"},E=["labelpos"];function T($){let U=new h({multigraph:!0,compound:!0}),W=z($.graph());return U.setGraph(Object.assign({},b,G(W,y),f.pick(W,x))),$.nodes().forEach(Y=>{let te=z($.node(Y));const ee=G(te,w);Object.keys(k).forEach(J=>{ee[J]===void 0&&(ee[J]=k[J])}),U.setNode(Y,ee),U.setParent(Y,$.parent(Y))}),$.edges().forEach(Y=>{let te=z($.edge(Y));U.setEdge(Y,Object.assign({},_,G(te,O),f.pick(te,E)))}),U}function N($){let U=$.graph();U.ranksep/=2,$.edges().forEach(W=>{let Y=$.edge(W);Y.minlen*=2,Y.labelpos.toLowerCase()!=="c"&&(U.rankdir==="TB"||U.rankdir==="BT"?Y.width+=Y.labeloffset:Y.height+=Y.labeloffset)})}function I($){$.edges().forEach(U=>{let W=$.edge(U);if(W.width&&W.height){let Y=$.node(U.v),ee={rank:($.node(U.w).rank-Y.rank)/2+Y.rank,e:U};f.addDummyNode($,"edge-proxy",ee,"_ep")}})}function A($){let U=0;$.nodes().forEach(W=>{let Y=$.node(W);Y.borderTop&&(Y.minRank=$.node(Y.borderTop).rank,Y.maxRank=$.node(Y.borderBottom).rank,U=Math.max(U,Y.maxRank))}),$.graph().maxRank=U}function R($){$.nodes().forEach(U=>{let W=$.node(U);W.dummy==="edge-proxy"&&($.edge(W.e).labelRank=W.rank,$.removeNode(U))})}function L($){let U=Number.POSITIVE_INFINITY,W=0,Y=Number.POSITIVE_INFINITY,te=0,ee=$.graph(),J=ee.marginx||0,re=ee.marginy||0;function le(X){let ne=X.x,se=X.y,de=X.width,ue=X.height;U=Math.min(U,ne-de/2),W=Math.max(W,ne+de/2),Y=Math.min(Y,se-ue/2),te=Math.max(te,se+ue/2)}$.nodes().forEach(X=>le($.node(X))),$.edges().forEach(X=>{let ne=$.edge(X);Object.hasOwn(ne,"x")&&le(ne)}),U-=J,Y-=re,$.nodes().forEach(X=>{let ne=$.node(X);ne.x-=U,ne.y-=Y}),$.edges().forEach(X=>{let ne=$.edge(X);ne.points.forEach(se=>{se.x-=U,se.y-=Y}),Object.hasOwn(ne,"x")&&(ne.x-=U),Object.hasOwn(ne,"y")&&(ne.y-=Y)}),ee.width=W-U+J,ee.height=te-Y+re}function M($){$.edges().forEach(U=>{let W=$.edge(U),Y=$.node(U.v),te=$.node(U.w),ee,J;W.points?(ee=W.points[0],J=W.points[W.points.length-1]):(W.points=[],ee=te,J=Y),W.points.unshift(f.intersectRect(Y,ee)),W.points.push(f.intersectRect(te,J))})}function B($){$.edges().forEach(U=>{let W=$.edge(U);if(Object.hasOwn(W,"x"))switch((W.labelpos==="l"||W.labelpos==="r")&&(W.width-=W.labeloffset),W.labelpos){case"l":W.x-=W.width/2+W.labeloffset;break;case"r":W.x+=W.width/2+W.labeloffset;break}})}function V($){$.edges().forEach(U=>{let W=$.edge(U);W.reversed&&W.points.reverse()})}function q($){$.nodes().forEach(U=>{if($.children(U).length){let W=$.node(U),Y=$.node(W.borderTop),te=$.node(W.borderBottom),ee=$.node(W.borderLeft[W.borderLeft.length-1]),J=$.node(W.borderRight[W.borderRight.length-1]);W.width=Math.abs(J.x-ee.x),W.height=Math.abs(te.y-Y.y),W.x=ee.x+W.width/2,W.y=Y.y+W.height/2}}),$.nodes().forEach(U=>{$.node(U).dummy==="border"&&$.removeNode(U)})}function F($){$.edges().forEach(U=>{if(U.v===U.w){var W=$.node(U.v);W.selfEdges||(W.selfEdges=[]),W.selfEdges.push({e:U,label:$.edge(U)}),$.removeEdge(U)}})}function H($){var U=f.buildLayerMatrix($);U.forEach(W=>{var Y=0;W.forEach((te,ee)=>{var J=$.node(te);J.order=ee+Y,(J.selfEdges||[]).forEach(re=>{f.addDummyNode($,"selfedge",{width:re.label.width,height:re.label.height,rank:J.rank,order:ee+ ++Y,e:re.e,label:re.label},"_se")}),delete J.selfEdges})})}function D($){$.nodes().forEach(U=>{var W=$.node(U);if(W.dummy==="selfedge"){var Y=$.node(W.e.v),te=Y.x+Y.width/2,ee=Y.y,J=W.x-te,re=Y.height/2;$.setEdge(W.e,W.label),$.removeNode(U),W.label.points=[{x:te+2*J/3,y:ee-re},{x:te+5*J/6,y:ee-re},{x:te+J,y:ee},{x:te+5*J/6,y:ee+re},{x:te+2*J/3,y:ee+re}],W.label.x=W.x,W.label.y=W.y}})}function G($,U){return f.mapValues(f.pick($,U),Number)}function z($){var U={};return $&&Object.entries($).forEach(([W,Y])=>{typeof W=="string"&&(W=W.toLowerCase()),U[W]=Y}),U}return xne}var wne,gBe;function HGn(){if(gBe)return wne;gBe=1;let e=$l(),t=Vg().Graph;wne={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 wne}var Sne,vBe;function WGn(){return vBe||(vBe=1,Sne="1.1.8"),Sne}var kne,yBe;function ZGn(){return yBe||(yBe=1,kne={graphlib:Vg(),layout:VGn(),debug:HGn(),util:{time:$l().time,notime:$l().notime},version:WGn()}),kne}var GGn=ZGn();const bBe=ql(GGn);function Zl(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=Zl(e[n]))!==""&&(t+=(t&&" ")+r);else for(let n in e)e[n]&&(t+=(t&&" ")+n);return t}var QGn={value:()=>{}};function CW(){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 u9(n)}function u9(e){this._=e}function YGn(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}})}u9.prototype=CW.prototype={constructor:u9,on:function(e,t){var n=this._,r=YGn(e+"",n),s,a=-1,i=r.length;if(arguments.length<2){for(;++a<i;)if((s=(e=r[a]).type)&&(s=KGn(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]=xBe(n[s],e.name,t);else if(t==null)for(s in n)n[s]=xBe(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 u9(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 KGn(e,t){for(var n=0,r=e.length,s;n<r;++n)if((s=e[n]).name===t)return s.value}function xBe(e,t,n){for(var r=0,s=e.length;r<s;++r)if(e[r].name===t){e[r]=QGn,e=e.slice(0,r).concat(e.slice(r+1));break}return n!=null&&e.push({name:t,value:n}),e}var Wve="http://www.w3.org/1999/xhtml";const wBe={svg:"http://www.w3.org/2000/svg",xhtml:Wve,xlink:"http://www.w3.org/1999/xlink",xml:"http://www.w3.org/XML/1998/namespace",xmlns:"http://www.w3.org/2000/xmlns/"};function _W(e){var t=e+="",n=t.indexOf(":");return n>=0&&(t=e.slice(0,n))!=="xmlns"&&(e=e.slice(n+1)),wBe.hasOwnProperty(t)?{space:wBe[t],local:e}:e}function XGn(e){return function(){var t=this.ownerDocument,n=this.namespaceURI;return n===Wve&&t.documentElement.namespaceURI===Wve?t.createElement(e):t.createElementNS(n,e)}}function JGn(e){return function(){return this.ownerDocument.createElementNS(e.space,e.local)}}function ICt(e){var t=_W(e);return(t.local?JGn:XGn)(t)}function eQn(){}function YOe(e){return e==null?eQn:function(){return this.querySelector(e)}}function tQn(e){typeof e!="function"&&(e=YOe(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 ep(r,this._parents)}function nQn(e){return e==null?[]:Array.isArray(e)?e:Array.from(e)}function rQn(){return[]}function ACt(e){return e==null?rQn:function(){return this.querySelectorAll(e)}}function sQn(e){return function(){return nQn(e.apply(this,arguments))}}function aQn(e){typeof e=="function"?e=sQn(e):e=ACt(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 ep(r,s)}function RCt(e){return function(){return this.matches(e)}}function PCt(e){return function(t){return t.matches(e)}}var iQn=Array.prototype.find;function oQn(e){return function(){return iQn.call(this.children,e)}}function lQn(){return this.firstElementChild}function cQn(e){return this.select(e==null?lQn:oQn(typeof e=="function"?e:PCt(e)))}var uQn=Array.prototype.filter;function dQn(){return Array.from(this.children)}function fQn(e){return function(){return uQn.call(this.children,e)}}function hQn(e){return this.selectAll(e==null?dQn:fQn(typeof e=="function"?e:PCt(e)))}function pQn(e){typeof e!="function"&&(e=RCt(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 ep(r,this._parents)}function $Ct(e){return new Array(e.length)}function mQn(){return new ep(this._enter||this._groups.map($Ct),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 gQn(e){return function(){return e}}function vQn(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 yQn(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 bQn(e){return e.__data__}function xQn(e,t){if(!arguments.length)return Array.from(this,bQn);var n=t?yQn:vQn,r=this._parents,s=this._groups;typeof e!="function"&&(e=gQn(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=wQn(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 ep(i,r),i._enter=l,i._exit=c,i}function wQn(e){return typeof e=="object"&&"length"in e?e:Array.from(e)}function SQn(){return new ep(this._exit||this._groups.map($Ct),this._parents)}function kQn(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 OQn(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 ep(l,this._parents)}function CQn(){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 _Qn(e){e||(e=EQn);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 ep(s,this._parents).order()}function EQn(e,t){return e<t?-1:e>t?1:e>=t?0:NaN}function TQn(){var e=arguments[0];return arguments[0]=this,e.apply(null,arguments),this}function jQn(){return Array.from(this)}function NQn(){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 IQn(){let e=0;for(const t of this)++e;return e}function AQn(){return!this.node()}function RQn(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 PQn(e){return function(){this.removeAttribute(e)}}function $Qn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function MQn(e,t){return function(){this.setAttribute(e,t)}}function DQn(e,t){return function(){this.setAttributeNS(e.space,e.local,t)}}function LQn(e,t){return function(){var n=t.apply(this,arguments);n==null?this.removeAttribute(e):this.setAttribute(e,n)}}function FQn(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 zQn(e,t){var n=_W(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?$Qn:PQn:typeof t=="function"?n.local?FQn:LQn:n.local?DQn:MQn)(n,t))}function MCt(e){return e.ownerDocument&&e.ownerDocument.defaultView||e.document&&e||e.defaultView}function BQn(e){return function(){this.style.removeProperty(e)}}function UQn(e,t,n){return function(){this.style.setProperty(e,t,n)}}function qQn(e,t,n){return function(){var r=t.apply(this,arguments);r==null?this.style.removeProperty(e):this.style.setProperty(e,r,n)}}function VQn(e,t,n){return arguments.length>1?this.each((t==null?BQn:typeof t=="function"?qQn:UQn)(e,t,n??"")):uN(this.node(),e)}function uN(e,t){return e.style.getPropertyValue(t)||MCt(e).getComputedStyle(e,null).getPropertyValue(t)}function HQn(e){return function(){delete this[e]}}function WQn(e,t){return function(){this[e]=t}}function ZQn(e,t){return function(){var n=t.apply(this,arguments);n==null?delete this[e]:this[e]=n}}function GQn(e,t){return arguments.length>1?this.each((t==null?HQn:typeof t=="function"?ZQn:WQn)(e,t)):this.node()[e]}function DCt(e){return e.trim().split(/^|\s+/)}function KOe(e){return e.classList||new LCt(e)}function LCt(e){this._node=e,this._names=DCt(e.getAttribute("class")||"")}LCt.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 FCt(e,t){for(var n=KOe(e),r=-1,s=t.length;++r<s;)n.add(t[r])}function zCt(e,t){for(var n=KOe(e),r=-1,s=t.length;++r<s;)n.remove(t[r])}function QQn(e){return function(){FCt(this,e)}}function YQn(e){return function(){zCt(this,e)}}function KQn(e,t){return function(){(t.apply(this,arguments)?FCt:zCt)(this,e)}}function XQn(e,t){var n=DCt(e+"");if(arguments.length<2){for(var r=KOe(this.node()),s=-1,a=n.length;++s<a;)if(!r.contains(n[s]))return!1;return!0}return this.each((typeof t=="function"?KQn:t?QQn:YQn)(n,t))}function JQn(){this.textContent=""}function eYn(e){return function(){this.textContent=e}}function tYn(e){return function(){var t=e.apply(this,arguments);this.textContent=t??""}}function nYn(e){return arguments.length?this.each(e==null?JQn:(typeof e=="function"?tYn:eYn)(e)):this.node().textContent}function rYn(){this.innerHTML=""}function sYn(e){return function(){this.innerHTML=e}}function aYn(e){return function(){var t=e.apply(this,arguments);this.innerHTML=t??""}}function iYn(e){return arguments.length?this.each(e==null?rYn:(typeof e=="function"?aYn:sYn)(e)):this.node().innerHTML}function oYn(){this.nextSibling&&this.parentNode.appendChild(this)}function lYn(){return this.each(oYn)}function cYn(){this.previousSibling&&this.parentNode.insertBefore(this,this.parentNode.firstChild)}function uYn(){return this.each(cYn)}function dYn(e){var t=typeof e=="function"?e:ICt(e);return this.select(function(){return this.appendChild(t.apply(this,arguments))})}function fYn(){return null}function hYn(e,t){var n=typeof e=="function"?e:ICt(e),r=t==null?fYn:typeof t=="function"?t:YOe(t);return this.select(function(){return this.insertBefore(n.apply(this,arguments),r.apply(this,arguments)||null)})}function pYn(){var e=this.parentNode;e&&e.removeChild(this)}function mYn(){return this.each(pYn)}function gYn(){var e=this.cloneNode(!1),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function vYn(){var e=this.cloneNode(!0),t=this.parentNode;return t?t.insertBefore(e,this.nextSibling):e}function yYn(e){return this.select(e?vYn:gYn)}function bYn(e){return arguments.length?this.property("__data__",e):this.node().__data__}function xYn(e){return function(t){e.call(this,t,this.__data__)}}function wYn(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 SYn(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 kYn(e,t,n){return function(){var r=this.__on,s,a=xYn(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 OYn(e,t,n){var r=wYn(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?kYn:SYn,s=0;s<a;++s)this.each(l(r[s],t,n));return this}function BCt(e,t,n){var r=MCt(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 CYn(e,t){return function(){return BCt(this,e,t)}}function _Yn(e,t){return function(){return BCt(this,e,t.apply(this,arguments))}}function EYn(e,t){return this.each((typeof t=="function"?_Yn:CYn)(e,t))}function*TYn(){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 UCt=[null];function ep(e,t){this._groups=e,this._parents=t}function dL(){return new ep([[document.documentElement]],UCt)}function jYn(){return this}ep.prototype=dL.prototype={constructor:ep,select:tQn,selectAll:aQn,selectChild:cQn,selectChildren:hQn,filter:pQn,data:xQn,enter:mQn,exit:SQn,join:kQn,merge:OQn,selection:jYn,order:CQn,sort:_Qn,call:TQn,nodes:jQn,node:NQn,size:IQn,empty:AQn,each:RQn,attr:zQn,style:VQn,property:GQn,classed:XQn,text:nYn,html:iYn,raise:lYn,lower:uYn,append:dYn,insert:hYn,remove:mYn,clone:yYn,datum:bYn,on:OYn,dispatch:EYn,[Symbol.iterator]:TYn};function Th(e){return typeof e=="string"?new ep([[document.querySelector(e)]],[document.documentElement]):new ep([[e]],UCt)}function NYn(e){let t;for(;t=e.sourceEvent;)e=t;return e}function gg(e,t){if(e=NYn(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 IYn={passive:!1},G2={capture:!0,passive:!1};function One(e){e.stopImmediatePropagation()}function yj(e){e.preventDefault(),e.stopImmediatePropagation()}function qCt(e){var t=e.document.documentElement,n=Th(e).on("dragstart.drag",yj,G2);"onselectstart"in t?n.on("selectstart.drag",yj,G2):(t.__noselect=t.style.MozUserSelect,t.style.MozUserSelect="none")}function VCt(e,t){var n=e.document.documentElement,r=Th(e).on("dragstart.drag",null);t&&(r.on("click.drag",yj,G2),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 RF=e=>()=>e;function Zve(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}})}Zve.prototype.on=function(){var e=this._.on.apply(this._,arguments);return e===this._?this:e};function AYn(e){return!e.ctrlKey&&!e.button}function RYn(){return this.parentNode}function PYn(e,t){return t??{x:e.x,y:e.y}}function $Yn(){return navigator.maxTouchPoints||"ontouchstart"in this}function HCt(){var e=AYn,t=RYn,n=PYn,r=$Yn,s={},a=CW("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,IYn).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");_&&(Th(k.view).on("mousemove.drag",m,G2).on("mouseup.drag",v,G2),qCt(k.view),One(k),u=!1,l=k.clientX,c=k.clientY,_("start",k))}}function m(k){if(yj(k),!u){var O=k.clientX-l,_=k.clientY-c;u=O*O+_*_>f}s.mouse("drag",k)}function v(k){Th(k.view).on("mousemove.drag mouseup.drag",null),VCt(k.view,u),yj(k),s.mouse("end",k)}function y(k,O){if(e.call(this,k,O)){var _=k.changedTouches,E=t.call(this,k,O),T=_.length,N,I;for(N=0;N<T;++N)(I=w(this,E,k,O,_[N].identifier,_[N]))&&(One(k),I("start",k,_[N]))}}function b(k){var O=k.changedTouches,_=O.length,E,T;for(E=0;E<_;++E)(T=s[O[E].identifier])&&(yj(k),T("drag",k,O[E]))}function x(k){var O=k.changedTouches,_=O.length,E,T;for(d&&clearTimeout(d),d=setTimeout(function(){d=null},500),E=0;E<_;++E)(T=s[O[E].identifier])&&(One(k),T("end",k,O[E]))}function w(k,O,_,E,T,N){var I=a.copy(),A=gg(N||_,O),R,L,M;if((M=n.call(k,new Zve("beforestart",{sourceEvent:_,target:h,identifier:T,active:i,x:A[0],y:A[1],dx:0,dy:0,dispatch:I}),E))!=null)return R=M.x-A[0]||0,L=M.y-A[1]||0,function B(V,q,F){var H=A,D;switch(V){case"start":s[T]=B,D=i++;break;case"end":delete s[T],--i;case"drag":A=gg(F||q,O),D=i;break}I.call(V,k,new Zve(V,{sourceEvent:q,subject:M,target:h,identifier:T,active:D,x:A[0]+R,y:A[1]+L,dx:A[0]-H[0],dy:A[1]-H[1],dispatch:I}),E)}}return h.filter=function(k){return arguments.length?(e=typeof k=="function"?k:RF(!!k),h):e},h.container=function(k){return arguments.length?(t=typeof k=="function"?k:RF(k),h):t},h.subject=function(k){return arguments.length?(n=typeof k=="function"?k:RF(k),h):n},h.touchable=function(k){return arguments.length?(r=typeof k=="function"?k:RF(!!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 XOe(e,t,n){e.prototype=t.prototype=n,n.constructor=e}function WCt(e,t){var n=Object.create(e.prototype);for(var r in t)n[r]=t[r];return n}function fL(){}var Q2=.7,pU=1/Q2,bj="\\s*([+-]?\\d+)\\s*",Y2="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)\\s*",py="\\s*([+-]?(?:\\d*\\.)?\\d+(?:[eE][+-]?\\d+)?)%\\s*",MYn=/^#([0-9a-f]{3,8})$/,DYn=new RegExp(`^rgb\\(${bj},${bj},${bj}\\)$`),LYn=new RegExp(`^rgb\\(${py},${py},${py}\\)$`),FYn=new RegExp(`^rgba\\(${bj},${bj},${bj},${Y2}\\)$`),zYn=new RegExp(`^rgba\\(${py},${py},${py},${Y2}\\)$`),BYn=new RegExp(`^hsl\\(${Y2},${py},${py}\\)$`),UYn=new RegExp(`^hsla\\(${Y2},${py},${py},${Y2}\\)$`),SBe={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};XOe(fL,lC,{copy(e){return Object.assign(new this.constructor,this,e)},displayable(){return this.rgb().displayable()},hex:kBe,formatHex:kBe,formatHex8:qYn,formatHsl:VYn,formatRgb:OBe,toString:OBe});function kBe(){return this.rgb().formatHex()}function qYn(){return this.rgb().formatHex8()}function VYn(){return ZCt(this).formatHsl()}function OBe(){return this.rgb().formatRgb()}function lC(e){var t,n;return e=(e+"").trim().toLowerCase(),(t=MYn.exec(e))?(n=t[1].length,t=parseInt(t[1],16),n===6?CBe(t):n===3?new jf(t>>8&15|t>>4&240,t>>4&15|t&240,(t&15)<<4|t&15,1):n===8?PF(t>>24&255,t>>16&255,t>>8&255,(t&255)/255):n===4?PF(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=DYn.exec(e))?new jf(t[1],t[2],t[3],1):(t=LYn.exec(e))?new jf(t[1]*255/100,t[2]*255/100,t[3]*255/100,1):(t=FYn.exec(e))?PF(t[1],t[2],t[3],t[4]):(t=zYn.exec(e))?PF(t[1]*255/100,t[2]*255/100,t[3]*255/100,t[4]):(t=BYn.exec(e))?TBe(t[1],t[2]/100,t[3]/100,1):(t=UYn.exec(e))?TBe(t[1],t[2]/100,t[3]/100,t[4]):SBe.hasOwnProperty(e)?CBe(SBe[e]):e==="transparent"?new jf(NaN,NaN,NaN,0):null}function CBe(e){return new jf(e>>16&255,e>>8&255,e&255,1)}function PF(e,t,n,r){return r<=0&&(e=t=n=NaN),new jf(e,t,n,r)}function HYn(e){return e instanceof fL||(e=lC(e)),e?(e=e.rgb(),new jf(e.r,e.g,e.b,e.opacity)):new jf}function Gve(e,t,n,r){return arguments.length===1?HYn(e):new jf(e,t,n,r??1)}function jf(e,t,n,r){this.r=+e,this.g=+t,this.b=+n,this.opacity=+r}XOe(jf,Gve,WCt(fL,{brighter(e){return e=e==null?pU:Math.pow(pU,e),new jf(this.r*e,this.g*e,this.b*e,this.opacity)},darker(e){return e=e==null?Q2:Math.pow(Q2,e),new jf(this.r*e,this.g*e,this.b*e,this.opacity)},rgb(){return this},clamp(){return new jf(pO(this.r),pO(this.g),pO(this.b),mU(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:_Be,formatHex:_Be,formatHex8:WYn,formatRgb:EBe,toString:EBe}));function _Be(){return`#${Gk(this.r)}${Gk(this.g)}${Gk(this.b)}`}function WYn(){return`#${Gk(this.r)}${Gk(this.g)}${Gk(this.b)}${Gk((isNaN(this.opacity)?1:this.opacity)*255)}`}function EBe(){const e=mU(this.opacity);return`${e===1?"rgb(":"rgba("}${pO(this.r)}, ${pO(this.g)}, ${pO(this.b)}${e===1?")":`, ${e})`}`}function mU(e){return isNaN(e)?1:Math.max(0,Math.min(1,e))}function pO(e){return Math.max(0,Math.min(255,Math.round(e)||0))}function Gk(e){return e=pO(e),(e<16?"0":"")+e.toString(16)}function TBe(e,t,n,r){return r<=0?e=t=n=NaN:n<=0||n>=1?e=t=NaN:t<=0&&(e=NaN),new kg(e,t,n,r)}function ZCt(e){if(e instanceof kg)return new kg(e.h,e.s,e.l,e.opacity);if(e instanceof fL||(e=lC(e)),!e)return new kg;if(e instanceof kg)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 kg(i,l,c,e.opacity)}function ZYn(e,t,n,r){return arguments.length===1?ZCt(e):new kg(e,t,n,r??1)}function kg(e,t,n,r){this.h=+e,this.s=+t,this.l=+n,this.opacity=+r}XOe(kg,ZYn,WCt(fL,{brighter(e){return e=e==null?pU:Math.pow(pU,e),new kg(this.h,this.s,this.l*e,this.opacity)},darker(e){return e=e==null?Q2:Math.pow(Q2,e),new kg(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 jf(Cne(e>=240?e-240:e+120,s,r),Cne(e,s,r),Cne(e<120?e+240:e-120,s,r),this.opacity)},clamp(){return new kg(jBe(this.h),$F(this.s),$F(this.l),mU(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=mU(this.opacity);return`${e===1?"hsl(":"hsla("}${jBe(this.h)}, ${$F(this.s)*100}%, ${$F(this.l)*100}%${e===1?")":`, ${e})`}`}}));function jBe(e){return e=(e||0)%360,e<0?e+360:e}function $F(e){return Math.max(0,Math.min(1,e||0))}function Cne(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 JOe=e=>()=>e;function GYn(e,t){return function(n){return e+n*t}}function QYn(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 YYn(e){return(e=+e)==1?GCt:function(t,n){return n-t?QYn(t,n,e):JOe(isNaN(t)?n:t)}}function GCt(e,t){var n=t-e;return n?GYn(e,n):JOe(isNaN(e)?t:e)}const gU=(function e(t){var n=YYn(t);function r(s,a){var i=n((s=Gve(s)).r,(a=Gve(a)).r),l=n(s.g,a.g),c=n(s.b,a.b),u=GCt(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 KYn(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 XYn(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function JYn(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]=bx(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 eKn(e,t){var n=new Date;return e=+e,t=+t,function(r){return n.setTime(e*(1-r)+t*r),n}}function yg(e,t){return e=+e,t=+t,function(n){return e*(1-n)+t*n}}function tKn(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]=bx(e[s],t[s]):r[s]=t[s];return function(a){for(s in n)r[s]=n[s](a);return r}}var Qve=/[-+]?(?:\d+\.?\d*|\.?\d+)(?:[eE][-+]?\d+)?/g,_ne=new RegExp(Qve.source,"g");function nKn(e){return function(){return e}}function rKn(e){return function(t){return e(t)+""}}function QCt(e,t){var n=Qve.lastIndex=_ne.lastIndex=0,r,s,a,i=-1,l=[],c=[];for(e=e+"",t=t+"";(r=Qve.exec(e))&&(s=_ne.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:yg(r,s)})),n=_ne.lastIndex;return n<t.length&&(a=t.slice(n),l[i]?l[i]+=a:l[++i]=a),l.length<2?c[0]?rKn(c[0].x):nKn(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 bx(e,t){var n=typeof t,r;return t==null||n==="boolean"?JOe(t):(n==="number"?yg:n==="string"?(r=lC(t))?(t=r,gU):QCt:t instanceof lC?gU:t instanceof Date?eKn:XYn(t)?KYn:Array.isArray(t)?JYn:typeof t.valueOf!="function"&&typeof t.toString!="function"||isNaN(t)?tKn:yg)(e,t)}function eCe(e,t){return e=+e,t=+t,function(n){return Math.round(e*(1-n)+t*n)}}var NBe=180/Math.PI,Yve={translateX:0,translateY:0,rotate:0,skewX:0,scaleX:1,scaleY:1};function YCt(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)*NBe,skewX:Math.atan(c)*NBe,scaleX:i,scaleY:l}}var MF;function sKn(e){const t=new(typeof DOMMatrix=="function"?DOMMatrix:WebKitCSSMatrix)(e+"");return t.isIdentity?Yve:YCt(t.a,t.b,t.c,t.d,t.e,t.f)}function aKn(e){return e==null||(MF||(MF=document.createElementNS("http://www.w3.org/2000/svg","g")),MF.setAttribute("transform",e),!(e=MF.transform.baseVal.consolidate()))?Yve:(e=e.matrix,YCt(e.a,e.b,e.c,e.d,e.e,e.f))}function KCt(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:yg(u,f)},{i:v-2,x:yg(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:yg(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:yg(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:yg(u,f)},{i:v-2,x:yg(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 iKn=KCt(sKn,"px, ","px)","deg)"),oKn=KCt(aKn,", ",")",")"),lKn=1e-12;function IBe(e){return((e=Math.exp(e))+1/e)/2}function cKn(e){return((e=Math.exp(e))-1/e)/2}function uKn(e){return((e=Math.exp(2*e))-1)/(e+1)}const d9=(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<lKn)b=Math.log(h/u)/t,y=function(E){return[l+E*p,c+E*m,u*Math.exp(t*E*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(E){var T=E*b,N=IBe(O),I=u/(n*x)*(N*uKn(t*T+O)-cKn(O));return[l+I*p,c+I*m,u*N/IBe(t*T+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 dKn(e,t){t===void 0&&(t=e,e=bx);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 dN=0,u$=0,YR=0,XCt=1e3,vU,d$,yU=0,cC=0,EW=0,K2=typeof performance=="object"&&performance.now?performance:Date,JCt=typeof window=="object"&&window.requestAnimationFrame?window.requestAnimationFrame.bind(window):function(e){setTimeout(e,17)};function tCe(){return cC||(JCt(fKn),cC=K2.now()+EW)}function fKn(){cC=0}function bU(){this._call=this._time=this._next=null}bU.prototype=e_t.prototype={constructor:bU,restart:function(e,t,n){if(typeof e!="function")throw new TypeError("callback is not a function");n=(n==null?tCe():+n)+(t==null?0:+t),!this._next&&d$!==this&&(d$?d$._next=this:vU=this,d$=this),this._call=e,this._time=n,Kve()},stop:function(){this._call&&(this._call=null,this._time=1/0,Kve())}};function e_t(e,t,n){var r=new bU;return r.restart(e,t,n),r}function hKn(){tCe(),++dN;for(var e=vU,t;e;)(t=cC-e._time)>=0&&e._call.call(void 0,t),e=e._next;--dN}function ABe(){cC=(yU=K2.now())+EW,dN=u$=0;try{hKn()}finally{dN=0,mKn(),cC=0}}function pKn(){var e=K2.now(),t=e-yU;t>XCt&&(EW-=t,yU=e)}function mKn(){for(var e,t=vU,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:vU=n);d$=e,Kve(r)}function Kve(e){if(!dN){u$&&(u$=clearTimeout(u$));var t=e-cC;t>24?(e<1/0&&(u$=setTimeout(ABe,e-K2.now()-EW)),YR&&(YR=clearInterval(YR))):(YR||(yU=K2.now(),YR=setInterval(pKn,XCt)),dN=1,JCt(ABe))}}function RBe(e,t,n){var r=new bU;return t=t==null?0:+t,r.restart(s=>{r.stop(),e(s+t)},t,n),r}var gKn=CW("start","end","cancel","interrupt"),vKn=[],t_t=0,PBe=1,Xve=2,f9=3,$Be=4,Jve=5,h9=6;function TW(e,t,n,r,s,a){var i=e.__transition;if(!i)e.__transition={};else if(n in i)return;yKn(e,n,{name:t,index:r,group:s,on:gKn,tween:vKn,time:a.time,delay:a.delay,duration:a.duration,ease:a.ease,timer:null,state:t_t})}function nCe(e,t){var n=ev(e,t);if(n.state>t_t)throw new Error("too late; already scheduled");return n}function Vy(e,t){var n=ev(e,t);if(n.state>f9)throw new Error("too late; already running");return n}function ev(e,t){var n=e.__transition;if(!n||!(n=n[t]))throw new Error("transition not found");return n}function yKn(e,t,n){var r=e.__transition,s;r[t]=n,n.timer=e_t(a,0,n.time);function a(u){n.state=PBe,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!==PBe)return c();for(d in r)if(p=r[d],p.name===n.name){if(p.state===f9)return RBe(i);p.state===$Be?(p.state=h9,p.timer.stop(),p.on.call("interrupt",e,e.__data__,p.index,p.group),delete r[d]):+d<t&&(p.state=h9,p.timer.stop(),p.on.call("cancel",e,e.__data__,p.index,p.group),delete r[d])}if(RBe(function(){n.state===f9&&(n.state=$Be,n.timer.restart(l,n.delay,n.time),l(u))}),n.state=Xve,n.on.call("start",e,e.__data__,n.index,n.group),n.state===Xve){for(n.state=f9,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=Jve,1),f=-1,h=s.length;++f<h;)s[f].call(e,d);n.state===Jve&&(n.on.call("end",e,e.__data__,n.index,n.group),c())}function c(){n.state=h9,n.timer.stop(),delete r[t];for(var u in r)return;delete e.__transition}}function p9(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>Xve&&r.state<Jve,r.state=h9,r.timer.stop(),r.on.call(s?"interrupt":"cancel",e,e.__data__,r.index,r.group),delete n[i]}a&&delete e.__transition}}function bKn(e){return this.each(function(){p9(this,e)})}function xKn(e,t){var n,r;return function(){var s=Vy(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 wKn(e,t,n){var r,s;if(typeof n!="function")throw new Error;return function(){var a=Vy(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 SKn(e,t){var n=this._id;if(e+="",arguments.length<2){for(var r=ev(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?xKn:wKn)(n,e,t))}function rCe(e,t,n){var r=e._id;return e.each(function(){var s=Vy(this,r);(s.value||(s.value={}))[t]=n.apply(this,arguments)}),function(s){return ev(s,r).value[t]}}function n_t(e,t){var n;return(typeof t=="number"?yg:t instanceof lC?gU:(n=lC(t))?(t=n,gU):QCt)(e,t)}function kKn(e){return function(){this.removeAttribute(e)}}function OKn(e){return function(){this.removeAttributeNS(e.space,e.local)}}function CKn(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 _Kn(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 EKn(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 TKn(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 jKn(e,t){var n=_W(e),r=n==="transform"?oKn:n_t;return this.attrTween(e,typeof t=="function"?(n.local?TKn:EKn)(n,r,rCe(this,"attr."+e,t)):t==null?(n.local?OKn:kKn)(n):(n.local?_Kn:CKn)(n,r,t))}function NKn(e,t){return function(n){this.setAttribute(e,t.call(this,n))}}function IKn(e,t){return function(n){this.setAttributeNS(e.space,e.local,t.call(this,n))}}function AKn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&IKn(e,a)),n}return s._value=t,s}function RKn(e,t){var n,r;function s(){var a=t.apply(this,arguments);return a!==r&&(n=(r=a)&&NKn(e,a)),n}return s._value=t,s}function PKn(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=_W(e);return this.tween(n,(r.local?AKn:RKn)(r,t))}function $Kn(e,t){return function(){nCe(this,e).delay=+t.apply(this,arguments)}}function MKn(e,t){return t=+t,function(){nCe(this,e).delay=t}}function DKn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?$Kn:MKn)(t,e)):ev(this.node(),t).delay}function LKn(e,t){return function(){Vy(this,e).duration=+t.apply(this,arguments)}}function FKn(e,t){return t=+t,function(){Vy(this,e).duration=t}}function zKn(e){var t=this._id;return arguments.length?this.each((typeof e=="function"?LKn:FKn)(t,e)):ev(this.node(),t).duration}function BKn(e,t){if(typeof t!="function")throw new Error;return function(){Vy(this,e).ease=t}}function UKn(e){var t=this._id;return arguments.length?this.each(BKn(t,e)):ev(this.node(),t).ease}function qKn(e,t){return function(){var n=t.apply(this,arguments);if(typeof n!="function")throw new Error;Vy(this,e).ease=n}}function VKn(e){if(typeof e!="function")throw new Error;return this.each(qKn(this._id,e))}function HKn(e){typeof e!="function"&&(e=RCt(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 zx(r,this._parents,this._name,this._id)}function WKn(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 zx(i,this._parents,this._name,this._id)}function ZKn(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 GKn(e,t,n){var r,s,a=ZKn(t)?nCe:Vy;return function(){var i=a(this,e),l=i.on;l!==r&&(s=(r=l).copy()).on(t,n),i.on=s}}function QKn(e,t){var n=this._id;return arguments.length<2?ev(this.node(),n).on.on(e):this.each(GKn(n,e,t))}function YKn(e){return function(){var t=this.parentNode;for(var n in this.__transition)if(+n!==e)return;t&&t.removeChild(this)}}function KKn(){return this.on("end.remove",YKn(this._id))}function XKn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=YOe(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,TW(u[h],t,n,h,u,ev(d,n)));return new zx(a,this._parents,t,n)}function JKn(e){var t=this._name,n=this._id;typeof e!="function"&&(e=ACt(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=ev(d,n),v=0,y=h.length;v<y;++v)(p=h[v])&&TW(p,t,n,v,h,m);a.push(h),i.push(d)}return new zx(a,i,t,n)}var eXn=dL.prototype.constructor;function tXn(){return new eXn(this._groups,this._parents)}function nXn(e,t){var n,r,s;return function(){var a=uN(this,e),i=(this.style.removeProperty(e),uN(this,e));return a===i?null:a===n&&i===r?s:s=t(n=a,r=i)}}function r_t(e){return function(){this.style.removeProperty(e)}}function rXn(e,t,n){var r,s=n+"",a;return function(){var i=uN(this,e);return i===s?null:i===r?a:a=t(r=i,n)}}function sXn(e,t,n){var r,s,a;return function(){var i=uN(this,e),l=n(this),c=l+"";return l==null&&(c=l=(this.style.removeProperty(e),uN(this,e))),i===c?null:i===r&&c===s?a:(s=c,a=t(r=i,l))}}function aXn(e,t){var n,r,s,a="style."+t,i="end."+a,l;return function(){var c=Vy(this,e),u=c.on,d=c.value[a]==null?l||(l=r_t(t)):void 0;(u!==n||s!==d)&&(r=(n=u).copy()).on(i,s=d),c.on=r}}function iXn(e,t,n){var r=(e+="")=="transform"?iKn:n_t;return t==null?this.styleTween(e,nXn(e,r)).on("end.style."+e,r_t(e)):typeof t=="function"?this.styleTween(e,sXn(e,r,rCe(this,"style."+e,t))).each(aXn(this._id,e)):this.styleTween(e,rXn(e,r,t),n).on("end.style."+e,null)}function oXn(e,t,n){return function(r){this.style.setProperty(e,t.call(this,r),n)}}function lXn(e,t,n){var r,s;function a(){var i=t.apply(this,arguments);return i!==s&&(r=(s=i)&&oXn(e,i,n)),r}return a._value=t,a}function cXn(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,lXn(e,t,n??""))}function uXn(e){return function(){this.textContent=e}}function dXn(e){return function(){var t=e(this);this.textContent=t??""}}function fXn(e){return this.tween("text",typeof e=="function"?dXn(rCe(this,"text",e)):uXn(e==null?"":e+""))}function hXn(e){return function(t){this.textContent=e.call(this,t)}}function pXn(e){var t,n;function r(){var s=e.apply(this,arguments);return s!==n&&(t=(n=s)&&hXn(s)),t}return r._value=e,r}function mXn(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,pXn(e))}function gXn(){for(var e=this._name,t=this._id,n=s_t(),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=ev(c,t);TW(c,e,n,u,i,{time:d.time+d.delay+d.duration,delay:0,duration:d.duration,ease:d.ease})}return new zx(r,this._parents,e,n)}function vXn(){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=Vy(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 yXn=0;function zx(e,t,n,r){this._groups=e,this._parents=t,this._name=n,this._id=r}function s_t(){return++yXn}var _b=dL.prototype;zx.prototype={constructor:zx,select:XKn,selectAll:JKn,selectChild:_b.selectChild,selectChildren:_b.selectChildren,filter:HKn,merge:WKn,selection:tXn,transition:gXn,call:_b.call,nodes:_b.nodes,node:_b.node,size:_b.size,empty:_b.empty,each:_b.each,on:QKn,attr:jKn,attrTween:PKn,style:iXn,styleTween:cXn,text:fXn,textTween:mXn,remove:KKn,tween:SKn,delay:DKn,duration:zKn,ease:UKn,easeVarying:VKn,end:vXn,[Symbol.iterator]:_b[Symbol.iterator]};function bXn(e){return((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2}var xXn={time:null,delay:0,duration:250,ease:bXn};function wXn(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 SXn(e){var t,n;e instanceof zx?(t=e._id,e=e._name):(t=s_t(),(n=xXn).time=tCe(),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])&&TW(c,e,t,u,i,n||wXn(c,t));return new zx(r,this._parents,e,t)}dL.prototype.interrupt=bKn;dL.prototype.transition=SXn;const DF=e=>()=>e;function kXn(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 ax(e,t,n){this.k=e,this.x=t,this.y=n}ax.prototype={constructor:ax,scale:function(e){return e===1?this:new ax(this.k*e,this.x,this.y)},translate:function(e,t){return e===0&t===0?this:new ax(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 jW=new ax(1,0,0);a_t.prototype=ax.prototype;function a_t(e){for(;!e.__zoom;)if(!(e=e.parentNode))return jW;return e.__zoom}function Ene(e){e.stopImmediatePropagation()}function KR(e){e.preventDefault(),e.stopImmediatePropagation()}function OXn(e){return(!e.ctrlKey||e.type==="wheel")&&!e.button}function CXn(){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 MBe(){return this.__zoom||jW}function _Xn(e){return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*(e.ctrlKey?10:1)}function EXn(){return navigator.maxTouchPoints||"ontouchstart"in this}function TXn(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 i_t(){var e=OXn,t=CXn,n=TXn,r=_Xn,s=EXn,a=[0,1/0],i=[[-1/0,-1/0],[1/0,1/0]],l=250,c=d9,u=CW("start","zoom","end"),d,f,h,p=500,m=150,v=0,y=10;function b(M){M.property("__zoom",MBe).on("wheel.zoom",T,{passive:!1}).on("mousedown.zoom",N).on("dblclick.zoom",I).filter(s).on("touchstart.zoom",A).on("touchmove.zoom",R).on("touchend.zoom touchcancel.zoom",L).style("-webkit-tap-highlight-color","rgba(0,0,0,0)")}b.transform=function(M,B,V,q){var F=M.selection?M.selection():M;F.property("__zoom",MBe),M!==F?O(M,B,V,q):F.interrupt().each(function(){_(this,arguments).event(q).start().zoom(null,typeof B=="function"?B.apply(this,arguments):B).end()})},b.scaleBy=function(M,B,V,q){b.scaleTo(M,function(){var F=this.__zoom.k,H=typeof B=="function"?B.apply(this,arguments):B;return F*H},V,q)},b.scaleTo=function(M,B,V,q){b.transform(M,function(){var F=t.apply(this,arguments),H=this.__zoom,D=V==null?k(F):typeof V=="function"?V.apply(this,arguments):V,G=H.invert(D),z=typeof B=="function"?B.apply(this,arguments):B;return n(w(x(H,z),D,G),F,i)},V,q)},b.translateBy=function(M,B,V,q){b.transform(M,function(){return n(this.__zoom.translate(typeof B=="function"?B.apply(this,arguments):B,typeof V=="function"?V.apply(this,arguments):V),t.apply(this,arguments),i)},null,q)},b.translateTo=function(M,B,V,q,F){b.transform(M,function(){var H=t.apply(this,arguments),D=this.__zoom,G=q==null?k(H):typeof q=="function"?q.apply(this,arguments):q;return n(jW.translate(G[0],G[1]).scale(D.k).translate(typeof B=="function"?-B.apply(this,arguments):-B,typeof V=="function"?-V.apply(this,arguments):-V),H,i)},q,F)};function x(M,B){return B=Math.max(a[0],Math.min(a[1],B)),B===M.k?M:new ax(B,M.x,M.y)}function w(M,B,V){var q=B[0]-V[0]*M.k,F=B[1]-V[1]*M.k;return q===M.x&&F===M.y?M:new ax(M.k,q,F)}function k(M){return[(+M[0][0]+ +M[1][0])/2,(+M[0][1]+ +M[1][1])/2]}function O(M,B,V,q){M.on("start.zoom",function(){_(this,arguments).event(q).start()}).on("interrupt.zoom end.zoom",function(){_(this,arguments).event(q).end()}).tween("zoom",function(){var F=this,H=arguments,D=_(F,H).event(q),G=t.apply(F,H),z=V==null?k(G):typeof V=="function"?V.apply(F,H):V,$=Math.max(G[1][0]-G[0][0],G[1][1]-G[0][1]),U=F.__zoom,W=typeof B=="function"?B.apply(F,H):B,Y=c(U.invert(z).concat($/U.k),W.invert(z).concat($/W.k));return function(te){if(te===1)te=W;else{var ee=Y(te),J=$/ee[2];te=new ax(J,z[0]-ee[0]*J,z[1]-ee[1]*J)}D.zoom(null,te)}})}function _(M,B,V){return!V&&M.__zooming||new E(M,B)}function E(M,B){this.that=M,this.args=B,this.active=0,this.sourceEvent=null,this.extent=t.apply(M,B),this.taps=0}E.prototype={event:function(M){return M&&(this.sourceEvent=M),this},start:function(){return++this.active===1&&(this.that.__zooming=this,this.emit("start")),this},zoom:function(M,B){return this.mouse&&M!=="mouse"&&(this.mouse[1]=B.invert(this.mouse[0])),this.touch0&&M!=="touch"&&(this.touch0[1]=B.invert(this.touch0[0])),this.touch1&&M!=="touch"&&(this.touch1[1]=B.invert(this.touch1[0])),this.that.__zoom=B,this.emit("zoom"),this},end:function(){return--this.active===0&&(delete this.that.__zooming,this.emit("end")),this},emit:function(M){var B=Th(this.that).datum();u.call(M,this.that,new kXn(M,{sourceEvent:this.sourceEvent,target:b,transform:this.that.__zoom,dispatch:u}),B)}};function T(M,...B){if(!e.apply(this,arguments))return;var V=_(this,B).event(M),q=this.__zoom,F=Math.max(a[0],Math.min(a[1],q.k*Math.pow(2,r.apply(this,arguments)))),H=gg(M);if(V.wheel)(V.mouse[0][0]!==H[0]||V.mouse[0][1]!==H[1])&&(V.mouse[1]=q.invert(V.mouse[0]=H)),clearTimeout(V.wheel);else{if(q.k===F)return;V.mouse=[H,q.invert(H)],p9(this),V.start()}KR(M),V.wheel=setTimeout(D,m),V.zoom("mouse",n(w(x(q,F),V.mouse[0],V.mouse[1]),V.extent,i));function D(){V.wheel=null,V.end()}}function N(M,...B){if(h||!e.apply(this,arguments))return;var V=M.currentTarget,q=_(this,B,!0).event(M),F=Th(M.view).on("mousemove.zoom",z,!0).on("mouseup.zoom",$,!0),H=gg(M,V),D=M.clientX,G=M.clientY;qCt(M.view),Ene(M),q.mouse=[H,this.__zoom.invert(H)],p9(this),q.start();function z(U){if(KR(U),!q.moved){var W=U.clientX-D,Y=U.clientY-G;q.moved=W*W+Y*Y>v}q.event(U).zoom("mouse",n(w(q.that.__zoom,q.mouse[0]=gg(U,V),q.mouse[1]),q.extent,i))}function $(U){F.on("mousemove.zoom mouseup.zoom",null),VCt(U.view,q.moved),KR(U),q.event(U).end()}}function I(M,...B){if(e.apply(this,arguments)){var V=this.__zoom,q=gg(M.changedTouches?M.changedTouches[0]:M,this),F=V.invert(q),H=V.k*(M.shiftKey?.5:2),D=n(w(x(V,H),q,F),t.apply(this,B),i);KR(M),l>0?Th(this).transition().duration(l).call(O,D,q,M):Th(this).call(b.transform,D,q,M)}}function A(M,...B){if(e.apply(this,arguments)){var V=M.touches,q=V.length,F=_(this,B,M.changedTouches.length===q).event(M),H,D,G,z;for(Ene(M),D=0;D<q;++D)G=V[D],z=gg(G,this),z=[z,this.__zoom.invert(z),G.identifier],F.touch0?!F.touch1&&F.touch0[2]!==z[2]&&(F.touch1=z,F.taps=0):(F.touch0=z,H=!0,F.taps=1+!!d);d&&(d=clearTimeout(d)),H&&(F.taps<2&&(f=z[0],d=setTimeout(function(){d=null},p)),p9(this),F.start())}}function R(M,...B){if(this.__zooming){var V=_(this,B).event(M),q=M.changedTouches,F=q.length,H,D,G,z;for(KR(M),H=0;H<F;++H)D=q[H],G=gg(D,this),V.touch0&&V.touch0[2]===D.identifier?V.touch0[0]=G:V.touch1&&V.touch1[2]===D.identifier&&(V.touch1[0]=G);if(D=V.that.__zoom,V.touch1){var $=V.touch0[0],U=V.touch0[1],W=V.touch1[0],Y=V.touch1[1],te=(te=W[0]-$[0])*te+(te=W[1]-$[1])*te,ee=(ee=Y[0]-U[0])*ee+(ee=Y[1]-U[1])*ee;D=x(D,Math.sqrt(te/ee)),G=[($[0]+W[0])/2,($[1]+W[1])/2],z=[(U[0]+Y[0])/2,(U[1]+Y[1])/2]}else if(V.touch0)G=V.touch0[0],z=V.touch0[1];else return;V.zoom("touch",n(w(D,G,z),V.extent,i))}}function L(M,...B){if(this.__zooming){var V=_(this,B).event(M),q=M.changedTouches,F=q.length,H,D;for(Ene(M),h&&clearTimeout(h),h=setTimeout(function(){h=null},p),H=0;H<F;++H)D=q[H],V.touch0&&V.touch0[2]===D.identifier?delete V.touch0:V.touch1&&V.touch1[2]===D.identifier&&delete V.touch1;if(V.touch1&&!V.touch0&&(V.touch0=V.touch1,delete V.touch1),V.touch0)V.touch0[1]=this.__zoom.invert(V.touch0[0]);else if(V.end(),V.taps===2&&(D=gg(D,this),Math.hypot(f[0]-D[0],f[1]-D[1])<y)){var G=Th(this).on("dblclick.zoom");G&&G.apply(this,arguments)}}}return b.wheelDelta=function(M){return arguments.length?(r=typeof M=="function"?M:DF(+M),b):r},b.filter=function(M){return arguments.length?(e=typeof M=="function"?M:DF(!!M),b):e},b.touchable=function(M){return arguments.length?(s=typeof M=="function"?M:DF(!!M),b):s},b.extent=function(M){return arguments.length?(t=typeof M=="function"?M:DF([[+M[0][0],+M[0][1]],[+M[1][0],+M[1][1]]]),b):t},b.scaleExtent=function(M){return arguments.length?(a[0]=+M[0],a[1]=+M[1],b):[a[0],a[1]]},b.translateExtent=function(M){return arguments.length?(i[0][0]=+M[0][0],i[1][0]=+M[1][0],i[0][1]=+M[0][1],i[1][1]=+M[1][1],b):[[i[0][0],i[0][1]],[i[1][0],i[1][1]]]},b.constrain=function(M){return arguments.length?(n=M,b):n},b.duration=function(M){return arguments.length?(l=+M,b):l},b.interpolate=function(M){return arguments.length?(c=M,b):c},b.on=function(){var M=u.on.apply(u,arguments);return M===u?b:M},b.clickDistance=function(M){return arguments.length?(v=(M=+M)*M,b):Math.sqrt(v)},b.tapDistance=function(M){return arguments.length?(y=+M,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."},X2=[[Number.NEGATIVE_INFINITY,Number.NEGATIVE_INFINITY],[Number.POSITIVE_INFINITY,Number.POSITIVE_INFINITY]],o_t=["Enter"," ","Escape"],l_t={"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 fN;(function(e){e.Strict="strict",e.Loose="loose"})(fN||(fN={}));var mO;(function(e){e.Free="free",e.Vertical="vertical",e.Horizontal="horizontal"})(mO||(mO={}));var J2;(function(e){e.Partial="partial",e.Full="full"})(J2||(J2={}));const c_t={inProgress:!1,isValid:null,from:null,fromHandle:null,fromPosition:null,fromNode:null,to:null,toHandle:null,toPosition:null,toNode:null,pointer:null};var Tw;(function(e){e.Bezier="default",e.Straight="straight",e.Step="step",e.SmoothStep="smoothstep",e.SimpleBezier="simplebezier"})(Tw||(Tw={}));var eD;(function(e){e.Arrow="arrow",e.ArrowClosed="arrowclosed"})(eD||(eD={}));var nr;(function(e){e.Left="left",e.Top="top",e.Right="right",e.Bottom="bottom"})(nr||(nr={}));const DBe={[nr.Left]:nr.Right,[nr.Right]:nr.Left,[nr.Top]:nr.Bottom,[nr.Bottom]:nr.Top};function u_t(e){return e===null?null:e?"valid":"invalid"}const d_t=e=>"id"in e&&"source"in e&&"target"in e,jXn=e=>"id"in e&&"position"in e&&!("source"in e)&&!("target"in e),sCe=e=>"id"in e&&"internals"in e&&!("source"in e)&&!("target"in e),hL=(e,t=[0,0])=>{const{width:n,height:r}=l0(e),s=e.origin??t,a=n*s[0],i=r*s[1];return{x:e.position.x-a,y:e.position.y-i}},NXn=(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):sCe(s)?s:t.nodeLookup.get(s.id));const l=i?xU(i,t.nodeOrigin):{x:0,y:0,x2:0,y2:0};return NW(r,l)},{x:1/0,y:1/0,x2:-1/0,y2:-1/0});return IW(n)},pL=(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=NW(n,xU(s)),r=!0)}),r?IW(n):{x:0,y:0,width:0,height:0}},aCe=(e,t,[n,r,s]=[0,0,1],a=!1,i=!1)=>{const l={...gL(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=tD(l,pN(u)),y=(p??0)*(m??0),b=a&&v>0;(!u.internals.handleBounds||b||v>=y||u.dragging)&&c.push(u)}return c},IXn=(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 AXn(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 RXn({nodes:e,width:t,height:n,panZoom:r,minZoom:s,maxZoom:a},i){if(e.size===0)return Promise.resolve(!0);const l=AXn(e,i),c=pL(l),u=iCe(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 f_t({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&&mN(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=mN(f)?uC(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 PXn({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=IXn(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 hN=(e,t=0,n=1)=>Math.min(Math.max(e,t),n),uC=(e={x:0,y:0},t,n)=>({x:hN(e.x,t[0][0],t[1][0]-(n?.width??0)),y:hN(e.y,t[0][1],t[1][1]-(n?.height??0))});function h_t(e,t,n){const{width:r,height:s}=l0(n),{x:a,y:i}=n.internals.positionAbsolute;return uC(e,[[a,i],[a+r,i+s]],t)}const LBe=(e,t,n)=>e<t?hN(Math.abs(e-t),1,t)/t:e>n?-hN(Math.abs(e-n),1,t)/t:0,p_t=(e,t,n=15,r=40)=>{const s=LBe(e.x,r,t.width-r)*n,a=LBe(e.y,r,t.height-r)*n;return[s,a]},NW=(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)}),eye=({x:e,y:t,width:n,height:r})=>({x:e,y:t,x2:e+n,y2:t+r}),IW=({x:e,y:t,x2:n,y2:r})=>({x:e,y:t,width:n-e,height:r-t}),pN=(e,t=[0,0])=>{const{x:n,y:r}=sCe(e)?e.internals.positionAbsolute:hL(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}=sCe(e)?e.internals.positionAbsolute:hL(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)}},m_t=(e,t)=>IW(NW(eye(e),eye(t))),tD=(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)},FBe=e=>Eg(e.width)&&Eg(e.height)&&Eg(e.x)&&Eg(e.y),Eg=e=>!isNaN(e)&&isFinite(e),$Xn=(e,t)=>{},mL=(e,t=[1,1])=>({x:t[0]*Math.round(e.x/t[0]),y:t[1]*Math.round(e.y/t[1])}),gL=({x:e,y:t},[n,r,s],a=!1,i=[1,1])=>{const l={x:(e-n)/s,y:(t-r)/s};return a?mL(l,i):l},wU=({x:e,y:t},[n,r,s])=>({x:e*s+n,y:t*s+r});function CE(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 MXn(e,t,n){if(typeof e=="string"||typeof e=="number"){const r=CE(e,n),s=CE(e,t);return{top:r,right:s,bottom:r,left:s,x:s*2,y:r*2}}if(typeof e=="object"){const r=CE(e.top??e.y??0,n),s=CE(e.bottom??e.y??0,n),a=CE(e.left??e.x??0,t),i=CE(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 DXn(e,t,n,r,s,a){const{x:i,y:l}=wU(e,[t,n,r]),{x:c,y:u}=wU({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 iCe=(e,t,n,r,s,a)=>{const i=MXn(a,t,n),l=(t-i.x)/e.width,c=(n-i.y)/e.height,u=Math.min(l,c),d=hN(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=DXn(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}},nD=()=>typeof navigator<"u"&&navigator?.userAgent?.indexOf("Mac")>=0;function mN(e){return e!=null&&e!=="parent"}function l0(e){return{width:e.measured?.width??e.width??e.initialWidth??0,height:e.measured?.height??e.height??e.initialHeight??0}}function g_t(e){return(e.measured?.width??e.width??e.initialWidth)!==void 0&&(e.measured?.height??e.height??e.initialHeight)!==void 0}function v_t(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 zBe(e,t){if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;return!0}function LXn(){let e,t;return{promise:new Promise((r,s)=>{e=r,t=s}),resolve:e,reject:t}}function FXn(e){return{...l_t,...e||{}}}function K$(e,{snapGrid:t=[0,0],snapToGrid:n=!1,transform:r,containerBounds:s}){const{x:a,y:i}=Tg(e),l=gL({x:a-(s?.left??0),y:i-(s?.top??0)},r),{x:c,y:u}=n?mL(l,t):l;return{xSnapped:c,ySnapped:u,...l}}const oCe=e=>({width:e.offsetWidth,height:e.offsetHeight}),y_t=e=>e?.getRootNode?.()||window?.document,zXn=["INPUT","SELECT","TEXTAREA"];function b_t(e){const t=e.composedPath?.()?.[0]||e.target;return t?.nodeType!==1?!1:zXn.includes(t.nodeName)||t.hasAttribute("contenteditable")||!!t.closest(".nokey")}const x_t=e=>"clientX"in e,Tg=(e,t)=>{const n=x_t(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)}},BBe=(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,...oCe(i)}})};function w_t({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 LF(e,t){return e>=0?.5*e:t*25*Math.sqrt(-e)}function UBe({pos:e,x1:t,y1:n,x2:r,y2:s,c:a}){switch(e){case nr.Left:return[t-LF(t-r,a),n];case nr.Right:return[t+LF(r-t,a),n];case nr.Top:return[t,n-LF(n-s,a)];case nr.Bottom:return[t,n+LF(s-n,a)]}}function lCe({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,curvature:i=.25}){const[l,c]=UBe({pos:n,x1:e,y1:t,x2:r,y2:s,c:i}),[u,d]=UBe({pos:a,x1:r,y1:s,x2:e,y2:t,c:i}),[f,h,p,m]=w_t({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 S_t({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 BXn({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 UXn({sourceNode:e,targetNode:t,width:n,height:r,transform:s}){const a=NW(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 tD(i,IW(a))>0}const qXn=({source:e,sourceHandle:t,target:n,targetHandle:r})=>`xy-edge__${e}${t||""}-${n}${r||""}`,VXn=(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)),HXn=(e,t,n={})=>{if(!e.source||!e.target)return t;const r=n.getEdgeId||qXn;let s;return d_t(e)?s={...e}:s={...e,id:r(e)},VXn(s,t)?t:(s.sourceHandle===null&&delete s.sourceHandle,s.targetHandle===null&&delete s.targetHandle,t.concat(s))};function k_t({sourceX:e,sourceY:t,targetX:n,targetY:r}){const[s,a,i,l]=S_t({sourceX:e,sourceY:t,targetX:n,targetY:r});return[`M ${e},${t}L ${n},${r}`,s,a,i,l]}const qBe={[nr.Left]:{x:-1,y:0},[nr.Right]:{x:1,y:0},[nr.Top]:{x:0,y:-1},[nr.Bottom]:{x:0,y:1}},WXn=({source:e,sourcePosition:t=nr.Bottom,target:n})=>t===nr.Left||t===nr.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},VBe=(e,t)=>Math.sqrt(Math.pow(t.x-e.x,2)+Math.pow(t.y-e.y,2));function ZXn({source:e,sourcePosition:t=nr.Bottom,target:n,targetPosition:r=nr.Top,center:s,offset:a,stepPosition:i}){const l=qBe[t],c=qBe[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=WXn({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]=S_t({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 T=[{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"?T:N:m=h==="x"?N:T}else{const T=[{x:u.x,y:d.y}],N=[{x:d.x,y:u.y}];if(h==="x"?m=l.x===p?N:T:m=l.y===p?T:N,t===r){const M=Math.abs(e[h]-n[h]);if(M<=a){const B=Math.min(a-1,a-M);l[h]===p?b[h]=(u[h]>e[h]?-1:1)*B:x[h]=(d[h]>n[h]?-1:1)*B}}if(t!==r){const M=h==="x"?"y":"x",B=l[h]===c[M],V=u[M]>d[M],q=u[M]<d[M];(l[h]===1&&(!B&&V||B&&q)||l[h]!==1&&(!B&&q||B&&V))&&(m=h==="x"?T:N)}const I={x:u.x+b.x,y:u.y+b.y},A={x:d.x+x.x,y:d.y+x.y},R=Math.max(Math.abs(I.x-m[0].x),Math.abs(A.x-m[0].x)),L=Math.max(Math.abs(I.y-m[0].y),Math.abs(A.y-m[0].y));R>=L?(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 GXn(e,t,n,r){const s=Math.min(VBe(e,t)/2,VBe(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 tye({sourceX:e,sourceY:t,sourcePosition:n=nr.Bottom,targetX:r,targetY:s,targetPosition:a=nr.Top,borderRadius:i=5,centerX:l,centerY:c,offset:u=20,stepPosition:d=.5}){const[f,h,p,m,v]=ZXn({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+=GXn(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 HBe(e){return e&&!!(e.internals.handleBounds||e.handles?.length)&&!!(e.measured.width||e.width||e.initialWidth)}function QXn(e){const{sourceNode:t,targetNode:n}=e;if(!HBe(t)||!HBe(n))return null;const r=t.internals.handleBounds||WBe(t.handles),s=n.internals.handleBounds||WBe(n.handles),a=ZBe(r?.source??[],e.sourceHandle),i=ZBe(e.connectionMode===fN.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||nr.Bottom,c=i?.position||nr.Top,u=dC(t,a,l),d=dC(n,i,c);return{sourceX:u.x,sourceY:u.y,targetX:d.x,targetY:d.y,sourcePosition:l,targetPosition:c}}function WBe(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 dC(e,t,n=nr.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??l0(e);if(r)return{x:s+i/2,y:a+l/2};switch(t?.position??n){case nr.Top:return{x:s+i/2,y:a};case nr.Right:return{x:s+i,y:a+l/2};case nr.Bottom:return{x:s+i/2,y:a+l};case nr.Left:return{x:s,y:a+l/2}}}function ZBe(e,t){return e&&(t?e.find(n=>n.id===t):e[0])||null}function nye(e,t){return e?typeof e=="string"?e:`${t?`${t}__`:""}${Object.keys(e).sort().map(r=>`${r}=${e[r]}`).join("&")}`:""}function YXn(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=nye(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 O_t=1e3,KXn=10,cCe={nodeOrigin:[0,0],nodeExtent:X2,elevateNodesOnSelect:!0,zIndexMode:"basic",defaults:{}},XXn={...cCe,checkEquality:!0};function uCe(e,t){const n={...e};for(const r in t)t[r]!==void 0&&(n[r]=t[r]);return n}function JXn(e,t,n){const r=uCe(cCe,n);for(const s of e.values())if(s.parentId)fCe(s,e,t,r);else{const a=hL(s,r.nodeOrigin),i=mN(s.extent)?s.extent:r.nodeExtent,l=uC(a,i,l0(s));s.internals.positionAbsolute=l}}function eJn(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 dCe(e){return e==="manual"}function rye(e,t,n,r={}){const s=uCe(XXn,r),a={i:0},i=new Map(t),l=s?.elevateNodesOnSelect&&!dCe(s.zIndexMode)?O_t: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=hL(d,s.nodeOrigin),p=mN(d.extent)?d.extent:s.nodeExtent,m=uC(h,p,l0(d));f={...s.defaults,...d,measured:{width:d.measured?.width,height:d.measured?.height},internals:{positionAbsolute:m,handleBounds:eJn(d,f),z:C_t(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&&fCe(f,t,n,r,a),u||=d.selected??!1}return{nodesInitialized:c,hasSelectedNodes:u}}function tJn(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 fCe(e,t,n,r,s){const{elevateNodesOnSelect:a,nodeOrigin:i,nodeExtent:l,zIndexMode:c}=uCe(cCe,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}tJn(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*KXn),s&&d.internals.rootParentIndex!==void 0&&(s.i=d.internals.rootParentIndex);const f=a&&!dCe(c)?O_t:0,{x:h,y:p,z:m}=nJn(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 C_t(e,t,n){const r=Eg(e.zIndex)?e.zIndex:0;return dCe(n)?r:r+(e.selected?t:0)}function nJn(e,t,n,r,s,a){const{x:i,y:l}=t.internals.positionAbsolute,c=l0(e),u=hL(e,n),d=mN(e.extent)?uC(u,e.extent,c):u;let f=uC({x:i+d.x,y:l+d.y},r,c);e.extent==="parent"&&(f=h_t(f,c,t));const h=C_t(e,s,a),p=t.internals.z??0;return{x:f.x,y:f.y,z:p>=h?p+1:h}}function hCe(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??pN(l),u=m_t(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=l0(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 rJn(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=oCe(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=mN(m.extent)?m.extent:a;let{positionAbsolute:k}=m.internals;m.parentId&&m.extent==="parent"?k=h_t(k,v,t.get(m.parentId)):w&&(k=uC(k,w,v));const O={...m,measured:v,internals:{...m.internals,positionAbsolute:k,handleBounds:{source:BBe("source",p.nodeElement,x,f,m.id),target:BBe("target",p.nodeElement,x,f,m.id)}}};t.set(m.id,O),m.parentId&&fCe(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:pN(O,s)}))}}if(h.length>0){const p=hCe(h,t,n,s);u.push(...p)}return{changes:u,updatedInternals:c}}async function sJn({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 GBe(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 __t(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}`;GBe("source",c,d,e,s,i),GBe("target",c,u,e,a,l),t.set(r.id,r)}}function E_t(e,t){if(!e.parentId)return!1;const n=t.get(e.parentId);return n?n.selected?!0:E_t(n,t):!1}function QBe(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 aJn(e,t,n,r){const s=new Map;for(const[a,i]of e)if((i.selected||i.id===r)&&(!i.parentId||!E_t(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 Tne({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 iJn({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=mL(a,t);return{x:i.x-a.x,y:i.y-a.y}}function oJn({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:E=0}){h=Th(k);function T({x:R,y:L}){const{nodeLookup:M,nodeExtent:B,snapGrid:V,snapToGrid:q,nodeOrigin:F,onNodeDrag:H,onSelectionDrag:D,onError:G,updateNodePositions:z}=t();a={x:R,y:L};let $=!1;const U=l.size>1,W=U&&B?eye(pL(l)):null,Y=U&&q?iJn({dragItems:l,snapGrid:V,x:R,y:L}):null;for(const[te,ee]of l){if(!M.has(te))continue;let J={x:R-ee.distance.x,y:L-ee.distance.y};q&&(J=Y?{x:Math.round(J.x+Y.x),y:Math.round(J.y+Y.y)}:mL(J,V));let re=null;if(U&&B&&!ee.extent&&W){const{positionAbsolute:ne}=ee.internals,se=ne.x-W.x+B[0][0],de=ne.x+ee.measured.width-W.x2+B[1][0],ue=ne.y-W.y+B[0][1],ye=ne.y+ee.measured.height-W.y2+B[1][1];re=[[se,ue],[de,ye]]}const{position:le,positionAbsolute:X}=f_t({nodeId:te,nextPosition:J,nodeLookup:M,nodeExtent:re||B,nodeOrigin:F,onError:G});$=$||ee.position.x!==le.x||ee.position.y!==le.y,ee.position=le,ee.internals.positionAbsolute=X}if(m=m||$,!!$&&(z(l,!0),v&&(r||H||!_&&D))){const[te,ee]=Tne({nodeId:_,dragItems:l,nodeLookup:M});r?.(v,l,te,ee),H?.(v,te,ee),_||D?.(v,ee)}}async function N(){if(!d)return;const{transform:R,panBy:L,autoPanSpeed:M,autoPanOnNodeDrag:B}=t();if(!B){c=!1,cancelAnimationFrame(i);return}const[V,q]=p_t(u,d,M);(V!==0||q!==0)&&(a.x=(a.x??0)-V/R[2],a.y=(a.y??0)-q/R[2],await L({x:V,y:q})&&T(a)),i=requestAnimationFrame(N)}function I(R){const{nodeLookup:L,multiSelectionActive:M,nodesDraggable:B,transform:V,snapGrid:q,snapToGrid:F,selectNodesOnDrag:H,onNodeDragStart:D,onSelectionDragStart:G,unselectNodesAndEdges:z}=t();f=!0,(!H||!O)&&!M&&_&&(L.get(_)?.selected||z()),O&&H&&_&&e?.(_);const $=K$(R.sourceEvent,{transform:V,snapGrid:q,snapToGrid:F,containerBounds:d});if(a=$,l=aJn(L,B,$,_),l.size>0&&(n||D||!_&&G)){const[U,W]=Tne({nodeId:_,dragItems:l,nodeLookup:L});n?.(R.sourceEvent,l,U,W),D?.(R.sourceEvent,U,W),_||G?.(R.sourceEvent,W)}}const A=HCt().clickDistance(E).on("start",R=>{const{domNode:L,nodeDragThreshold:M,transform:B,snapGrid:V,snapToGrid:q}=t();d=L?.getBoundingClientRect()||null,p=!1,m=!1,v=R.sourceEvent,M===0&&I(R),a=K$(R.sourceEvent,{transform:B,snapGrid:V,snapToGrid:q,containerBounds:d}),u=Tg(R.sourceEvent,d)}).on("drag",R=>{const{autoPanOnNodeDrag:L,transform:M,snapGrid:B,snapToGrid:V,nodeDragThreshold:q,nodeLookup:F}=t(),H=K$(R.sourceEvent,{transform:M,snapGrid:B,snapToGrid:V,containerBounds:d});if(v=R.sourceEvent,(R.sourceEvent.type==="touchmove"&&R.sourceEvent.touches.length>1||_&&!F.has(_))&&(p=!0),!p){if(!c&&L&&f&&(c=!0,N()),!f){const D=Tg(R.sourceEvent,d),G=D.x-u.x,z=D.y-u.y;Math.sqrt(G*G+z*z)>q&&I(R)}(a.x!==H.xSnapped||a.y!==H.ySnapped)&&l&&f&&(u=Tg(R.sourceEvent,d),T(H))}}).on("end",R=>{if(!(!f||p)&&(c=!1,f=!1,cancelAnimationFrame(i),l.size>0)){const{nodeLookup:L,updateNodePositions:M,onNodeDragStop:B,onSelectionDragStop:V}=t();if(m&&(M(l,!1),m=!1),s||B||!_&&V){const[q,F]=Tne({nodeId:_,dragItems:l,nodeLookup:L,dragging:!1});s?.(R.sourceEvent,l,q,F),B?.(R.sourceEvent,q,F),_||V?.(R.sourceEvent,F)}}}).filter(R=>{const L=R.target;return!R.button&&(!x||!QBe(L,`.${x}`,k))&&(!w||QBe(L,w,k))});h.call(A)}function b(){h?.on(".drag",null)}return{update:y,destroy:b}}function lJn(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())tD(s,pN(a))>0&&r.push(a);return r}const cJn=250;function uJn(e,t,n,r){let s=[],a=1/0;const i=lJn(e,n,t+cJn);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}=dC(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 T_t(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,...dC(i,c,c.position,!0)}:c}function j_t(e,t){return e||(t?.classList.contains("target")?"target":t?.classList.contains("source")?"source":null)}function dJn(e,t){let n=null;return t?n=!0:e&&!t&&(n=!1),n}const N_t=()=>!0;function fJn(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=N_t,onReconnectEnd:x,updateConnection:w,getTransform:k,getFromHandle:O,autoPanSpeed:_,dragThreshold:E=1,handleDomNode:T}){const N=y_t(e.target);let I=0,A;const{x:R,y:L}=Tg(e),M=j_t(a,T),B=l?.getBoundingClientRect();let V=!1;if(!B||!M)return;const q=T_t(s,M,r,c,t);if(!q)return;let F=Tg(e,B),H=!1,D=null,G=!1,z=null;function $(){if(!d||!B)return;const[le,X]=p_t(F,B,_);h({x:le,y:X}),I=requestAnimationFrame($)}const U={...q,nodeId:s,type:M,position:q.position},W=c.get(s);let te={inProgress:!0,isValid:null,from:dC(W,U,nr.Left,!0),fromHandle:U,fromPosition:U.position,fromNode:W,to:F,toHandle:null,toPosition:DBe[U.position],toNode:null,pointer:F};function ee(){V=!0,w(te),m?.(e,{nodeId:s,handleId:r,handleType:M})}E===0&&ee();function J(le){if(!V){const{x:ye,y:he}=Tg(le),xe=ye-R,Ne=he-L;if(!(xe*xe+Ne*Ne>E*E))return;ee()}if(!O()||!U){re(le);return}const X=k();F=Tg(le,B),A=uJn(gL(F,X,!1,[1,1]),n,c,U),H||($(),H=!0);const ne=I_t(le,{handle:A,connectionMode:t,fromNodeId:s,fromHandleId:r,fromType:i?"target":"source",isValidConnection:b,doc:N,lib:u,flowId:f,nodeLookup:c});z=ne.handleDomNode,D=ne.connection,G=dJn(!!A,ne.isValid);const se=c.get(s),de=se?dC(se,U,nr.Left,!0):te.from,ue={...te,from:de,isValid:G,to:ne.toHandle&&G?wU({x:ne.toHandle.x,y:ne.toHandle.y},X):F,toHandle:ne.toHandle,toPosition:G&&ne.toHandle?ne.toHandle.position:DBe[U.position],toNode:ne.toHandle?c.get(ne.toHandle.nodeId):null,pointer:F};w(ue),te=ue}function re(le){if(!("touches"in le&&le.touches.length>0)){if(V){(A||z)&&D&&G&&v?.(D);const{inProgress:X,...ne}=te,se={...ne,toPosition:te.toHandle?te.toPosition:null};y?.(le,se),a&&x?.(le,se)}p(),cancelAnimationFrame(I),H=!1,G=!1,D=null,z=null,N.removeEventListener("mousemove",J),N.removeEventListener("mouseup",re),N.removeEventListener("touchmove",J),N.removeEventListener("touchend",re)}}N.addEventListener("mousemove",J),N.addEventListener("mouseup",re),N.addEventListener("touchmove",J),N.addEventListener("touchend",re)}function I_t(e,{handle:t,connectionMode:n,fromNodeId:r,fromHandleId:s,fromType:a,doc:i,lib:l,flowId:c,isValidConnection:u=N_t,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}=Tg(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=j_t(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 E={source:f?w:r,sourceHandle:f?k:s,target:f?r:w,targetHandle:f?s:k};b.connection=E;const N=O&&_&&(n===fN.Strict?f&&x==="source"||!f&&x==="target":w!==r||k!==s);b.isValid=N&&u(E),b.toHandle=T_t(w,x,k,d,n,!0)}return b}const sye={onPointerDown:fJn,isValid:I_t};function hJn({domNode:e,panZoom:t,getTransform:n,getViewScale:r}){const s=Th(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&&nD()?10:1,_=-w.sourceEvent.deltaY*(w.sourceEvent.deltaMode===1?.05:w.sourceEvent.deltaMode?1:.002)*d,E=k[2]*Math.pow(2,_*O);t.scaleTo(E)};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 E=r()*Math.max(k[2],Math.log(k[2]))*(p?-1:1),T={x:k[0]-_[0]*E,y:k[1]-_[1]*E},N=[[0,0],[c,u]];t.setViewportConstrained({x:T.x,y:T.y,zoom:k[2]},N,l)},x=i_t().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:gg}}const AW=e=>({x:e.x,y:e.y,zoom:e.k}),jne=({x:e,y:t,zoom:n})=>jW.translate(e,t).scale(n),AT=(e,t)=>e.target.closest(`.${t}`),A_t=(e,t)=>t===2&&Array.isArray(e)&&e.includes(2),pJn=e=>((e*=2)<=1?e*e*e:(e-=2)*e*e+2)/2,Nne=(e,t=0,n=pJn,r=()=>{})=>{const s=typeof t=="number"&&t>0;return s||r(),s?e.transition().duration(t).ease(n).on("end",r):e},R_t=e=>{const t=e.ctrlKey&&nD()?10:1;return-e.deltaY*(e.deltaMode===1?.05:e.deltaMode?1:.002)*t};function mJn({zoomPanValues:e,noWheelClassName:t,d3Selection:n,d3Zoom:r,panOnScrollMode:s,panOnScrollSpeed:a,zoomOnPinch:i,onPanZoomStart:l,onPanZoom:c,onPanZoomEnd:u}){return d=>{if(AT(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=gg(d),b=R_t(d),x=f*Math.pow(2,b);r.scaleTo(n,x,y,d);return}const h=d.deltaMode===1?20:1;let p=s===mO.Vertical?0:d.deltaX*h,m=s===mO.Horizontal?0:d.deltaY*h;!nD()&&d.shiftKey&&s!==mO.Vertical&&(p=d.deltaY*h,m=0),r.translateBy(n,-(p/f)*a,-(m/f)*a,{internal:!0});const v=AW(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 gJn({noWheelClassName:e,preventScrolling:t,d3ZoomHandler:n}){return function(r,s){const a=r.type==="wheel",i=!t&&a&&!r.ctrlKey,l=AT(r,e);if(r.ctrlKey&&a&&l&&r.preventDefault(),i||l)return null;r.preventDefault(),n.call(this,r,s)}}function vJn({zoomPanValues:e,onDraggingChange:t,onPanZoomStart:n}){return r=>{if(r.sourceEvent?.internal)return;const s=AW(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 yJn({zoomPanValues:e,panOnDrag:t,onPaneContextMenu:n,onTransformChange:r,onPanZoom:s}){return a=>{e.usedRightMouseButton=!!(n&&A_t(t,e.mouseButton??0)),a.sourceEvent?.sync||r([a.transform.x,a.transform.y,a.transform.k]),s&&!a.sourceEvent?.internal&&s?.(a.sourceEvent,AW(a.transform))}}function bJn({zoomPanValues:e,panOnDrag:t,panOnScroll:n,onDraggingChange:r,onPanZoomEnd:s,onPaneContextMenu:a}){return i=>{if(!i.sourceEvent?.internal&&(e.isZoomingOrPanning=!1,a&&A_t(t,e.mouseButton??0)&&!e.usedRightMouseButton&&i.sourceEvent&&a(i.sourceEvent),e.usedRightMouseButton=!1,r(!1),s)){const l=AW(i.transform);e.prevViewport=l,clearTimeout(e.timerId),e.timerId=setTimeout(()=>{s?.(i.sourceEvent,l)},n?150:0)}}}function xJn({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"&&(AT(f,`${u}-flow__node`)||AT(f,`${u}-flow__edge`)))return!0;if(!r&&!h&&!s&&!a&&!n||i||d&&!m||AT(f,l)&&m||AT(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 wJn({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=i_t().scaleExtent([t,n]).translateExtent(r),h=Th(e).call(f);x({x:s.x,y:s.y,zoom:hN(s.zoom,t,n)},[[0,0],[d.width,d.height]],r);const p=h.on("wheel.zoom"),m=h.on("dblclick.zoom");f.wheelDelta(R_t);function v(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?bx:d9).transform(Nne(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function y({noWheelClassName:A,noPanClassName:R,onPaneContextMenu:L,userSelectionActive:M,panOnScroll:B,panOnDrag:V,panOnScrollMode:q,panOnScrollSpeed:F,preventScrolling:H,zoomOnPinch:D,zoomOnScroll:G,zoomOnDoubleClick:z,zoomActivationKeyPressed:$,lib:U,onTransformChange:W,connectionInProgress:Y,paneClickDistance:te,selectionOnDrag:ee}){M&&!u.isZoomingOrPanning&&b();const J=B&&!$&&!M;f.clickDistance(ee?1/0:!Eg(te)||te<0?0:te);const re=J?mJn({zoomPanValues:u,noWheelClassName:A,d3Selection:h,d3Zoom:f,panOnScrollMode:q,panOnScrollSpeed:F,zoomOnPinch:D,onPanZoomStart:i,onPanZoom:a,onPanZoomEnd:l}):gJn({noWheelClassName:A,preventScrolling:H,d3ZoomHandler:p});if(h.on("wheel.zoom",re,{passive:!1}),!M){const X=vJn({zoomPanValues:u,onDraggingChange:c,onPanZoomStart:i});f.on("start",X);const ne=yJn({zoomPanValues:u,panOnDrag:V,onPaneContextMenu:!!L,onPanZoom:a,onTransformChange:W});f.on("zoom",ne);const se=bJn({zoomPanValues:u,panOnDrag:V,panOnScroll:B,onPaneContextMenu:L,onPanZoomEnd:l,onDraggingChange:c});f.on("end",se)}const le=xJn({zoomActivationKeyPressed:$,panOnDrag:V,zoomOnScroll:G,panOnScroll:B,zoomOnDoubleClick:z,zoomOnPinch:D,userSelectionActive:M,noPanClassName:R,noWheelClassName:A,lib:U,connectionInProgress:Y});f.filter(le),z?h.on("dblclick.zoom",m):h.on("dblclick.zoom",null)}function b(){f.on("zoom",null)}async function x(A,R,L){const M=jne(A),B=f?.constrain()(M,R,L);return B&&await v(B),new Promise(V=>V(B))}async function w(A,R){const L=jne(A);return await v(L,R),new Promise(M=>M(L))}function k(A){if(h){const R=jne(A),L=h.property("__zoom");(L.k!==A.zoom||L.x!==A.x||L.y!==A.y)&&f?.transform(h,R,null,{sync:!0})}}function O(){const A=h?a_t(h.node()):{x:0,y:0,k:1};return{x:A.x,y:A.y,zoom:A.k}}function _(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?bx:d9).scaleTo(Nne(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function E(A,R){return h?new Promise(L=>{f?.interpolate(R?.interpolate==="linear"?bx:d9).scaleBy(Nne(h,R?.duration,R?.ease,()=>L(!0)),A)}):Promise.resolve(!1)}function T(A){f?.scaleExtent(A)}function N(A){f?.translateExtent(A)}function I(A){const R=!Eg(A)||A<0?0:A;f?.clickDistance(R)}return{update:y,destroy:b,setViewport:w,setViewportConstrained:x,getViewport:O,scaleTo:_,scaleBy:E,setScaleExtent:T,setTranslateExtent:N,syncViewport:k,setClickDistance:I}}var gN;(function(e){e.Line="line",e.Handle="handle"})(gN||(gN={}));function SJn({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 YBe(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 rw(e,t){return Math.max(0,t-e)}function sw(e,t){return Math.max(0,e-t)}function FF(e,t,n){return Math.max(0,t-e,e-n)}function KBe(e,t){return e?!t:t}function kJn(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:E}=e;let T=Math.floor(d?p-e.pointerX:0),N=Math.floor(f?m-e.pointerY:0);const I=O+(c?-T:T),A=_+(u?-N:N),R=-a[0]*O,L=-a[1]*_;let M=FF(I,v,y),B=FF(A,b,x);if(i){let F=0,H=0;c&&T<0?F=rw(w+T+R,i[0][0]):!c&&T>0&&(F=sw(w+I+R,i[1][0])),u&&N<0?H=rw(k+N+L,i[0][1]):!u&&N>0&&(H=sw(k+A+L,i[1][1])),M=Math.max(M,F),B=Math.max(B,H)}if(l){let F=0,H=0;c&&T>0?F=sw(w+T,l[0][0]):!c&&T<0&&(F=rw(w+I,l[1][0])),u&&N>0?H=sw(k+N,l[0][1]):!u&&N<0&&(H=rw(k+A,l[1][1])),M=Math.max(M,F),B=Math.max(B,H)}if(s){if(d){const F=FF(I/E,b,x)*E;if(M=Math.max(M,F),i){let H=0;!c&&!u||c&&!u&&h?H=sw(k+L+I/E,i[1][1])*E:H=rw(k+L+(c?T:-T)/E,i[0][1])*E,M=Math.max(M,H)}if(l){let H=0;!c&&!u||c&&!u&&h?H=rw(k+I/E,l[1][1])*E:H=sw(k+(c?T:-T)/E,l[0][1])*E,M=Math.max(M,H)}}if(f){const F=FF(A*E,v,y)/E;if(B=Math.max(B,F),i){let H=0;!c&&!u||u&&!c&&h?H=sw(w+A*E+R,i[1][0])/E:H=rw(w+(u?N:-N)*E+R,i[0][0])/E,B=Math.max(B,H)}if(l){let H=0;!c&&!u||u&&!c&&h?H=rw(w+A*E,l[1][0])/E:H=sw(w+(u?N:-N)*E,l[0][0])/E,B=Math.max(B,H)}}}N=N+(N<0?B:-B),T=T+(T<0?M:-M),s&&(h?I>A*E?N=(KBe(c,u)?-T:T)/E:T=(KBe(c,u)?-N:N)*E:d?(N=T/E,u=c):(T=N*E,c=u));const V=c?w+T:w,q=u?k+N:k;return{width:O+(c?-T:T),height:_+(u?-N:N),x:a[0]*T*(c?-1:1)+V,y:a[1]*N*(u?-1:1)+q}}const P_t={width:0,height:0,x:0,y:0},OJn={...P_t,pointerX:0,pointerY:0,aspectRatio:1};function CJn(e){return[[0,0],[e.measured.width,e.measured.height]]}function _Jn(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 EJn({domNode:e,nodeId:t,getStoreItems:n,onChange:r,onEnd:s}){const a=Th(e);let i={controlDirection:YBe("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={...P_t},x={...OJn};i={boundaries:d,resizeDirection:h,keepAspectRatio:f,controlDirection:YBe(u)};let w,k=null,O=[],_,E,T,N=!1;const I=HCt().on("start",A=>{const{nodeLookup:R,transform:L,snapGrid:M,snapToGrid:B,nodeOrigin:V,paneDomNode:q}=n();if(w=R.get(t),!w)return;k=q?.getBoundingClientRect()??null;const{xSnapped:F,ySnapped:H}=K$(A.sourceEvent,{transform:L,snapGrid:M,snapToGrid:B,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:F,pointerY:H,aspectRatio:b.width/b.height},_=void 0,w.parentId&&(w.extent==="parent"||w.expandParent)&&(_=R.get(w.parentId),E=_&&w.extent==="parent"?CJn(_):void 0),O=[],T=void 0;for(const[D,G]of R)if(G.parentId===t&&(O.push({id:D,position:{...G.position},extent:G.extent}),G.extent==="parent"||G.expandParent)){const z=_Jn(G,w,G.origin??V);T?T=[[Math.min(z[0][0],T[0][0]),Math.min(z[0][1],T[0][1])],[Math.max(z[1][0],T[1][0]),Math.max(z[1][1],T[1][1])]]:T=z}p?.(A,{...b})}).on("drag",A=>{const{transform:R,snapGrid:L,snapToGrid:M,nodeOrigin:B}=n(),V=K$(A.sourceEvent,{transform:R,snapGrid:L,snapToGrid:M,containerBounds:k}),q=[];if(!w)return;const{x:F,y:H,width:D,height:G}=b,z={},$=w.origin??B,{width:U,height:W,x:Y,y:te}=kJn(x,i.controlDirection,V,i.boundaries,i.keepAspectRatio,$,E,T),ee=U!==D,J=W!==G,re=Y!==F&&ee,le=te!==H&&J;if(!re&&!le&&!ee&&!J)return;if((re||le||$[0]===1||$[1]===1)&&(z.x=re?Y:b.x,z.y=le?te:b.y,b.x=z.x,b.y=z.y,O.length>0)){const de=Y-F,ue=te-H;for(const ye of O)ye.position={x:ye.position.x-de+$[0]*(U-D),y:ye.position.y-ue+$[1]*(W-G)},q.push(ye)}if((ee||J)&&(z.width=ee&&(!i.resizeDirection||i.resizeDirection==="horizontal")?U:b.width,z.height=J&&(!i.resizeDirection||i.resizeDirection==="vertical")?W:b.height,b.width=z.width,b.height=z.height),_&&w.expandParent){const de=$[0]*(z.width??0);z.x&&z.x<de&&(b.x=de,x.x=x.x-(z.x-de));const ue=$[1]*(z.height??0);z.y&&z.y<ue&&(b.y=ue,x.y=x.y-(z.y-ue))}const X=SJn({width:b.width,prevWidth:D,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(z,q))}).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 TJn={},XBe=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:()=>{(TJn?"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},jJn=e=>e?XBe(e):XBe,{useDebugValue:NJn}=qe,{useSyncExternalStoreWithSelector:IJn}=VIn,AJn=e=>e;function $_t(e,t=AJn,n){const r=IJn(e.subscribe,e.getState,e.getServerState||e.getInitialState,t,n);return NJn(r),r}const JBe=(e,t)=>{const n=jJn(e),r=(s,a=t)=>$_t(n,s,a);return Object.assign(r,n),r},RJn=(e,t)=>e?JBe(e,t):JBe;function ro(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 RW=g.createContext(null),PJn=RW.Provider,M_t=_y.error001();function Ws(e,t){const n=g.useContext(RW);if(n===null)throw new Error(M_t);return $_t(n,e,t)}function Oo(){const e=g.useContext(RW);if(e===null)throw new Error(M_t);return g.useMemo(()=>({getState:e.getState,setState:e.setState,subscribe:e.subscribe}),[e])}const eUe={display:"none"},$Jn={position:"absolute",width:1,height:1,margin:-1,border:0,padding:0,overflow:"hidden",clip:"rect(0px, 0px, 0px, 0px)",clipPath:"inset(100%)"},D_t="react-flow__node-desc",L_t="react-flow__edge-desc",MJn="react-flow__aria-live",DJn=e=>e.ariaLiveMessage,LJn=e=>e.ariaLabelConfig;function FJn({rfId:e}){const t=Ws(DJn);return o.jsx("div",{id:`${MJn}-${e}`,"aria-live":"assertive","aria-atomic":"true",style:$Jn,children:t})}function zJn({rfId:e,disableKeyboardA11y:t}){const n=Ws(LJn);return o.jsxs(o.Fragment,{children:[o.jsx("div",{id:`${D_t}-${e}`,style:eUe,children:t?n["node.a11yDescription.default"]:n["node.a11yDescription.keyboardDisabled"]}),o.jsx("div",{id:`${L_t}-${e}`,style:eUe,children:n["edge.a11yDescription.default"]}),!t&&o.jsx(FJn,{rfId:e})]})}const vL=g.forwardRef(({position:e="top-left",children:t,className:n,style:r,...s},a)=>{const i=`${e}`.split("-");return o.jsx("div",{className:Zl(["react-flow__panel",n,...i]),style:r,ref:a,...s,children:t})});vL.displayName="Panel";function BJn({proOptions:e,position:t="bottom-right"}){return e?.hideAttribution?null:o.jsx(vL,{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 UJn=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}},zF=e=>e.id;function qJn(e,t){return ro(e.selectedNodes.map(zF),t.selectedNodes.map(zF))&&ro(e.selectedEdges.map(zF),t.selectedEdges.map(zF))}function VJn({onSelectionChange:e}){const t=Oo(),{selectedNodes:n,selectedEdges:r}=Ws(UJn,qJn);return g.useEffect(()=>{const s={nodes:n,edges:r};e?.(s),t.getState().onSelectionChangeHandlers.forEach(a=>a(s))},[n,r,e]),null}const HJn=e=>!!e.onSelectionChangeHandlers;function WJn({onSelectionChange:e}){const t=Ws(HJn);return e||t?o.jsx(VJn,{onSelectionChange:e}):null}const aye=typeof window<"u"?g.useLayoutEffect:g.useEffect,F_t=[0,0],ZJn={x:0,y:0,zoom:1},GJn=["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"],tUe=[...GJn,"rfId"],QJn=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}),nUe={translateExtent:X2,nodeOrigin:F_t,minZoom:.5,maxZoom:2,elementsSelectable:!0,noPanClassName:"nopan",rfId:"1"};function YJn(e){const{setNodes:t,setEdges:n,setMinZoom:r,setMaxZoom:s,setTranslateExtent:a,setNodeExtent:i,reset:l,setDefaultNodesAndEdges:c}=Ws(QJn,ro),u=Oo();aye(()=>(c(e.defaultNodes,e.defaultEdges),()=>{d.current=nUe,l()}),[]);const d=g.useRef(nUe);return aye(()=>{for(const f of tUe){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:FXn(h)}):f==="fitView"?u.setState({fitViewQueued:h}):f==="fitViewOptions"?u.setState({fitViewOptions:h}):u.setState({[f]:h})))}d.current=e},tUe.map(f=>e[f])),null}function rUe(){return typeof window>"u"||!window.matchMedia?null:window.matchMedia("(prefers-color-scheme: dark)")}function KJn(e){const[t,n]=g.useState(e==="system"?null:e);return g.useEffect(()=>{if(e!=="system"){n(e);return}const r=rUe(),s=()=>n(r?.matches?"dark":"light");return s(),r?.addEventListener("change",s),()=>{r?.removeEventListener("change",s)}},[e]),t!==null?t:rUe()?.matches?"dark":"light"}const sUe=typeof document<"u"?document:null;function rD(e=null,t={target:sUe,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
|
`,`
|
|
@@ -670,7 +670,7 @@ Token usage: ${n} input + ${r} output = ${s} total`:`The model stopped generatin
|
|
|
670
670
|
}
|
|
671
671
|
]`,Hbs=[{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 Wbs(){const{isCopied:e,handleCopy:t}=Vd({text:lnt,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:Hbs.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(yt,{variant:"green",size:"xs",children:"required"}):o.jsx(yt,{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(oe,{variant:"ghost",size:"xs",onClick:t,children:e?"Copied":"Copy"})]}),o.jsx(Vr,{variant:"embedded",language:"json",editable:!1,lineNumbers:!1,showCopyButton:!1,value:lnt,className:"p-3"})]}),o.jsxs(oe,{variant:"ghost",as:"a",href:Vbs,target:"_blank",rel:"noopener noreferrer",className:"self-start",children:["Datasets documentation ",o.jsx(Ds,{})]})]})}const noe=10,Zbs=`[
|
|
672
672
|
{ "input": "…", "groundTruth": "…" }
|
|
673
|
-
]`,cnt="flex min-h-0 flex-1 flex-col py-0";function Gbs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:a,onPastedTextChange:i,validation:l,isImporting:c}){return o.jsxs(wl,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[o.jsxs(xl,{variant:"pill",children:[o.jsx(wr,{value:"upload",children:"Upload file"}),o.jsx(wr,{value:"paste",children:"Paste JSON"})]}),o.jsx(Qr,{value:"upload",className:cnt,children:n?o.jsx(Xbs,{file:n,validation:l,onReplace:s,isImporting:c}):o.jsx(Qbs,{onFileSelect:r,disabled:c})}),o.jsx(Qr,{value:"paste",className:cnt,children:o.jsx(Mo,{"aria-label":"JSON items",className:"text-ui-sm min-h-[200px] flex-1 resize-none font-mono",placeholder:Zbs,spellCheck:!1,value:a,onChange:u=>i(u.target.value),disabled:c})})]})}function Qbs({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-6 py-10 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(d3,{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 ",URe]})]})}function Ybs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function Kbs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function Xbs({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,noe);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(dI,{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:Ybs(e.size)}),o.jsx(oe,{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:Kbs(l.input)}),l.hasInput?l.hasGroundTruth?null:o.jsx(yt,{variant:"yellow",size:"xs",children:"no groundTruth"}):o.jsx(yt,{variant:"red",size:"xs",children:"no input"})]},l.index)),a>noe&&o.jsxs("div",{className:"border-border1 text-ui-xs text-neutral3 border-t px-3 py-1.5",children:["+ ",a-noe," more"]})]})}const Jbs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function exs({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}=Fa(),w=a==="upload"?u:p,k=g.useMemo(()=>a==="upload"&&f?{status:"error",kind:"parse",message:f}:Vys(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>lWt){h(`File is larger than ${URe}`);return}try{const R=await Jbs(I);if(A!==b.current)return;c({name:I.name,size:I.size}),d(R),h(null)}catch{if(A!==b.current)return;h("Could not read the file")}},[]),_=g.useCallback(()=>{b.current++,c(null),d(""),h(null)},[]),E=g.useCallback(()=>{b.current++,i("upload"),c(null),d(""),h(null),m("")},[]),T=g.useCallback(()=>{v||(r(!1),setTimeout(E,150))},[v,r,E]),N=g.useCallback(async()=>{if(k.status==="ready"){y(!0);try{await x.mutateAsync({datasetId:e,items:k.items}),Ve.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(E,150)}catch(I){Ve.error(I instanceof Error?I.message:"Failed to import items")}finally{y(!1)}}},[k,x,e,s,r,E]);return o.jsx(vr,{open:n,onOpenChange:T,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-6 py-4",children:[o.jsx(fr,{children:"Import into dataset"}),o.jsxs($s,{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(Pr,{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-6",children:o.jsx(Gbs,{tab:a,onTabChange:i,file:l,onFileSelect:O,onReplace:_,pastedText:p,onPastedTextChange:m,validation:k,isImporting:v})}),o.jsx("div",{className:"p-6",children:o.jsx(Wbs,{})})]})}),o.jsxs(Fl,{className:"border-border1 items-center border-t px-6 py-3 sm:justify-between",children:[o.jsx(txs,{validation:k}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(oe,{onClick:T,disabled:v,children:"Cancel"}),o.jsxs(oe,{variant:"primary",onClick:N,disabled:k.status!=="ready"||v,children:[v&&o.jsx(Vt,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})]})})}function txs({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 ${URe}`;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 nxs(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 pWt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=a=>{a.defaultPrevented||nxs(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 mWt=g.createContext(null);function rxs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=Kr(),i=nyt("/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]);pWt({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(mWt.Provider,{value:h,children:r})}function gWt(){const e=g.useContext(mWt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function sxs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:a}){const[i,l]=ya(),{activeVersion:c}=qRe(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),[E,T]=g.useState([]),[N,I]=g.useState(0),[A,R]=g.useState(""),[L]=vke(A,300),{data:M}=Yg(e),{data:B=[],isLoading:V,setEndOfListElement:q,isFetchingNextPage:F,hasNextPage:H}=IC(e,L||void 0,c),{deleteItems:D}=Fa(),{currentItemId:G,openItem:z,close:$}=gWt(),U=X=>{G===X?$():z(X)},W=X=>{y(X),m(!0)},Y=X=>{k(X),x(!0)},te=X=>{x(X),X||(k([]),I(ne=>ne+1))},ee=X=>{T(X),_(!0)},J=async()=>{await D.mutateAsync({datasetId:e,itemIds:E}),Ve.success(`Deleted ${E.length} items`),_(!1),T([]),I(X=>X+1)},re=X=>{m(!1),y([]),I(ne=>ne+1),n?.(X)},le=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(qbs,{items:B,leftSlot:r,rightSlot:s,belowToolbarSlot:a,isLoading:V,onItemClick:U,featuredItemId:G,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>h(!0),onBulkDeleteClick:ee,onCreateDatasetClick:W,onAddToDatasetClick:Y,datasetName:M?.name,clearSelectionTrigger:N,setEndOfListElement:q,isFetchingNextPage:F,hasNextPage:H,searchQuery:A,activeSearchQuery:L,onSearchChange:R,currentDatasetVersion:M?.version})}),o.jsx(Dbs,{datasetId:e,open:u,onOpenChange:d}),o.jsx(exs,{datasetId:e,datasetName:M?.name,open:f,onOpenChange:h}),o.jsx(vbs,{open:p,onOpenChange:le,items:v,onSuccess:re}),o.jsx(ybs,{open:b,onOpenChange:te,items:w,currentDatasetId:e}),o.jsx(Dt,{open:O,onOpenChange:_,children:o.jsxs(Dt.Content,{children:[o.jsxs(Dt.Header,{children:[o.jsx(Dt.Title,{children:"Delete Items"}),o.jsxs(Dt.Description,{children:["Are you sure you want to delete ",E.length," item",E.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Dt.Footer,{children:[o.jsx(Dt.Cancel,{children:"Cancel"}),o.jsx(Dt.Action,{onClick:J,children:D.isPending?"Deleting...":"Delete"})]})]})})]})}const unt="__create_tag__";function axs({datasetId:e}){const{data:t}=Yg(e),{data:n}=Rm(),{updateDataset:r}=Fa(),[s,a]=g.useState(""),i=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>cWt(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const h=l.map(v=>({label:v,value:v,end:i.includes(v)?o.jsx(Dr,{"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:unt},...h]:h},[l,i,s]),u=h=>{r.mutate({datasetId:e,tags:h},{onError:()=>Ve.error("Failed to update tags")})},d=h=>{const p=h===unt?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(WQ,{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(or,{className:"size-3"})})]},h)),o.jsx(Fo,{options:c,value:void 0,onValueChange:d,onInputValueChange:a,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(pI,{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 vWt({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(yl,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),o.jsx(Mt,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),o.jsx("p",{className:"text-muted-foreground text-xs",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?o.jsx(pY,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function ixs(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 roe({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-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function oxs({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}=Fa(),O=()=>{a("{}"),l(""),u(""),f(""),p(!1),v([]),b(""),w(null)},_=R=>{O(),n(R)},E=async R=>{R.preventDefault();let L;try{L=JSON.parse(s)}catch{Ve.error("Input must be valid JSON");return}let M;if(i.trim())try{M=JSON.parse(i)}catch{Ve.error("Ground Truth must be valid JSON");return}let B;if(c.trim())try{B=JSON.parse(c)}catch{Ve.error("Expected Trajectory must be valid JSON");return}let V;if(d.trim())try{const F=JSON.parse(d);if(!Array.isArray(F)){Ve.error("Tool Mocks must be a JSON array");return}V=F}catch{Ve.error("Tool Mocks must be valid JSON");return}let q;if(y.trim())try{q=JSON.parse(y)}catch{Ve.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:M,expectedTrajectory:B,toolMocks:V,scorerIds:h?m:void 0,requestContext:q}),Ve.success("Item added successfully"),_(!1),r?.()}catch(F){const H=ixs(F);H?w(H):Ve.error(`Failed to add item: ${F instanceof Error?F.message:"Unknown error"}`)}},T=R=>{a(R),x?.field==="input"&&w(null)},N=R=>{l(R),x?.field==="groundTruth"&&w(null)},I=R=>{f(R),x?.field==="toolMocks"&&w(null)},A=()=>{_(!1)};return o.jsxs(ki,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(ki.Top,{children:"Add Item"}),o.jsxs(ki.Content,{children:[o.jsx(ki.Header,{children:o.jsx(ki.Heading,{children:"Add Item"})}),o.jsxs("form",{onSubmit:E,className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Vr,{value:s,onChange:T,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(roe,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{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(roe,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{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(Mt,{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(roe,{field:"toolMocks",errors:x.errors})]}),o.jsx(vWt,{overrideEnabled:h,onOverrideEnabledChange:p,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{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(oe,{type:"button",onClick:A,children:"Cancel"}),o.jsx(oe,{type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}const wk=e=>JSON.stringify(e??null,null,2),lxs=[{key:"input",title:"Input",icon:o.jsx(_O,{}),value:e=>wk(e.input)},{key:"groundTruth",title:"Ground Truth",icon:o.jsx(dy,{}),value:e=>wk(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:o.jsx(Mut,{}),value:e=>e.expectedTrajectory!=null?wk(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:o.jsx(Ud,{}),value:e=>wk(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:o.jsx(Y0e,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":wk(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:o.jsx(nc,{}),value:e=>e.requestContext!=null?wk(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:o.jsx(pI,{}),value:e=>wk(e.metadata)}];function O0e({item:e,diff:t}){return o.jsxs(o.Fragment,{children:[o.jsxs(Fn,{children:[o.jsx(Fn.Key,{children:"Dataset Id"}),o.jsx(Fn.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),o.jsx(Fn.Key,{children:"Version"}),o.jsxs(Fn.Value,{children:["v",e.datasetVersion]}),o.jsx(Fn.Key,{children:"Created"}),o.jsx(Fn.Value,{children:mr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")}),o.jsx(Fn.Key,{children:"Updated"}),o.jsx(Fn.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?mr(new Date(e.updatedAt),"MMM d, yyyy h:mm aaa"):"n/a"})]}),o.jsx("div",{className:"mt-3 grid gap-3",children:lxs.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(wn.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function soe({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-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function cxs({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:"flex items-center gap-2 text-lg font-medium",children:[o.jsx(Qh,{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(Mt,{children:"Input (JSON) *"}),o.jsx(Vr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(soe,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Vr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(soe,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{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(Mt,{children:"Tool Mocks (JSON array, optional)"}),o.jsxs("p",{className:"text-muted-foreground text-xs",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(soe,{field:"toolMocks",errors:y.errors})]}),o.jsx(vWt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:h,onSelectedScorerIdsChange:p,disabled:w}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{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(Mt,{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(oe,{variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),o.jsx(oe,{onClick:x,disabled:w,children:"Cancel"})]})]})]})}const uxs={light:"bg-gray-100 border-gray-300 text-gray-700 shadow-[0_1px_0_rgba(0,0,0,0.1)]",dark:"bg-surface4 border-border1 text-neutral5 shadow-[0_1px_0_rgba(0,0,0,0.3)]"},dxs={default:"h-6 min-w-6 rounded-md px-1.5 text-ui-sm",sm:"h-5 min-w-5 rounded-md px-1 text-ui-xs",xs:"h-4 min-w-4 rounded px-1 text-ui-xs leading-none"},WT=({children:e,theme:t="dark",size:n="default",className:r})=>o.jsx("kbd",{className:K("inline-flex items-center justify-center border font-mono",dxs[n],Yr.transform,"active:scale-95 active:shadow-none",uxs[t],r),children:e}),fxs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function hxs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=zm(),{data:l,isLoading:c}=Yy(),{data:u,isLoading:d}=up(),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(Mt,{children:"Target Type"}),o.jsx(Fo,{options:fxs,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(Mt,{children:m}),o.jsx(Fo,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:h,container:s})]})]})}const pxs=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function mxs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return bm(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(Mt,{children:"Request Context"}),o.jsx(rL,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-sm",children:"Failed to parse request context schema"})}function aoe({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-6"),children:r})]})}function mY({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??""),[E,T]=g.useState(n??null),[N,I]=g.useState({}),[A,R]=g.useState(""),{triggerExperiment:L}=Fa(),{data:M}=Yg(v),{total:B}=IC(v,void 0,b),V=M?.requestContextSchema,q=M?.scorerIds??[],F=E===null&&q.length>0,H=E??q,D=!!(V&&Object.keys(V).length>0),G=!!(v&&w&&O&&f.trim()),z=L.isPending,$=[!f.trim()&&"name",!v&&"dataset",!O&&"target"].filter(Boolean),U=D?Object.values(N).some(le=>le!==void 0&&le!==""):A.trim().length>0,W=le=>{y(le),x(null),T(n??null),I({})},Y=()=>{h(a??""),m(i??""),y(e??""),x(t??null),k(r??""),_(s??""),T(n??null),I({}),R("")},te=()=>{if(D){const le=Object.entries(N).filter(([,X])=>X!==void 0&&X!=="");return le.length>0?Object.fromEntries(le):void 0}if(A.trim()){let le;try{le=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!le||typeof le!="object"||Array.isArray(le))throw new Error("Request Context must be a JSON object");return le}},ee=async()=>{if(!v||!w||!O||!f.trim())return;let le;try{le=te()}catch(X){const ne=X instanceof Error?X.message:"Request Context must be valid JSON";du.error(ne);return}try{const X=await L.mutateAsync({datasetId:v,name:f.trim(),description:p.trim()||void 0,targetType:w,targetId:O,scorerIds:H.length>0?H:void 0,version:b??void 0,requestContext:le});du.success("Experiment triggered successfully"),c(!1),u?.(X.experimentId),Y()}catch(X){const ne=X instanceof Error?X.message:"Failed to trigger experiment";du.error(ne)}},J=()=>{z||(c(!1),Y())},re=le=>{(le.metaKey||le.ctrlKey)&&le.key==="Enter"&&G&&!z&&(le.preventDefault(),ee())};return o.jsx(vr,{open:l,onOpenChange:J,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-6 py-4",children:[o.jsx(fr,{children:"Run experiment"}),o.jsx($s,{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(Pr,{className:"max-h-[70vh] space-y-6 overflow-y-auto px-6 py-5",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"experiment-name",children:"Name *"}),o.jsx(jn,{id:"experiment-name",value:f,onChange:le=>h(le.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:z})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"experiment-description",children:"Description"}),o.jsx(Mo,{id:"experiment-description",value:p,onChange:le=>m(le.target.value),placeholder:"Enter experiment description (optional)",disabled:z,rows:2})]})]}),o.jsxs("ol",{className:"list-none",children:[o.jsxs(aoe,{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(Mt,{children:"Dataset"}),o.jsx(Obs,{value:v,onValueChange:W,container:d})]}),v&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{children:"Version"}),o.jsx(hWt,{datasetId:v,value:b,onValueChange:x,container:d})]})]}),v&&B!==void 0&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[B," ",B===1?"item":"items"]})]}),o.jsxs(aoe,{index:2,done:!!O,children:[o.jsx(hxs,{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(aoe,{index:3,done:H.length>0,isLast:!0,children:o.jsx(pY,{selectedScorers:H,setSelectedScorers:T,disabled:z,container:d,helperText:F?"Pre-filled from the dataset's default scorers.":"Scores are computed after each item runs."})})]}),o.jsxs(lc,{children:[o.jsxs(Bl,{className:"text-ui-sm flex items-center gap-2",children:[o.jsx(qr,{className:"size-4"}),"Request Context (JSON, optional)",U&&o.jsx(yt,{size:"xs",variant:"blue",children:"set"})]}),o.jsx(Ul,{className:"pt-3",children:D?o.jsx(mxs,{requestContextSchema:V,onChange:I}):o.jsx(Vr,{value:A,onChange:R,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),o.jsxs(Fl,{className:"border-border1 items-center border-t px-6 py-4 sm:justify-between",children:[o.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"flex items-center gap-2",children:$.length===0?o.jsxs(o.Fragment,{children:[o.jsx(yt,{variant:"green",indicator:"dot",children:"Ready"}),o.jsxs("span",{className:"text-ui-xs text-neutral3",children:[B??0," items · ",w," · ",H.length," scorers"]})]}):o.jsxs(yt,{variant:"neutral",indicator:"dot",children:["Missing ",$.join(", ")]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(oe,{onClick:J,disabled:z,children:"Cancel"}),o.jsx(oe,{variant:"primary",onClick:ee,disabled:!G||z,children:z?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{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(WT,{size:"xs",children:pxs?"⌘":"Ctrl"}),o.jsx(WT,{size:"xs",children:"↵"})]})]})})]})]})]})})}const yWt=g.createContext(null);function gxs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,children:i}){const l=Kr(),u=nyt("/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]);pWt({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(yWt.Provider,{value:v,children:i})}function bWt(){const e=g.useContext(yWt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function vxs({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}=bWt(),h=g.useMemo(()=>u?n.find(b=>b.itemId===u)?.id??null:null,[n,u]),{data:p}=Ny(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(dY,{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 yxs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${mr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function bxs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=aRe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${yxs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(el.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Kd,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Kd,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}function xWt({children:e,className:t}){return o.jsx("div",{className:K("",t),children:e})}function xxs({date:e,className:t,withTime:n=!1}){const r=e?q0t(new Date(e)):!1,s=e?Y3(new Date(e))?"Today":mr(new Date(e),"MMM dd"):"",a=e&&!r?mr(new Date(e),"yyyy"):"",i=e&&n?`${mr(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 VRe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function wxs({columns:e,isSelectionActive:t,children:n}){return o.jsx("div",{className:K("sticky top-0 z-10 mb-4 rounded-lg bg-surface3 px-4"),children:o.jsx("div",{className:K("grid items-center gap-4 text-left text-ui-xs tracking-widest text-neutral3 uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:VRe(e)},children:n})})}function Sxs({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function kxs({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 Oxs({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function Cxs({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function _xs({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 Exs({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-6 rounded-lg px-3 py-[0.6rem] text-left","hover:bg-surface4",Yr.colors,W3.visible,n),children:e});return s==null?a:o.jsxs(gn,{children:[o.jsx(fn,{render:a}),o.jsx(hn,{children:s})]})}function Txs({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-8 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(jc,{}):o.jsx(Cm,{})," ",t]}):e})}function jxs({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-8 flex justify-center opacity-50",children:[e&&r,!t&&!e&&s]}):null}function Nxs({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-8 pt-6 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(wu,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(Mf,{})]})]})]})}function Ixs({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function Axs({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",Yr.colors,{"selected-row":e,"grid px-4 gap-4 ":n}),style:{gridTemplateColumns:VRe(n)},children:t})}function Rxs({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-4 rounded-lg px-4 text-left",Yr.colors,W3.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!i},a),style:{gridTemplateColumns:VRe(s)},disabled:i,children:r});return l==null?d:o.jsxs(gn,{children:[o.jsx(fn,{render:d}),o.jsx(hn,{children:l})]})}function Pxs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function $xs({status:e}){return e?o.jsxs(gn,{children:[o.jsx(fn,{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(hn,{children:Pxs(e)})]}):null}function Mxs({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 dnt={latest:"Latest version",deleted:"Deleted in this version"};function Dxs({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(xWt,{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?mr(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":dnt.latest,children:o.jsx(yt,{variant:"blue",size:"sm",icon:o.jsx(lS,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":dnt.deleted,children:o.jsx(yt,{variant:"red",size:"sm",icon:o.jsx(B0e,{})})})]})]})}const Ap=Object.assign(Ixs,{Header:wxs,HeaderCol:Sxs,Items:Oxs,Scroller:Cxs,Row:Axs,RowButton:Rxs,Message:Txs,NextPageLoading:jxs,Pagination:Nxs,Cell:xWt,TextCell:Mxs,StatusCell:$xs,VersionCell:Dxs,IdCell:kxs,DateCell:xxs,LinkCell:Exs,LabelCell:_xs}),Lxs=[{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"}],H9={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(Fr,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(Qen,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(Sut,{}),tooltip:"Same in both versions"}};function ioe({red:e=!1,tooltip:t}){return o.jsxs(gn,{children:[o.jsx(fn,{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(B0e,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(hn,{children:t})]})}function ooe({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}=H9[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(yt,{variant:n,size:"xs",icon:r})})]})}function Fxs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function fnt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function zxs({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=ln(),l=t>n;return o.jsx(Ap,{children:o.jsx(Ap.Scroller,{children:o.jsx(Ap.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=Fxs(u,d),h=fnt({otherVersionExists:d!==void 0,status:f,isNewer:l}),p=fnt({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(Ap.Row,{columns:Lxs,children:[o.jsx(Ap.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?H9[h].tooltip:void 0,children:o.jsx(ooe,{variant:h,version:u.datasetVersion})}):o.jsx(Ap.Cell,{className:"flex items-center justify-center",children:o.jsx(ioe,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?H9[p].tooltip:void 0,children:o.jsx(ooe,{variant:p,version:d.datasetVersion})}):o.jsx(Ap.Cell,{className:"flex items-center justify-center",children:o.jsx(ioe,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:H9.same.tooltip,children:o.jsx(ooe,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?version=${u?.datasetVersion}&compare=${d?.datasetVersion}`,children:"Compare"}):o.jsx(Ap.Cell,{children:o.jsx(ioe,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}function Bxs(){const e=Kr(),[t,n]=g.useState(""),[r,s]=g.useState("all"),[a,i]=g.useState("all"),{data:l=[],isLoading:c,error:u,isFetchingNextPage:d,hasNextPage:f,setEndOfListElement:h}=m$n(),{data:p,isLoading:m,error:v}=QH(),y=g.useMemo(()=>p?.experiments??[],[p?.experiments]),b=g.useMemo(()=>Xys(l),[l]),x=c||m,w=u||v,k=()=>{e("/datasets/new")};if(w&&hs(w))return o.jsx(Zn,{children:o.jsx(Es,{})});if(w&&ps(w))return o.jsx(Zn,{children:o.jsx(Os,{resource:"datasets"})});if(w)return o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load datasets",message:w.message})});if(l.length===0&&!x)return o.jsx(Zn,{children:o.jsx(Jys,{onCreateClick:k})});const O=r!=="all"||a!=="all"||t!=="",_=()=>{n(""),s("all"),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(sbs,{search:t,onSearchChange:n,experimentFilter:r,onExperimentFilterChange:s,tagFilter:a,onTagFilterChange:i,tagOptions:b,onReset:_,hasActiveFilters:O,onCreateClick:k})}),o.jsx(Yys,{datasets:l,experiments:y,isLoading:x,search:t,experimentFilter:r,tagFilter:a,isFetchingNextPage:d,hasNextPage:f,setEndOfListElement:h})]})}function h8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function Uxs(){const{datasetId:e}=ur(),t=Kr(),[n,r]=ya(),{activeVersion:s,handleVersionChange:a}=qRe(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}=Yg(e),{data:b=[],isLoading:x}=IC(e,void 0,s),w=!x&&b.length===0;if(y)return null;if(v&&hs(v))return o.jsx(h8,{children:o.jsx(Es,{})});if(v&&ps(v))return o.jsx(h8,{children:o.jsx(Os,{resource:"datasets"})});if(v&&h0(v)||!y&&!v&&!m)return o.jsx(h8,{children:o.jsx(pr,{iconSlot:o.jsx($g,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(oe,{as:yo,to:"/datasets",children:[o.jsx(wu,{}),"Back to Datasets"]})})});if(v)return o.jsx(h8,{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(rxs,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"h-full",children:[o.jsx(Lt,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Lt.MainArea,{children:o.jsx(sxs,{datasetId:e,onAddItemClick:()=>u(!0),belowToolbarSlot:o.jsx(axs,{datasetId:e}),leftSlot:o.jsx("span",{className:"text-ui-sm text-neutral3 mr-3 whitespace-nowrap",children:m?.createdAt?`Created ${mr(new Date(m.createdAt),"MMM d")}`:""}),rightSlot:o.jsxs(ts,{children:[o.jsxs(oe,{as:yo,to:`/experiments?dataset=${e}`,children:[o.jsx(W0e,{}),"View experiments"]}),o.jsx(hWt,{datasetId:e,value:s,onValueChange:a,currentVersion:m?.version,className:"w-36"}),w?o.jsxs(gn,{children:[o.jsx(fn,{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.jsxs(oe,{variant:"primary",children:[o.jsx(Pc,{}),"Run Experiment"]})})})}),o.jsx(hn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(oe,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Pc,{}),"Run Experiment"]}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(oe,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(XS,{})})}),o.jsxs(ot.Content,{align:"end",className:"w-48",children:[o.jsxs(ot.Item,{onSelect:()=>{t(`/datasets/${e}/edit`)},children:[o.jsx(Qh,{})," Edit Dataset"]}),o.jsxs(ot.Item,{onSelect:()=>p(!0),children:[o.jsx(zd,{})," Duplicate Dataset"]}),o.jsxs(ot.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(ll,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(Fg,{})]}),o.jsx(mY,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:i,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx(oxs,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(bbs,{open:h,onOpenChange:p,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx(kbs,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:O})]})}function loe({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function qxs(){const{datasetId:e}=ur(),t=Kr(),{data:n,error:r,isLoading:s}=Yg(e),a=()=>{t(`/datasets/${e}`)};return s?null:r&&hs(r)?o.jsx(loe,{children:o.jsx(Es,{})}):r&&ps(r)?o.jsx(loe,{children:o.jsx(Os,{resource:"datasets"})}):r||!n?o.jsx(loe,{children:o.jsx(Fs,{title:"Failed to load dataset",message:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Nh,{className:"mb-6 p-0",children:o.jsxs(Nh.Column,{children:[o.jsxs(Nh.Title,{children:[o.jsx($g,{})," Edit dataset"]}),o.jsx(Nh.Description,{children:n.name})]})}),o.jsx(Ic,{className:"p-6",children:o.jsx(Sbs,{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 gY({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 Vxs(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 Hxs({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:a}=ln(),{updateItem:i,deleteItem:l}=Fa(),[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),[_,E]=g.useState(t.scorerIds??[]),[T,N]=g.useState(""),[I,A]=g.useState(null),[R,L]=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),E(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),L(!1),A(null))},[t?.id]);const M=n.findIndex(z=>z.id===t.id),B=M>0?()=>r(n[M-1].id):void 0,V=M>=0&&M<n.length-1?()=>r(n[M+1].id):void 0,q=async()=>{let z;try{z=JSON.parse(d)}catch{Ve.error("Input must be valid JSON");return}let $;if(h.trim())try{$=JSON.parse(h)}catch{Ve.error("Ground Truth must be valid JSON");return}let U;if(m.trim())try{U=JSON.parse(m)}catch{Ve.error("Metadata must be valid JSON");return}let W=null;if(y.trim())try{W=JSON.parse(y)}catch{Ve.error("Expected Trajectory must be valid JSON");return}let Y;if(x.trim())try{const J=JSON.parse(x);if(!Array.isArray(J)){Ve.error("Tool Mocks must be a JSON array");return}Y=J}catch{Ve.error("Tool Mocks must be valid JSON");return}else Y=[];let te;if(T.trim())try{te=JSON.parse(T)}catch{Ve.error("Request Context must be valid JSON");return}let ee;k?ee=_:t.scorerIds!==void 0&&(ee=null);try{const J=await i.mutateAsync({datasetId:e,itemId:t.id,input:z,groundTruth:$,metadata:U,expectedTrajectory:W,toolMocks:Y,scorerIds:ee,requestContext:te});Ve.success("Item updated successfully"),O(J.scorerIds!==void 0),E(J.scorerIds??[]),u(!1),A(null)}catch(J){const re=Vxs(J);re?A(re):Ve.error(`Failed to update item: ${J instanceof Error?J.message:"Unknown error"}`)}},F=()=>{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),E(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},H=z=>{f(z),I?.field==="input"&&A(null)},D=z=>{p(z),I?.field==="groundTruth"&&A(null)},G=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Ve.success("Item deleted successfully"),L(!1),s()}catch(z){Ve.error(`Failed to delete item: ${z instanceof Error?z.message:"Unknown error"}`)}};return o.jsxs(o.Fragment,{children:[o.jsxs(wn,{children:[o.jsxs(wn.Header,{children:[o.jsxs(wn.Heading,{children:["Item ",o.jsxs("b",{children:["# ",t.id.length>12?`${t.id.slice(0,12)}…`:t.id]})]}),o.jsxs(ts,{className:"ml-auto shrink-0",children:[o.jsx(wn.NextPrevNav,{onPrevious:B,onNext:V,previousLabel:"Previous item",nextLabel:"Next item"}),!c&&o.jsxs(o.Fragment,{children:[o.jsx(oe,{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(X0e,{})}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(oe,{size:"md","aria-label":"Actions menu",children:o.jsx(XS,{})})}),o.jsxs(ot.Content,{align:"end",className:"w-48",children:[o.jsxs(ot.Item,{onSelect:()=>u(!0),children:[o.jsx(Qh,{}),"Edit"]}),o.jsxs(ot.Item,{onSelect:()=>L(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(ll,{}),"Delete Item"]})]})]})]}),o.jsx(wn.CloseButton,{onClick:s,tooltip:"Close detail panel"})]})]}),o.jsx(wn.Content,{children:c?o.jsx(cxs,{inputValue:d,setInputValue:H,groundTruthValue:h,setGroundTruthValue:D,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:O,selectedScorerIds:_,setSelectedScorerIds:E,requestContextValue:T,setRequestContextValue:N,validationErrors:I,onSave:q,onCancel:F,isSaving:i.isPending}):o.jsx(O0e,{item:t})})]}),o.jsx(Dt,{open:R,onOpenChange:L,children:o.jsxs(Dt.Content,{children:[o.jsxs(Dt.Header,{children:[o.jsx(Dt.Title,{children:"Delete Item"}),o.jsx(Dt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Dt.Footer,{children:[o.jsx(Dt.Cancel,{children:"Cancel"}),o.jsx(Dt.Action,{onClick:G,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function Wxs(){const{itemId:e}=ur(),{datasetId:t,items:n,isLoadingItems:r,openItem:s,close:a}=gWt(),i=g.useMemo(()=>n.find(d=>d.id===e)??null,[n,e]),{data:l,isLoading:c}=CVt(i?"":t,!i&&e?e:""),u=i??l??null;return e?o.jsx(gY,{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(Hxs,{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(Vt,{})})}):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(pr,{iconSlot:o.jsx($g,{}),titleSlot:"Item not found",descriptionSlot:`No loaded item "${e}".`,actionSlot:o.jsx(oe,{onClick:a,children:"Close"})})})})}):null}function hnt(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 pnt(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]})," · ",mr(r,"MMM d, HH:mm")]}),n.isLatest?o.jsx(yt,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function mnt(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function Zxs(){const{datasetId:e,itemId:t}=ur(),[n,r]=ya(),s=mnt(n.get("version")),a=mnt(n.get("compare")),i=n.get("view")==="diff",{data:l,error:c}=Yg(e??""),{data:u,isLoading:d}=Rys(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}=Pys(e??"",t??"",p??0,l?.version),y=(_,E)=>r(T=>{const N=new URLSearchParams(T);return E==null?N.delete(_):N.set(_,String(E)),N},{replace:!0});if(c&&hs(c))return o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Es,{})})});if(c&&ps(c))return o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"datasets"})})});if(!e||!t)return o.jsx(ia,{children:o.jsx(Ox,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Item not found."})})})});const b=!!(f&&m),x=i&&b,w=f?hnt(f,e):null,k=m?hnt(m,e):null,O=(f?.datasetVersion??0)<(m?.datasetVersion??0);return o.jsxs(ia,{children:[o.jsx(l_,{owner:"dataset-item-versions",children:b&&o.jsx(oe,{variant:"outline",onClick:()=>y("view",i?null:"diff"),children:i?o.jsxs(o.Fragment,{children:[o.jsx(V0e,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(gJt,{})," Diff View"]})})}),o.jsx(Lt,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-6 md:grid-cols-2",children:[o.jsxs(Ic,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(tS,{children:o.jsx(gnt,{name:"version",value:h!=null?String(h):"",options:pnt(u??[],p!=null?new Set([p]):void 0),onValueChange:_=>y("version",Number(_))})}),o.jsx($f,{className:"grid content-start gap-8 overflow-y-auto",children:d?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):w?o.jsx(O0e,{item:w,diff:x&&k?{against:k,side:O?"a":"b"}:void 0}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})})]}),o.jsxs(Ic,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(tS,{children:o.jsx(gnt,{name:"compare",value:p!=null?String(p):"",placeholder:"Select a version to compare",options:pnt(u??[],h!=null?new Set([h]):void 0),onValueChange:_=>y("compare",Number(_))})}),o.jsx($f,{className:"grid content-start gap-8 overflow-y-auto",children:p==null?o.jsx(pr,{className:"h-full",iconSlot:o.jsx(hpe,{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-sm",children:"Loading..."}):k?o.jsx(O0e,{item:k,diff:x&&w?{against:w,side:O?"b":"a"}:void 0}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",p," not found"]})})]})]})})]})}function gnt({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(X0e,{className:"size-4 opacity-50"}),o.jsxs(ka,{name:e,value:t,onValueChange:s,children:[o.jsx(Ca,{"aria-label":e==="compare"?"Compare version":"Version",className:"w-full",children:o.jsx(Oa,{placeholder:r,className:"flex-1"})}),o.jsx(_a,{children:n.map(a=>o.jsx(jr,{value:a.value,disabled:a.disabled,children:a.label},a.value))})]})]})}function Gxs(){const{datasetId:e}=ur(),[t]=ya(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=Kr(),{data:s,error:a}=Yg(e??""),i=IC(e??"",void 0,n[0]??null),l=IC(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&&hs(a))return o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Es,{})})});if(a&&ps(a))return o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(ia,{children:o.jsx(Ox,{children:o.jsx("div",{className:"text-neutral4 py-8 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(ia,{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-6",children:[o.jsxs(Nh,{children:[o.jsxs(Nh.Column,{children:[o.jsxs(Nh.Title,{children:[o.jsx(Ctn,{})," Compare Dataset Versions"]}),o.jsx(Nh.Description,{children:o.jsxs(Ad,{children:[o.jsx(X0e,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(Nh.Column,{children:o.jsxs(oe,{as:yo,to:`/datasets/${e}`,children:[o.jsx(wu,{}),"Back to Dataset"]})})]}),o.jsx(bM,{children:o.jsxs(el,{children:[o.jsx(bxs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:p}),o.jsx(zxs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h})]})})]})})})}const Qxs=["agent","workflow","scorer","processor"],Yxs=new Set(Qxs);function Kxs(e){return typeof e=="string"&&Yxs.has(e)}function Xxs(){const e=Kr(),[t]=ya(),n=t.get("targetType"),r=Kxs(n)?n:void 0,s=t.get("targetIds"),a=r&&s?s.split(",").map(i=>i.trim()).filter(Boolean):void 0;return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Nh,{className:"mb-6 p-0",children:o.jsxs(Nh.Column,{children:[o.jsxs(Nh.Title,{children:[o.jsx($g,{})," Create new dataset"]}),o.jsx(Nh.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Ic,{className:"p-6",children:o.jsx(gbs,{targetType:r,targetIds:a,onSuccess:i=>{e(`/datasets/${i}`)},onCancel:()=>{e(-1)}})})]})})]})}function C0e({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-8",t),children:e})}function Jxs(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 e0s({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=Jxs(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 wWt({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:a}=Fa(),i=async()=>{try{await a.mutateAsync(n),Ve.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Ve.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return o.jsx(Dt,{open:e,onOpenChange:t,children:o.jsxs(Dt.Content,{children:[o.jsxs(Dt.Header,{children:[o.jsx(Dt.Title,{children:"Delete Experiment"}),o.jsxs(Dt.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(Dt.Footer,{children:[o.jsx(oe,{variant:"primary",size:"lg",onClick:i,disabled:a.isPending,children:a.isPending?"Deleting...":"Delete"}),o.jsx(Dt.Cancel,{children:"Cancel"})]})]})})}function SWt(e){const t=b0(e.id)??e.id;return e.name||`Experiment #${t}`}const t0s=60;function n0s({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:SWt(e)})}function r0s({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<=t0s?n:o.jsxs(gn,{children:[o.jsx(fn,{asChild:!0,children:n}),o.jsx(hn,{children:t})]})}const vY=()=>{const{requestContext:e}=vs(),t=Ze();return mt({queryKey:["processors"],queryFn:()=>t.listProcessors(e)})},kWt=(e,t)=>{const n=Ze(),{requestContext:r}=vs();return mt({queryKey:["processor",e],queryFn:()=>n.getProcessor(e).details(r),enabled:!!e})},s0s=()=>{const e=Ze(),{requestContext:t}=vs();return bn({mutationFn:async({processorId:n,phase:r,messages:s,agentId:a})=>e.getProcessor(n).execute({phase:r,messages:s,agentId:a,requestContext:t})})};function OWt(){const{data:e}=zm(),{data:t}=Yy(),{data:n}=up(),{data:r}=vY();return{agents:e,workflows:t,scorers:n,processors:r}}const CWt={agent:co,workflow:Su,scorer:M_,processor:aV},_Wt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},a0s="External (caller-run)";function EWt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:a,targetId:i}=e;if(!i)return a0s;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 i0s({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(ve.Cell,{children:o.jsx(n0s,{experiment:e})}),o.jsx(ve.Cell,{children:o.jsx(r0s,{experiment:e})}),t!==void 0&&o.jsx(ve.TextCell,{children:t}),o.jsx(ve.Cell,{children:o.jsx(o0s,{experiment:e})}),o.jsx(ve.Cell,{children:o.jsx(yt,{variant:OVt[r]??"neutral",indicator:"dot",children:qT[r]??r})}),o.jsx(ve.TextCell,{className:"text-center",children:i}),o.jsx(ve.TextCell,{className:"text-center",children:s}),o.jsx(ve.TextCell,{className:"text-center",children:o.jsx("span",{className:a>0?"text-accent2":"",children:a})}),o.jsx(ve.Cell,{className:"text-center",children:o.jsx(l0s,{review:n})}),o.jsx(ve.TextCell,{children:dfs(e.createdAt)})]})}function o0s({experiment:e}){const t=OWt(),n=EWt(e,t),r=e.targetId?e.targetType:null,s=r?CWt[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":_Wt[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function l0s({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(yt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(yt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const TWt=`${ofs} ${lfs} ${cfs} ${ufs}`,vnt=`${TWt} auto`,c0s=[{label:Cv.experiment},{label:Cv.description},{label:Cv.dataset},{label:Cv.target},{label:Cv.status},{label:Cv.items,className:"text-center"},{label:Cv.succeeded,className:"text-center"},{label:Cv.failed,className:"text-center"},{label:Cv.review,className:"text-center"},{label:Cv.date}];function u0s({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all",selection:l}){const c=l!==void 0,{paths:u,Link:d}=ln(),f=g.useMemo(()=>{const k=new Map;return t?.forEach(O=>k.set(O.id,O.name)),k},[t]),h=g.useMemo(()=>[...e].sort((k,O)=>{const _=k.createdAt?new Date(k.createdAt).getTime():0;return(O.createdAt?new Date(O.createdAt).getTime():0)-_}),[e]),p=g.useMemo(()=>{const k=s.toLowerCase();return h.filter(O=>{const _=O.datasetId?f.get(O.datasetId)??"":"",E=!k||O.id.toLowerCase().includes(k)||(O.name??"").toLowerCase().includes(k)||_.toLowerCase().includes(k)||(O.targetId??"").toLowerCase().includes(k),T=a==="all"||O.status===a,N=i==="all"||O.datasetId===i;return E&&T&&N})},[h,s,f,a,i]),{containerRef:m,getRowProps:v}=ol({count:p.length}),[y,b]=g.useState(null);if(r)return o.jsx(Do,{columns:vnt});const x=c?`auto ${TWt}`:vnt,w=c0s.map(k=>o.jsx(ve.TopCell,{className:k.className,children:k.label},k.label));return o.jsxs(ve,{columns:x,scrollRef:m,children:[o.jsx(ve.Top,{hasLeadingCell:c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(ve.TopCell,{children:" "}),o.jsx(ve.TopCells,{colStart:2,children:w})]}):o.jsxs(o.Fragment,{children:[w,o.jsx(ve.TopCell,{"aria-hidden":!0,children:null})]})}),p.map((k,O)=>{const _=k.datasetId?f.get(k.datasetId)??b0(k.datasetId)??k.datasetId:"—",E=o.jsx(i0s,{experiment:k,datasetName:_,review:n?.get(k.id)});if(!l)return o.jsxs(ve.RowWrapper,{children:[o.jsx(ve.RowLink,{colEnd:-2,to:u.experimentLink(k.id),LinkComponent:d,...v(O),children:E}),o.jsx(ve.ActionsCell,{className:"pl-2",children:o.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs",tooltip:"Delete experiment","aria-label":`Delete experiment ${k.name??k.id}`,onClick:I=>{I.stopPropagation(),b(k)},children:o.jsx(ll,{className:"size-4"})})})]},k.id);const T=l.selectedExperimentIds.includes(k.id),N=()=>l.onToggleSelection(k.id);return o.jsxs(ve.RowWrapper,{children:[o.jsx(ve.SelectCell,{checked:T,onToggle:N,"aria-label":`Select experiment ${k.id}`}),o.jsx(ve.RowButton,{colStart:2,featured:T,onClick:N,...v(O),children:E})]},k.id)}),y&&o.jsx(wWt,{open:!0,onOpenChange:k=>{k||b(null)},experimentId:y.id,experimentName:y.name??void 0})]})}const d0s=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function f0s(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const p8={completed:G7.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},h0s=[{label:"Completed",color:p8.completed},{label:"Running",color:p8.running},{label:"Pending",color:p8.pending},{label:"Failed",color:p8.failed}];function p0s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(qt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(qt.Loading,{}):r?o.jsx(qt.Error,{message:"Failed to load experiments data"}):o.jsx(qt.Content,{children:i?o.jsx(nI,{data:s,segments:h0s,maxVal:a,fmt:l=>String(l)}):o.jsx(qt.NoData,{message:"No experiments have been run yet"})})]})}const m0s=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),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.jsxs(oe,{variant:"primary",onClick:e,children:[o.jsx(Pc,{}),"Run Experiment"]}),o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Ds,{})]})]})})});function g0s({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c,onRunClick:u,runTooltip:d="Run an experiment",onCompareClick:f,selection:h}){const p=h?.selectedCount===2&&!h.compareDisabledReason;return o.jsxs("div",{className:"flex min-h-9 flex-wrap items-center gap-2",children:[o.jsx("div",{className:"max-w-120 min-w-48 flex-1",children:o.jsx(Uc,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),o.jsxs(ts,{children:[o.jsx(Kd,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...d0s],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Kd,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(oe,{onClick:l,size:"sm",variant:"default",children:[o.jsx(or,{className:"size-3"})," Reset"]})]}),h?o.jsxs(ts,{className:"ml-auto shrink-0 whitespace-nowrap",children:[o.jsxs(Dh,{className:"gap-2",children:[o.jsxs(yt,{size:"sm",variant:h.selectedCount<2?"red":"green",children:[h.selectedCount," / 2"]}),"selected",h.compareDisabledReason&&o.jsxs("span",{className:"text-accent2",children:["· ",h.compareDisabledReason]})]}),o.jsxs(oe,{variant:"primary",disabled:!p,onClick:h.onExecuteCompare,children:[o.jsx(hpe,{}),"Compare Experiments"]}),o.jsx(oe,{onClick:h.onCancelSelection,children:"Cancel"})]}):o.jsxs(ts,{className:"ml-auto shrink-0",children:[f&&o.jsxs(oe,{onClick:f,tooltip:"Select two experiments of the same dataset to compare",children:[o.jsx(hpe,{}),"Compare"]}),u&&o.jsxs(oe,{onClick:u,tooltip:d,variant:"primary",children:[o.jsx(Pc,{}),"Run Experiment"]})]})]})}const v0s={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},ynt=e=>e?e instanceof Date?e.toISOString():e:null,bnt=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},xnt=(e,t,n)=>{if(!e)return v0s;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:ynt(t?.startedAt),completedAt:ynt(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))}},y0s=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:a,contenderScores:i})=>{if(!e)return[];const l=bnt(r),c=bnt(s);return e.items.map(u=>{const d=xnt(u.results[t],l.get(u.itemId),a?.[u.itemId]),f=xnt(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 Bk({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(lc,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(Bl,{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(qr,{}),e]}),t]}),o.jsx(Ul,{role:"region","aria-label":e,children:s})]})}function wnt({label:e,value:t}){return t==null?null:o.jsx(Bk,{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 jWt({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-sm",t),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?o.jsx(fut,{className:"size-3.5"}):e<0?o.jsx(GYt,{className:"size-3.5"}):null]})}function NWt({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 flex min-w-0 items-center gap-1.5 text-sm font-medium hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(M_,{}),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 font-mono text-sm",children:t!=null?t.toFixed(2):"-"}),n!=null&&o.jsx(jWt,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-sm",children:r})]})}function Snt(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function b0s(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 x0s="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 knt({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],a=b0s(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(Vt,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 py-8 text-center text-sm",children:"Not present in this experiment"});const i=Snt(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[a&&o.jsxs(gn,{children:[o.jsx(fn,{render:o.jsxs("p",{className:"text-neutral3 flex items-center justify-end gap-1.5 text-sm [&>svg]:size-3.5",children:[o.jsx(lS,{}),a]})}),o.jsx(hn,{children:"Run duration"})]}),s.error?o.jsx(Bk,{title:"Error",tone:"negative",actions:o.jsx(Da,{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(Bk,{title:"Output",actions:o.jsx(Da,{content:i}),children:o.jsx("pre",{className:x0s,children:i})}),s.scores.length>0&&o.jsx(Bk,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx(NWt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(Bk,{title:"Comment",defaultOpen:!1,children:o.jsx("p",{className:"text-neutral3 text-sm",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&o.jsx(Bk,{title:"Metadata",defaultOpen:!1,children:o.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>o.jsxs("div",{className:"flex items-start justify-between gap-4 text-sm",children:[o.jsx("dt",{className:"text-neutral3",children:l}),o.jsx("dd",{className:"text-neutral5 font-mono break-all",children:Snt(c)})]},l))})})]})}const w0s={baseline:"Baseline",contender:"Contender"},S0s={baseline:"purple",contender:"blue"},k0s="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function Ont({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:a,paths:i}=ln(),l=w0s[e],c=t?b0(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(yt,{variant:S0s[e],size:"xs",children:l}),t&&o.jsx(oe,{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(Ad,{children:[o.jsx(l3,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(a,{href:i.agentLink(t.targetId),className:k0s,children:[o.jsx(co,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Ad,{children:[o.jsx(But,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Ad,{children:[o.jsx(UV,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Ad,{children:[o.jsx(Y9,{})," ",mr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(Bk,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:h,delta:p})=>o.jsx(NWt,{scorerId:f,value:h,delta:r?p:null},f))})})]})}const QE="min-w-0 px-4 py-3";function O0s({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=ln(),{data:a,isLoading:i,error:l}=$ys(e,t,n),{data:c}=XD(e,t),{data:u}=XD(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}=JD({datasetId:e,experimentId:f,experimentStatus:p?.status}),{data:b,isLoading:x}=JD({datasetId:e,experimentId:h,experimentStatus:m?.status}),{data:w}=Ny(f,p?.status),{data:k}=Ny(h,m?.status),O=g.useMemo(()=>y0s({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(T=>Object.keys(T.deltas)))].sort(),[O]),E=g.useMemo(()=>{const T=(A,R)=>{const L=O.map(M=>M[A].scores.find(B=>B.scorerId===R)?.value).filter(M=>M!=null);return L.length>0?L.reduce((M,B)=>M+B,0)/L.length:null},N=_.map(A=>({scorerId:A,average:T("baseline",A),delta:null})),I=_.map(A=>{const R=T("baseline",A),L=T("contender",A);return{scorerId:A,average:L,delta:R!=null&&L!=null?L-R:null}});return{baseline:N,contender:I}},[O,_]);return i?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Vt,{})}):l?o.jsx(An,{variant:"warning",title:"Error loading comparison",children:o.jsx(An.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!a||a.items.length===0?o.jsx("div",{className:"text-neutral4 py-8 text-center text-sm",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:`${QE} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:QE,children:o.jsx(Ont,{side:"baseline",experiment:p,summary:E.baseline,versionMismatch:d})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:QE,children:o.jsx(Ont,{side:"contender",experiment:m,summary:E.contender,versionMismatch:d,showDeltas:!0})})]}),O.map(T=>{const N=Object.entries(T.deltas).filter(([,I])=>I!=null&&I!==0);return o.jsxs("div",{role:"row","aria-label":T.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:`${QE} grid content-start gap-1`,children:[o.jsx(r,{href:s.datasetItemLink(e,T.itemId),"aria-label":`Open item ${T.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",T.baseline.present&&T.contender.present?"text-neutral4":"text-neutral1"),children:o.jsx("span",{className:"min-w-0",children:T.itemId})}),N.length>0&&o.jsx("span",{className:"flex flex-wrap items-center gap-2",children:N.map(([I,A])=>o.jsx(jWt,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx(wnt,{label:"Input",value:T.input}),o.jsx(wnt,{label:"Ground truth",value:T.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:QE,children:o.jsx(knt,{side:"baseline",row:T,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:QE,children:o.jsx(knt,{side:"contender",row:T,isLoading:x,showDeltas:!0})})]},T.itemId)})]})})}const C0s=100;function yY(e){const t=Ze(),n={perPage:C0s};return mt({queryKey:e?["dataset-experiments",e,n]:["experiments",n],queryFn:()=>e?t.listDatasetExperiments(e,n):t.listExperiments(n)})}const IWt=(e,t)=>{const n=Ze(),{data:r,isLoading:s}=yY(void 0),a=r?.experiments,i=t?a?.filter(c=>c.id===t):a,l=mt({queryKey:["review-items",e,t??"all",i?.map(c=>c.id)],queryFn:async()=>!i||i.length===0?[]:(await Promise.all(i.map(async u=>{if(!u.datasetId)return[];try{const{results:d}=await n.listDatasetExperimentResults(u.datasetId,u.id);return d.filter(f=>f.status===e).map(f=>({id:f.id,input:f.input,output:f.output,error:f.error,itemId:f.itemId,experimentId:f.experimentId,datasetId:u.datasetId??void 0,traceId:f.traceId??void 0,scores:f.scores?Object.fromEntries(f.scores.map(h=>[h.scorerId,h.score??0])):{},tags:f.tags??[],createdAt:f.createdAt,status:f.status,groundTruth:f.groundTruth,toolMockReport:f.toolMockReport}))}catch{return[]}}))).flat(),enabled:!!a,refetchOnWindowFocus:!1});return{...l,isLoading:l.isLoading||s}},_0s=({experimentId:e}={})=>IWt("needs-review",e),E0s=({experimentId:e}={})=>IWt("complete",e),T0s=[{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"}],coe="__untagged__",uoe="all",j0s=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}];function N0s({datasetId:e,experimentId:t,featuredItemId:n,detailPanelVariant:r="inline",toolbarStart:s,toolbarEnd:a}){const i=Ze(),{paths:l}=ln(),{data:c}=Yg(e??""),{data:u,isLoading:d}=_0s({experimentId:t}),{data:f,isLoading:h}=E0s({experimentId:t}),{updateExperimentResult:p}=Fa(),[m,v]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&v(n)},[n]);const[y,b]=g.useState(null),[x,w]=g.useState(new Set),[k,O]=g.useState(!1),[_,E]=g.useState(!1),[T,N]=g.useState(!1),[I,A]=g.useState(""),[R,L]=g.useState(""),[M,B]=g.useState(""),[V,q]=g.useState([]),[F,H]=g.useState(!1),D=g.useMemo(()=>u??[],[u]),G=g.useMemo(()=>{const ae=new Set;if(c?.tags)for(const ce of c.tags)ae.add(ce);for(const ce of D)for(const me of ce.tags)ae.add(me);return[...ae].sort()},[c,D]),z=g.useCallback(ae=>{!c||!e||(c.tags??[]).includes(ae)},[c,e]),$=g.useMemo(()=>y?y===coe?D.filter(ae=>ae.tags.length===0):D.filter(ae=>ae.tags.includes(y)):D,[D,y]),U=g.useMemo(()=>{const ae=new Map;let ce=0;for(const Se of D){Se.tags.length===0&&ce++;for(const Fe of Se.tags)ae.set(Fe,(ae.get(Fe)??0)+1)}const me=[...ae.entries()].sort((Se,Fe)=>Fe[1]-Se[1]).map(([Se])=>({value:Se,label:Se}));return[{value:uoe,label:"All tags"},...ce>0?[{value:coe,label:"Untagged"}]:[],...me]},[D]),W=!!y||k,Y=g.useCallback(()=>{b(null),O(!1),v(null)},[]),te=g.useCallback((ae,ce)=>{const me=D.find(Se=>Se.id===ae);me?.experimentId&&me?.datasetId&&p.mutate({datasetId:me.datasetId,experimentId:me.experimentId,resultId:me.id,tags:ce})},[D,p]),ee=g.useCallback(ae=>{const ce=D.find(me=>me.id===ae);w(me=>{const Se=new Set(me);return Se.delete(ae),Se}),m===ae&&v(null),ce?.experimentId&&ce?.datasetId&&p.mutate({datasetId:ce.datasetId,experimentId:ce.experimentId,resultId:ce.id,status:null})},[D,p,m]),J=g.useCallback(ae=>{const ce=D.find(me=>me.id===ae);w(me=>{const Se=new Set(me);return Se.delete(ae),Se}),m===ae&&v(null),ce?.experimentId&&ce?.datasetId&&p.mutate({datasetId:ce.datasetId,experimentId:ce.experimentId,resultId:ce.id,status:"complete"})},[D,p,m]),re=g.useMemo(()=>{const ae=k?f??[]:$;return!k||!y?ae:y===coe?ae.filter(ce=>ce.tags.length===0):ae.filter(ce=>ce.tags.includes(y))},[k,f,$,y]),le=k?h:!1,X=g.useMemo(()=>new Set(re.map(ae=>ae.id)),[re]),ne=g.useMemo(()=>[...x].filter(ae=>X.has(ae)).length,[x,X]),se=re.length>0&&ne===re.length,de=g.useCallback(ae=>{w(ce=>{const me=new Set(ce);return me.has(ae)?me.delete(ae):me.add(ae),me})},[]),ue=g.useCallback(()=>{w(se?new Set:new Set(re.map(ae=>ae.id)))},[se,re]),ye=g.useCallback(ae=>{for(const ce of x){const me=D.find(Se=>Se.id===ce);me&&!me.tags.includes(ae)&&te(ce,[...me.tags,ae])}},[D,x,te]),he=g.useCallback(ae=>{for(const ce of x){const me=D.find(Se=>Se.id===ce);me&&me.tags.includes(ae)&&te(ce,me.tags.filter(Se=>Se!==ae))}},[D,x,te]),xe=g.useCallback(()=>{for(const ae of x)J(ae);w(new Set)},[x,J]),Ne=g.useCallback(()=>{for(const ae of x)ee(ae);w(new Set)},[x,ee]),Me=g.useCallback(()=>{A(""),N(!0)},[]),Re=g.useCallback(async()=>{if(!(!R||!M)){E(!0),N(!1);try{const ae=D.filter(me=>x.has(me.id));if(ae.length===0){E(!1);return}const ce=await i.clusterFailures({modelId:`${R}/${M}`,items:ae.map(me=>({id:me.id,input:me.input,output:me.output??void 0,error:typeof me.error=="string"?me.error:me.error?String(me.error):void 0,scores:me.scores,existingTags:me.tags.length>0?me.tags:void 0})),availableTags:G.length>0?G:void 0,prompt:I||void 0});ce.proposedTags&&ce.proposedTags.length>0&&(q(ce.proposedTags.map(me=>({...me,accepted:!0}))),H(!0))}catch(ae){console.error("Analysis failed:",ae)}finally{E(!1)}}},[R,M,D,x,i,G,I]),Ae=g.useCallback(()=>{for(const ae of V){if(!ae.accepted)continue;const ce=D.find(me=>me.id===ae.itemId);if(ce){const me=[...new Set([...ce.tags,...ae.tags])];te(ce.id,me)}}H(!1)},[V,D,te]),Ie=g.useCallback(ae=>{v(ce=>ce===ae?null:ae)},[]),Pe=g.useMemo(()=>m?re.find(ae=>ae.id===m)??null:null,[m,re]),{data:Ce}=Ny(Pe?.experimentId??""),Ee=m?re.findIndex(ae=>ae.id===m):-1,ze=Ee>0?()=>v(re[Ee-1].id):void 0,Oe=Ee>=0&&Ee<re.length-1?()=>v(re[Ee+1].id):void 0,$e=!k&&x.size>0,tt=o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs(ts,{children:[s,o.jsx(Kd,{label:"Status",labelIsHidden:!0,name:"filter-status",options:j0s,value:k?"completed":"review",onValueChange:ae=>{O(ae==="completed"),v(null)},className:"whitespace-nowrap"}),U.length>1&&o.jsx(Kd,{label:"Tags",labelIsHidden:!0,name:"filter-tags",options:U,value:y??uoe,onValueChange:ae=>b(ae===uoe?null:ae),className:"whitespace-nowrap"}),W&&o.jsxs(oe,{onClick:Y,size:"sm",variant:"default",children:[o.jsx(or,{className:"size-3"})," Reset"]})]}),($e||a)&&o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[a,$e&&o.jsxs(o.Fragment,{children:[o.jsx(BHt,{size:"md",selectedCount:x.size,vocabulary:G,onApplyTag:ye,onRemoveTag:he,onNewTag:ae=>ye(ae)}),o.jsxs(oe,{variant:"primary",onClick:xe,children:[o.jsx(uI,{}),"Mark as reviewed"]}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(oe,{variant:"outline",disabled:_,"aria-label":"More actions",children:_?o.jsx(Vt,{className:"h-4 w-4"}):o.jsx(wut,{})})}),o.jsxs(ot.Content,{align:"end",children:[o.jsxs(ot.Item,{onSelect:Me,children:[o.jsx(Je,{size:"sm",children:o.jsx(uS,{})}),"Analyze"]}),o.jsx(ot.Separator,{}),o.jsxs(ot.Item,{onSelect:Ne,children:[o.jsx(Je,{size:"sm",children:o.jsx(ll,{})}),"Remove from queue"]})]})]})]})]})]});if(d)return o.jsxs(o.Fragment,{children:[o.jsx(Lt.TopArea,{children:tt}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(Vt,{className:"h-6 w-6"})})]});const Ge=Pe?o.jsx(ERe,{className:"h-full",result:Pe,scores:Ce?.[Pe.itemId],experimentLink:Pe.experimentId?l.experimentItemLink(Pe.experimentId,Pe.itemId):void 0,tagVocabulary:G,onTagsChange:k?void 0:ae=>{te(Pe.id,ae);for(const ce of ae)G.includes(ce)||z(ce)},onComplete:k?void 0:()=>J(Pe.id),onPrevious:ze,onNext:Oe,onClose:()=>v(null)}):null;return o.jsxs(o.Fragment,{children:[o.jsx(Lt.TopArea,{children:tt}),o.jsx(vr,{open:T,onOpenChange:N,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(fr,{children:"Analyze Items"}),o.jsx($s,{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(Mt,{className:"mb-1 block text-xs",children:"Provider"}),o.jsx(Gy,{value:R,onValueChange:L})]}),o.jsxs("div",{children:[o.jsx(Mt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Qy,{llmId:R,value:M,onValueChange:B})]})]}),o.jsxs(ge,{variant:"ui-xs",className:"text-neutral3",children:[x.size," item",x.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Mt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(Mo,{value:I,onChange:ae=>A(ae.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-xs"})]})]}),o.jsxs(Fl,{children:[o.jsx(oe,{variant:"outline",onClick:()=>N(!1),children:"Cancel"}),o.jsxs(oe,{onClick:Re,disabled:!R||!M||_,children:[_?o.jsx(Vt,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(vr,{open:F,onOpenChange:H,children:o.jsxs(yr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(br,{children:[o.jsx(fr,{children:"Review Proposed Tags"}),o.jsxs($s,{children:[V.filter(ae=>ae.accepted).length," of ",V.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:V.map((ae,ce)=>{const me=D.find(Se=>Se.id===ae.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!ae.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(zo,{checked:ae.accepted,onCheckedChange:Se=>q(Fe=>Fe.map((De,be)=>be===ce?{...De,accepted:!!Se}:De))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 block truncate",children:me?typeof me.input=="string"?me.input.slice(0,100):JSON.stringify(me.input).slice(0,100):ae.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:ae.tags.map((Se,Fe)=>o.jsx(UHt,{tag:Se,onRename:De=>q(be=>be.map((je,Le)=>Le===ce?{...je,tags:je.tags.map((Xe,kt)=>kt===Fe?De:Xe)}:je)),onRemove:()=>q(De=>De.map((be,je)=>je===ce?{...be,tags:be.tags.filter((Le,Xe)=>Xe!==Fe)}:be))},`${Se}-${Fe}`))}),ae.reason&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:ae.reason})]})]})},ae.itemId)})}),o.jsxs(Fl,{children:[o.jsx(oe,{variant:"outline",onClick:()=>H(!1),children:"Cancel"}),o.jsxs(oe,{onClick:Ae,disabled:V.filter(ae=>ae.accepted).length===0,children:["Accept ",V.filter(ae=>ae.accepted).length," proposals"]})]})]})}),o.jsxs(Lt.MainArea,{className:K("grid h-full min-h-0 w-full grid-cols-1 gap-4",r==="overlay"?"overflow-visible":"overflow-hidden",Pe&&r==="inline"&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"min-h-0 w-full overflow-hidden",children:le?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vt,{className:"h-6 w-6"})}):re.length===0?o.jsx("div",{className:"flex h-full items-center-safe justify-center-safe overflow-auto py-12",children:o.jsx(pr,{iconSlot:o.jsx(ks,{className:"text-neutral3 h-8 w-8"}),titleSlot:k?"No completed reviews yet":"No items to review",descriptionSlot:k?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})}):o.jsx(dY,{results:re,isLoading:!1,featuredResultId:m,onResultClick:Ie,columns:T0s,selectedIds:k?void 0:x,onToggleSelect:k?void 0:de,onToggleSelectAll:k?void 0:ue})}),Ge&&(r==="overlay"?o.jsx(gY,{label:`Review item ${Pe?.id??""}`,children:o.jsx("div",{className:"[&>section]:bg-surface3 h-full min-h-0 p-3 [&>section]:rounded-lg [&>section]:shadow-lg",children:Ge})}):Ge)]})]})}const Cnt={needsReview:"#facc15",complete:"#22c55e"},I0s=[{label:"Needs Review",color:Cnt.needsReview},{label:"Reviewed",color:Cnt.complete}];function A0s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(qt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(qt.Loading,{}):s?o.jsx(qt.Error,{message:"Failed to load review data"}):o.jsx(qt.Content,{children:c?o.jsx(nI,{data:a,segments:I0s,maxVal:i,fmt:u=>String(u)}):o.jsx(qt.NoData,{message:"No items have been sent to review yet"})})]})}function AWt(){const e=Ze();return mt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function R0s(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 P0s(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 $0s(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=up(),{data:l,isLoading:c,error:u}=Rm(),{data:d,isLoading:f,error:h}=QH(),{data:p,isLoading:m,isError:v,error:y}=wWr(n),{data:b,isLoading:x,isError:w,error:k}=AWt(),O=l?.datasets,_=d?.experiments,E=g.useMemo(()=>P0s(b),[b]),T=i||u||h||y||k;return T&&hs(T)?o.jsx(Zn,{children:o.jsx(Es,{})}):T&&ps(T)?o.jsx(Zn,{children:o.jsx(Os,{resource:"evaluation"})}):T?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load evaluation data",message:T.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{children:o.jsx(KL,{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-6",children:[o.jsx(C0e,{children:o.jsx(e0s,{scorers:s,datasets:O,experiments:_,avgScore:p?.avgScore??null,prevAvgScore:p?.prevAvgScore??null,totalNeedsReview:E.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(RHr,{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-6 lg:grid-cols-2",children:[o.jsx(rbs,{experiments:_,isLoading:f,isError:!!h}),o.jsx(p0s,{experiments:_,datasets:O,isLoading:f,isError:!!h})]}),o.jsx(A0s,{reviewSummary:b,experiments:_,datasets:O,isLoading:x,isError:!!w})]})]})}function M0s(){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=Kr(),[f,h]=ya(),p=f.get("dataset")??"all",m=g.useCallback(G=>{h(z=>{const $=new URLSearchParams(z);return G==="all"?$.delete("dataset"):$.set("dataset",G),$},{replace:!0})},[h]),{data:v,isLoading:y,error:b}=Rm(),{data:x,isLoading:w,error:k}=yY(p==="all"?void 0:p),{data:O}=AWt(),_=g.useMemo(()=>v?.datasets??[],[v?.datasets]),E=g.useMemo(()=>x?.experiments??[],[x?.experiments]),T=g.useMemo(()=>f0s(_),[_]),N=g.useMemo(()=>R0s(O),[O]),I=y||w,A=k||b,R=G=>{u(z=>z.includes(G)?z.filter($=>$!==G):z.length>=2?[z[0],G]:[...z,G])},L=()=>{u([]),l(!1)},{selectedIds:M,selectedDatasetIds:B}=g.useMemo(()=>{const G=new Map(E.map($=>[$.id,$.datasetId])),z=c.filter($=>G.has($));return{selectedIds:z,selectedDatasetIds:new Set(z.map($=>G.get($)))}},[E,c]),V=M.length===2&&B.size!==1?"not the same dataset":void 0,q=()=>{if(M.length!==2||V)return;const[G,z]=M,[$]=B;if(!$)return;const U=new URLSearchParams({dataset:$,baseline:G,contender:z});d(`/experiments/compare?${U.toString()}`)};if(A&&hs(A))return o.jsx(Zn,{children:o.jsx(Es,{})});if(k&&ps(k))return o.jsx(Zn,{children:o.jsx(Os,{resource:"experiments"})});if(b&&ps(b))return o.jsx(Zn,{children:o.jsx(Os,{resource:"datasets"})});if(A)return o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load experiments",message:A.message})});const F=o.jsx(mY,{open:s,onOpenChange:a,onSuccess:G=>{d(`/experiments/${G}`)}});if(E.length===0&&!I&&p==="all")return o.jsxs(Zn,{children:[o.jsx(m0s,{onRunExperiment:()=>a(!0)}),F]});const H=n!=="all"||p!=="all"||e!=="",D=()=>{t(""),r("all"),m("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(g0s,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:p,onDatasetFilterChange:m,datasetOptions:T,onReset:D,hasActiveFilters:H,onRunClick:()=>a(!0),onCompareClick:()=>l(!0),selection:i?{selectedCount:M.length,onExecuteCompare:q,onCancelSelection:L,compareDisabledReason:V}:void 0})}),o.jsx(u0s,{experiments:E,datasets:_,reviewByExperiment:N,isLoading:I,search:e,statusFilter:n,datasetFilter:p,selection:i?{selectedExperimentIds:M,onToggleSelection:R}:void 0}),F]})}function m8({experimentId:e}){const{Link:t,paths:n}=ln();return o.jsx(oe,{as:t,href:n.experimentLink(e),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function D0s(){const[e,t]=ya(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",a=XD(n,r),i=XD(n,s),l=a.isLoading||i.isLoading,c=a.error??i.error;return c&&hs(c)?o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Es,{})})}):c&&ps(c)?o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"experiments"})})}):!n||!r||!s?o.jsx(ia,{children:o.jsx(Ox,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"mt-2 text-sm",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):l?null:c&&!h0(c)?o.jsx(ia,{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(ia,{children:o.jsx(Ox,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),o.jsxs("p",{className:"mt-2 flex items-center justify-center gap-2 text-sm",children:["One of",o.jsx(m8,{experimentId:r}),"and",o.jsx(m8,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(ia,{children:o.jsx(Ox,{children:o.jsxs("div",{className:"grid w-full content-start",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-6 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(m8,{experimentId:r}),"and",o.jsx(m8,{experimentId:s})]})]}),o.jsxs(gn,{children:[o.jsx(fn,{asChild:!0,children:o.jsxs(oe,{onClick:()=>t({dataset:n,baseline:s,contender:r}),children:[o.jsx(dut,{}),"Swap sides"]})}),o.jsx(hn,{children:"Switch baseline and contender"})]})]}),o.jsx(O0s,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}function L0s({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(ts,{className:"whitespace-nowrap",children:[o.jsxs(oe,{variant:"outline",disabled:i,onClick:e.flagSelectedForReview,children:[o.jsx($C,{}),"Flag ",t.size," to review"]}),o.jsx(jVt,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:i}),o.jsx(oe,{variant:"ghost",onClick:e.clearSelection,children:"Clear"})]})}const RWt=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 8.64637 9.45103",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M7.80735 5.87241C7.63209 5.97219 7.43696 6.06166 7.22844 6.13866C6.46456 6.42068 5.43714 6.58649 4.32296 6.58649C3.20873 6.58649 2.18135 6.4207 1.41747 6.13866C1.20889 6.06164 1.01385 5.97223 0.838558 5.87241V7.59003C0.838558 7.62341 0.855765 7.70759 1.00172 7.83512C1.14707 7.96201 1.38219 8.09563 1.70829 8.21605C2.3572 8.45563 3.28149 8.61268 4.32296 8.61269C5.36456 8.61269 6.28937 8.45568 6.9383 8.21605C7.26428 8.09566 7.49888 7.96198 7.64419 7.83512C7.79024 7.70754 7.80735 7.62342 7.80735 7.59003V5.87241ZM7.80735 3.00789C7.63214 3.10763 7.4369 3.19647 7.22844 3.27345C6.46455 3.55549 5.43719 3.72129 4.32296 3.72129C3.20868 3.72128 2.18136 3.55552 1.41747 3.27345C1.20896 3.19645 1.01381 3.10766 0.838558 3.00789V4.72551C0.838558 4.7589 0.855657 4.84301 1.00172 4.97059C1.14707 5.09749 1.38219 5.23111 1.70829 5.35153C2.3572 5.59109 3.28154 5.74747 4.32296 5.74748C5.36456 5.74748 6.28937 5.59116 6.9383 5.35153C7.26432 5.23112 7.49887 5.09747 7.64419 4.97059C7.7536 4.87505 7.79089 4.80404 7.80257 4.76033L7.80735 4.72551V3.00789ZM7.80735 1.86099C7.80735 1.82758 7.79045 1.74291 7.64419 1.61522C7.49887 1.48838 7.26421 1.35534 6.9383 1.23497C6.28937 0.995339 5.36456 0.838331 4.32296 0.838331C3.28149 0.83834 2.3572 0.995383 1.70829 1.23497C1.38219 1.35539 1.14707 1.48832 1.00172 1.61522C0.855475 1.7429 0.838558 1.82758 0.838558 1.86099C0.838673 1.89462 0.855968 1.97882 1.00172 2.10607C1.14707 2.23297 1.38219 2.3659 1.70829 2.48632C2.3572 2.7259 3.28149 2.88295 4.32296 2.88296C5.36456 2.88296 6.28937 2.72595 6.9383 2.48632C7.26421 2.36595 7.49887 2.23291 7.64419 2.10607C7.78996 1.97881 7.80724 1.89462 7.80735 1.86099ZM8.64637 7.59003C8.64637 7.95465 8.44458 8.25006 8.1958 8.46728C7.94608 8.68529 7.60876 8.86274 7.22844 9.00318C6.46455 9.28522 5.43718 9.45102 4.32296 9.45102C3.20869 9.45101 2.18135 9.28525 1.41747 9.00318C1.03715 8.86274 0.699831 8.68529 0.450113 8.46728C0.201377 8.25007 0.000227451 7.9546 0.000227451 7.59003V1.86099C0.000227451 1.49643 0.201388 1.20095 0.450113 0.983742C0.699831 0.765728 1.03715 0.588275 1.41747 0.447838C2.18136 0.165769 3.20868 8.74396e-06 4.32296 0C5.43719 0 6.46455 0.165797 7.22844 0.447838C7.60876 0.588275 7.94608 0.765728 8.1958 0.983742C8.44457 1.20096 8.64637 1.49638 8.64637 1.86099V7.59003Z",fill:"currentColor"})});function PWt(e){const{data:t}=Ny(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 doe({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(fn,{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(hn,{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 foe="text-neutral5 inline-flex min-w-0 items-center gap-1.5 hover:underline";function F0s({experiment:e,className:t}){const{Link:n,paths:r}=ln(),s=OWt(),{scorers:a}=s,{data:i,isLoading:l}=Yg(e.datasetId??""),c=PWt(e),u=e.targetType,d=e.targetId,f=EWt(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&&CWt[u]||co,m=u&&_Wt[u]||"Evaluation target";return o.jsxs("ol",{className:K("grid",t),children:[o.jsx(doe,{icon:o.jsx(RWt,{}),typeLabel:"Dataset",description:`Each item will be passed to the ${m.toLowerCase()}`,subject:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:foe,children:[o.jsx("span",{className:"truncate",children:l?o.jsx(wt,{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(doe,{icon:o.jsx(p,{}),typeLabel:m,description:"Its output is then scored",subject:h?o.jsx(n,{href:h,className:foe,children:o.jsx("span",{className:"truncate",children:f})}):o.jsx("span",{className:"text-neutral3 truncate",children:f})}),o.jsx(doe,{icon:o.jsx(M_,{}),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:foe,children:o.jsx("span",{className:"truncate",children:y})})},v)})})})]})}function YE({label:e,children:t}){return o.jsxs(o.Fragment,{children:[o.jsx(Fn.Key,{children:e}),o.jsx(Fn.Value,{className:"flex flex-wrap items-baseline justify-end gap-x-1.5 text-right",children:t})]})}function _nt(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 z0s({experiment:e,metrics:t}){const{data:n}=Ny(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?"—":_nt(c)})();return o.jsxs(Fn,{children:[o.jsx(YE,{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(YE,{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(YE,{label:"Started",children:i?o.jsx("span",{title:DDn(i,{addSuffix:!0}),children:mr(i,"MMM d, h:mm a")}):o.jsx("span",{children:"—"})}),o.jsx(YE,{label:"Duration",children:o.jsx("span",{children:l})}),t?.isEnabled&&o.jsxs(o.Fragment,{children:[o.jsx(YE,{label:"Tokens",children:t.data?.totalTokens==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:to(t.data.totalTokens)}),t.data.estimatedCost!=null&&o.jsxs("span",{className:"text-neutral3",children:["· ",Fd(t.data.estimatedCost,t.data.costUnit)]}),r&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(YE,{label:"Latency (avg)",children:t.data?.avgAgentDurationMs==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsx("span",{children:_nt(Math.round(t.data.avgAgentDurationMs))})})]})]})}function B0s({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=ln(),{data:s}=up(),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(Ry,{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(fn,{render:o.jsx(M_,{role:"img","aria-label":"Scorer"})}),o.jsx(hn,{children:"Scorer"})]}),o.jsx("span",{className:"truncate",children:c})]}),o.jsxs("strong",{className:"text-ui-lg 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 hoe({title:e,children:t}){return o.jsxs("section",{className:"grid gap-3",children:[o.jsx("h2",{className:"text-ui-sm text-neutral2 tracking-widest uppercase",children:e}),t]})}function U0s({experiment:e,metrics:t,className:n}){const{Link:r,paths:s}=ln(),{data:a}=Ny(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(Ic,{as:"aside","aria-label":"Experiment details",className:K("grid content-start gap-8 p-5",n),children:[o.jsxs(hoe,{title:"Pipeline",children:[o.jsx(F0s,{experiment:e}),e.agentVersion&&o.jsxs(Fn,{children:[o.jsx(Fn.Key,{children:"Version"}),i?o.jsx(Fn.ValueLink,{href:i,as:r,children:e.agentVersion}):o.jsx(Fn.Value,{children:e.agentVersion})]})]}),o.jsx(hoe,{title:"Run",children:o.jsx(z0s,{experiment:e,metrics:t})}),o.jsx(hoe,{title:"Scorers",children:o.jsx(B0s,{scoresByItemId:a,experimentStatus:e.status})})]})}function q0s({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[a,i]=g.useState(e.description??""),{updateExperiment:l}=Fa(),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()}),Ve.success("Experiment renamed"),n(!1)}catch(f){Ve.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(fr,{children:"Rename Experiment"})}),o.jsx(Pr,{children:o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{htmlFor:"rename-experiment-name",children:"Name *"}),o.jsx(jn,{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(Mt,{htmlFor:"rename-experiment-description",children:"Description"}),o.jsx(jn,{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(oe,{type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(oe,{type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}const V0s=["agent","workflow","scorer"];function H0s({experiment:e}){const[t,n]=g.useState(!1),r=Kr(),{paths:s}=ln(),a=PWt(e),i=V0s.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsxs(oe,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",children:[o.jsx(Pc,{}),"Rerun"]}),t&&o.jsx(mY,{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 W0s({experiment:e,onDeleteClick:t,children:n}){const{Link:r}=ln(),[s,a]=g.useState(!1),i=!!e.datasetId,l=i||!!t;return o.jsxs(Lt.TopArea,{children:[o.jsxs(Lt.Row,{className:"items-center justify-start gap-2",children:[o.jsxs(ts,{className:"whitespace-nowrap",children:[o.jsx(H0s,{experiment:e}),o.jsxs(oe,{as:r,to:mDt(e.id),children:[o.jsx($C,{}),"Review queue"]}),l&&o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(oe,{size:"lg","aria-label":"Experiment actions menu",children:o.jsx(XS,{})})}),o.jsxs(ot.Content,{align:"start",className:"w-48",children:[i&&o.jsxs(ot.Item,{onSelect:()=>a(!0),children:[o.jsx(Qh,{})," Rename Experiment"]}),t&&o.jsxs(ot.Item,{onSelect:t,className:"text-red-500 focus:text-red-400",children:[o.jsx(ll,{})," Delete Experiment"]})]})]})]}),n]}),s&&o.jsx(q0s,{experiment:e,open:!0,onOpenChange:a})]})}const Z0s=({experimentId:e,experimentStatus:t})=>{const n=Ze(),{supportsMetrics:r}=HQ(),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 G0s({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=Fa();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?Ve(`Tag "${i}" added to ${u} result${u>1?"s":""}`):Ve.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function $Wt(e,t){const{data:n}=Yg(e);return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}function Q0s({datasetId:e,experimentId:t,results:n}){const[r,s]=g.useState(new Set),[a,i]=g.useState(!1),{updateExperimentResult:l}=Fa(),{addTag:c,isPending:u}=G0s({datasetId:e,experimentId:t}),d=$Wt(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}),Ve(`${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 Y0s=[];function g8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function K0s(){const{experimentId:e}=ur(),t=Kr(),[n,r]=g.useState(!1),{data:s,isLoading:a}=QH(),l=s?.experiments?.find(w=>w.id===e)?.datasetId??"",{data:c,isLoading:u,error:d}=XD(l,e??""),{data:f,isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v}=JD({datasetId:l,experimentId:e??"",experimentStatus:c?.status}),y=Z0s({experimentId:e,experimentStatus:c?.status}),b=Q0s({datasetId:l,experimentId:e??"",results:f??Y0s});if(!e||a||u)return null;if(d&&hs(d))return o.jsx(g8,{children:o.jsx(Es,{})});if(d&&ps(d))return o.jsx(g8,{children:o.jsx(Os,{resource:"datasets"})});const x=o.jsx(g8,{children:o.jsx(pr,{iconSlot:o.jsx(U0e,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(oe,{as:yo,to:"/experiments",children:[o.jsx(wu,{}),"Back to Experiments"]})})});return d&&h0(d)?x:d?o.jsx(g8,{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(gxs,{experimentId:e,datasetId:l,experimentStatus:c.status,results:f??[],isLoadingResults:h,hasNextPage:v,children:o.jsxs("div",{className:"h-full",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(W0s,{experiment:c,onDeleteClick:()=>r(!0),children:o.jsx(L0s,{selection:b})}),o.jsxs(Lt.MainArea,{className:"grid grid-cols-[1fr_auto] gap-6 overflow-visible",children:[o.jsx(vxs,{experimentId:e,experimentStatus:c.status,results:f??[],isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v,selectedIds:b.selectedIds,onToggleSelect:b.toggleSelect}),o.jsx(U0s,{experiment:c,metrics:y,className:"w-80 overflow-y-auto"})]})]}),o.jsx(Fg,{}),o.jsx(wWt,{open:n,onOpenChange:r,experimentId:e,experimentName:c.name??void 0,onSuccess:()=>t("/experiments")})]})})}function X0s(){const{itemId:e}=ur();return e?o.jsx(J0s,{itemId:e},e):null}function J0s({itemId:e}){const{experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:a,hasNextPage:i,close:l,goToPreviousItem:c,goToNextItem:u}=bWt(),d=g.useMemo(()=>s.find(w=>w.itemId===e)??null,[s,e]),{data:f}=Ny(t,r),{updateExperimentResult:h}=Fa(),p=g.useCallback(async w=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,status:"needs-review"}),Ve("Result flagged for review")}catch{Ve.error("Failed to flag result for review")}},[n,t,h]),m=$Wt(n,s),v=g.useCallback(async(w,k)=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,tags:k})}catch{Ve.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"}),Ve("Result marked as reviewed")}catch{Ve.error("Failed to complete result")}},[n,t,h]),b=d?f?.[d.itemId]:void 0,x=IVt(b);return o.jsx(gY,{label:`Experiment item ${e}`,wide:x.wide,children:d?o.jsx(ERe,{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(Vt,{})})}):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(pr,{iconSlot:o.jsx(U0e,{}),titleSlot:"Item not found",descriptionSlot:`No loaded result for item "${e}".`,actionSlot:o.jsx(oe,{onClick:l,children:"Close"})})})})})}const MWt=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"})}),PV="all",Ent=60,ews=e=>e.length>Ent?`${e.slice(0,Ent)}…`:e;function tws({value:e,onValueChange:t,className:n,variant:r,allOption:s}){const{data:a,isLoading:i,isError:l}=yY(void 0),c=(a?.experiments??[]).map(d=>({label:SWt(d),value:d.id,start:o.jsx(MWt,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:d.description?ews(d.description):b0(d.id)??d.id})),u=s?[{label:"All experiments",value:PV},...c]:c;return o.jsx(Fo,{options:u,value:e??(s?PV:""),onValueChange:t,placeholder:i?"Loading experiments...":l?"Failed to load experiments":"Select experiment",searchPlaceholder:"Search experiments...",emptyText:"No experiments found.",className:n,disabled:i||l,variant:r})}function nws(){const[e,t]=ya(),n=e.get("experiment"),r=e.get("review"),{Link:s,paths:a}=ln(),{data:i,error:l}=yY(void 0),c=i?.experiments.find(d=>d.id===n),u=d=>{t(d===PV?{}:{experiment:d},{replace:!0})};return l&&hs(l)?o.jsx(Zn,{children:o.jsx(Es,{})}):l&&ps(l)?o.jsx(Zn,{children:o.jsx(Os,{resource:"experiments"})}):l?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load experiments",message:l.message})}):o.jsx(Lt,{height:"full",children:o.jsx(N0s,{datasetId:c?.datasetId??void 0,experimentId:n??void 0,featuredItemId:r,detailPanelVariant:"overlay",toolbarStart:o.jsx(tws,{allOption:!0,value:n??void 0,onValueChange:u,className:"w-72"}),toolbarEnd:n?o.jsxs(oe,{as:s,href:a.experimentLink(n),children:["See experiment",o.jsx(fut,{})]}):void 0},n??PV)})}const DWt=[{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"}],rws=DWt.map(e=>e.size).join(" ");function sws({items:e,isLoading:t,error:n}){const r=Kr(),[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(Do,{columns:rws}):n?o.jsx(Fs,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(pr,{iconSlot:o.jsx(ks,{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(Uc,{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(dY,{results:l,isLoading:!1,featuredResultId:null,onResultClick:c=>{const u=l.find(d=>d.id===c);u&&r(mDt(u.experimentId,u.id))},columns:DWt,emptyMessage:"No dataset items match your search"})})]})}function aws(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),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(oe,{as:yo,to:"/experiments",variant:"outline",children:"Go to experiments"}),o.jsx(oe,{as:yo,to:"/traces",variant:"outline",children:"Go to traces"})]})})})}function _0e(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 Tnt="minmax(0, 2fr) minmax(0, 1fr) auto minmax(0, 1fr) auto auto";function iws({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=>_0e(x).toLowerCase().includes(h)||(TV(x)??"").toLowerCase().includes(h)||(x.traceId??"").toLowerCase().includes(h)||(x.feedbackSource??"").toLowerCase().includes(h)):e,{containerRef:m,getRowProps:v}=ol({count:p.length}),{inView:y,setRef:b}=s0({root:m});return g.useEffect(()=>{y&&r&&!s&&a()},[y,r,s,a]),t?o.jsx(Do,{columns:Tnt}):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(Uc,{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(ve,{columns:Tnt,fit:"container",scrollRef:m,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Feedback"}),o.jsx(ve.TopCell,{children:"Author"}),o.jsx(ve.TopCell,{children:"Source"}),o.jsx(ve.TopCell,{children:"Trace"}),o.jsx(ve.TopCell,{children:"Date"}),o.jsx(ve.TopCell,{children:" "})]}),p.length===0?o.jsx(ve.NoMatch,{message:h?"No feedback matches your search":"No feedback needs review"}):p.map((x,w)=>{const k=x.feedbackId,O=TV(x);return o.jsxs(ve.RowWrapper,{children:[o.jsxs(ve.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,onClick:()=>c(x),...v(w),children:[o.jsx(ve.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:_0e(x)})}),o.jsx(ve.Cell,{className:"flex gap-2",children:O&&o.jsxs(o.Fragment,{children:[o.jsx(jy,{name:O,src:x.author?.avatarUrl,size:"sm"}),o.jsx("span",{className:"truncate",children:O})]})}),o.jsx(ve.Cell,{children:o.jsx(yt,{size:"sm",children:x.feedbackSource})}),o.jsx(ve.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(ve.TextCell,{children:mr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(ve.ActionsCell,{className:"pl-2",children:k?o.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>i(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(ve.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function ows({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}=rWt({traceId:t,anchorSpanId:null,listMode:"traces"}),h=TV(e)??e.feedbackUserId;return o.jsx(gY,{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(wn,{className:"max-h-[33vh]",children:[o.jsxs(wn.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(wn.Heading,{children:"Feedback"}),o.jsx(yt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(yt,{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(jy,{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:mr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss")})]})]}),o.jsx(ts,{className:"ml-auto shrink-0",children:o.jsxs(oe,{variant:"primary",size:"sm",onClick:i,disabled:l,children:[o.jsx(Je,{children:o.jsx(Dr,{})}),"Mark as reviewed"]})})]}),o.jsx(wn.Content,{children:o.jsx(ge,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:_0e(e)})})]}),o.jsx("section",{className:"min-h-0 overflow-hidden",children:o.jsx(_Re,{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(t3,{traceId:p}),spanFeedbackTabSlot:({traceId:p,spanId:m})=>p&&m?o.jsx(hRe,{traceId:p,spanId:m},`${p}:${m}`):null})})]})})}const LWt=100;async function lws(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:LWt});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function cws(e,t,n){const r=[];let s=0,a=!0;for(;a;){const i=await e.listDatasetExperimentResults(t,n,{page:s,perPage:LWt});r.push(...i.results),a=i.pagination.hasMore,s+=1}return r}function uws(){const e=Ze();return mt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await lws(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await cws(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 dws({enabled:e}){const t=Ze();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 fws(e){return e==="dataset"||e==="feedback"}function hws(){const[e,t]=ya(),n=e.get("tab"),r=fws(n)?n:"feedback",s=_hs({reviewStatus:"needs-review"}),a=fRe(),i=uws(),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=E=>{t(T=>{const N=new URLSearchParams(T);for(const I of["feedbackId","traceId","spanId"]){const A=E[I];A?N.set(I,A):N.delete(I)}return N},{replace:!0})},m=()=>p({}),v=E=>p({feedbackId:E.feedbackId??void 0,traceId:E.traceId??void 0,spanId:E.spanId??void 0}),y=s.items.findIndex(E=>E.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=E=>{a.mutate({feedbackId:E,reviewStatus:"reviewed"},{onSuccess:()=>E===d&&m()})},_=E=>{t(T=>{const N=new URLSearchParams(T);return N.set("tab",E),N},{replace:!0})};return o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(pu,{children:[o.jsx(pu.Title,{children:"Inbox"}),o.jsx(pu.Description,{children:"Items waiting for review"})]})}),o.jsx(Lt.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(aws,{}):o.jsxs(wl,{defaultTab:"feedback",value:r,onValueChange:_,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(xl,{variant:"pill-ghost",children:[o.jsxs(wr,{value:"feedback",className:"px-3 py-2.5",children:[o.jsx(Je,{size:"sm",children:o.jsx(c3,{})}),o.jsx(ge,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(yt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(wr,{value:"dataset",className:"px-3 py-2.5",children:[o.jsx(Je,{size:"sm",children:o.jsx($C,{})}),o.jsx(ge,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(yt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(Qr,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(iws,{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(Qr,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(sws,{items:l,isLoading:i.isLoading,error:i.error??void 0})})]})})]}),k&&f&&b&&o.jsx(ows,{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 pws({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-xs",children:e.connectionId}),o.jsxs("div",{className:"text-xs 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 FWt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(pws,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function mws({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-sm font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(FWt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function gws({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-lg 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(mws,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(FWt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function vws({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 jnt=e=>e.authorId?.trim()||"shared",yws=(e,t)=>{if(!t||new Set(e.map(jnt)).size<=1)return null;const r=new Map;for(const a of e){const i=jnt(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},bws=["*","tool-providers:*","tool-providers:admin"];function xws(){const{data:e}=Fm();return e?.permissions?.some(t=>bws.includes(t))??!1}function wws(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=oA(),l=vG(e||null),c=YLt(e||null,n||null),u=QLt(),d=WLt(),f=xws(),h=i.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>yws(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-6 max-w-3xl space-y-6 text-sm",children:[o.jsx("h1",{className:"text-2xl 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(vws,{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(gws,{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 Sws({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-xl font-semibold",children:e})]}),t,n,r]})})}function zWt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=uc(),{mutate:i,isPending:l,error:c}=W2r(),{mutate:u,isPending:d,error:f}=G2r(),{mutate:h,isPending:p}=GDt(),[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,E=_.type==="sso"||_.type==="both",T=_.type==="credentials"||_.type==="both",N=_.sso,I=_.signUpEnabled!==!1,A=m==="signin"||!I,R=A?l:d,L=A?c:f,M=()=>{t?t():e?window.location.href=e:window.location.href=_G("/")},B=D=>{D.preventDefault(),A?i({email:x,password:k},{onSuccess:M}):u({email:x,password:k,name:y||void 0},{onSuccess:M})},V=()=>{h({redirectUri:e},{onSuccess:D=>{window.location.href=D.url}})},q=()=>{v(A?"signup":"signin")},F=_.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(Bd,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-sm",children:_.description})]}):null,H=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(Sws,{title:A?"Sign in to Mastra Studio":"Create your account",description:F,errorBanner:H,children:[T&&o.jsxs("form",{onSubmit:B,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"text-neutral4 block text-sm",children:"Name"}),o.jsx(jn,{id:"name",type:"text",value:y,onChange:D=>b(D.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 block text-sm",children:"Email"}),o.jsx(jn,{id:"email",type:"email",value:x,onChange:D=>w(D.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 block text-sm",children:"Password"}),o.jsx(jn,{id:"password",type:"password",value:k,onChange:D=>O(D.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),L&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:L.message}),o.jsx(oe,{type:"submit",disabled:R,className:"w-full",size:"lg",children:R?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-center text-sm",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:q,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),E&&T&&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:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),E&&N&&o.jsxs(oe,{onClick:V,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 kws(){const[e]=ya(),t=Kr(),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(zWt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const yh=Ra.KeyValueList;function Ows(e){return e instanceof Date?e:new Date(e)}function Cws({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=Ows(e.timestamp),p=e.traceId,m=e.spanId;return o.jsxs(Ra,{collapsed:d,children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Log ",o.jsx("b",{children:mr(h,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(ts,{className:"ml-auto shrink-0",children:[l&&o.jsx(oe,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(cI,{}):o.jsx(LV,{})}),o.jsxs(ts,{spacing:"close",children:[o.jsx(oe,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(KS,{})}),o.jsx(oe,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(MV,{})})]}),o.jsx(Ra.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Ra.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(ts,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(oe,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(p),children:[o.jsx(Mf,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",p]})]}),o.jsx(Da,{content:p,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(ts,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(oe,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!p||!r,onClick:()=>p&&r?.(p,m),children:[o.jsx(Mf,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(Da,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(yh,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Entity Type"}),o.jsx(yh.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Entity Name"}),o.jsx(yh.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Service"}),o.jsx(yh.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Environment"}),o.jsx(yh.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Source"}),o.jsx(yh.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(yh.Key,{children:v}),o.jsx(yh.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Ra.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function _ws({error:e,resource:t,errorTitle:n}){if(hs(e))return o.jsx(Es,{});if(ps(e))return o.jsx(Os,{resource:t});if(YL(e))return o.jsx(pr,{iconSlot:o.jsx(ks,{}),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(QL(e,"logs"))return o.jsx(pr,{iconSlot:o.jsx(ks,{}),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 Ews({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 Tws={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 jws({level:e}){const t=Tws[e];return o.jsx(lo,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Nws({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(co,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(Su,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Uf,{className:n,"aria-hidden":!0});default:return null}}function Iws({entityType:e,entityName:t}){const n=e??"";return o.jsxs(lo,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(Nws,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function Aws({message:e}){return o.jsx(lo,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function Rws({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(lo,{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(bTe,{font:"mono",children:t})}const Jl=Object.assign(WL,{Top:GL,TopCell:y1,TopCellWithTooltip:sG,TopCellSmart:_Mt,RowWrapper:STe,RowButton:ZL,RowLink:CMt,Spacer:kTe,NoMatch:rG,DateCell:SMt,TimeCell:kMt,LevelCell:jws,EntityCell:Iws,MessageCell:Aws,DataCell:Rws,NextPageLoading:nG}),Nnt="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",Pws=36,$ws=8;function Mws({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=nWt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>Pws,overscan:$ws}),{getRowProps:d}=ol({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y)}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Do,{columns:Nnt});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:Nnt,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 Dws({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=>Lws(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(PRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ARe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Lws(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 Fws={"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"},poe="MMM d, yyyy HH:mm",moe="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function zws({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Fws[e]}`,description:moe}:t&&n?{title:`No logs between ${mr(t,poe)} and ${mr(n,poe)}`,description:moe}:t?{title:`No logs since ${mr(t,poe)}`,description:moe}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Bws=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=zws({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(Ds,{})]})})})},Uws=20,qws=1e4;function Vws(e,t,n){if(e?.pagination?.hasMore)return n+1}function Hws(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 Wws(e){return QL(e.state.error,"logs")||YL(e.state.error)?!1:qws}const Zws=({filters:e}={})=>{const t=Ze(),{inView:n,setRef:r}=s0(),s=Fy({queryKey:["logs",e],queryFn:({pageParam:h})=>t.listLogsVNext({pagination:{page:h,perPage:Uws},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:Vws,select:Hws,retry:!1,refetchInterval:Wws}),{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}},v8={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},BWt=[{label:"Agent",entityType:v8.AGENT},{label:"Workflow",entityType:v8.WORKFLOW},{label:"Scorer",entityType:v8.SCORER},{label:"Ingest",entityType:v8.INGEST}],Gws=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Kx="rootEntityType",nx="datePreset",rx="dateFrom",sx="dateTo",Qws=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Nl={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"},r5=Object.keys(Nl),HRe=new Set(["tags"]),WRe="mastra:logs:saved-filters";function Yws(e,t=WRe){const n=tSs(e),r=e.get(nx);r&&n.set(nx,r);const s=e.get(rx);s&&n.set(rx,s);const a=e.get(sx);a&&n.set(sx,a);try{localStorage.setItem(t,n.toString())}catch{}}function Kws(e=WRe){try{localStorage.removeItem(e)}catch{}}function Int(e=WRe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Xws(e){if(e.has(nx)||e.has(rx)||e.has(sx)||e.has(Kx))return!0;for(const t of r5)if(e.has(Nl[t]))return!0;return!1}function Jws({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:BWt.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:Gws.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 eSs(e){const t=[],n=new Map([[Kx,"rootEntityType"]]);for(const s of r5)n.set(Nl[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),HRe.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 tSs(e){const t=new URLSearchParams,n=e.get(Kx);n&&t.set(Kx,n);for(const r of r5){const s=Nl[r];if(HRe.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 nSs(e,t){e.delete(Kx);for(const n of r5)e.delete(Nl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Kx,n.value);continue}const r=Nl[n.fieldId];if(r){if(HRe.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 rSs({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 sSs(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 aSs="Filters setting for Logs saved",iSs="Filters setting for Logs cleared up";function oSs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Int(r)!==null),c=g.useCallback(()=>{Yws(e,r),l(!0);const f=s?.saved??aSs;f!==!1&&Ve.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Kws(r),l(!1);const f=s?.cleared??iSs;f!==!1&&Ve.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Xws(e)))return;const f=Int(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 lSs(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 cSs(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,lSs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function uSs(e,t,n,r){const s=g.useMemo(()=>cSs(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 E0e="logId",T0e="traceId",j0e="spanId",FP=1440*60*1e3,dSs={"last-24h":FP,"last-3d":3*FP,"last-7d":7*FP,"last-14d":14*FP,"last-30d":30*FP};function y8(e){e.delete(E0e),e.delete(T0e),e.delete(j0e)}function fSs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const O=e.get(nx);return O&&Qws.has(O)?O:"last-24h"},[e]),a=e.get(rx),i=e.get(sx),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=dSs[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(E0e),f=e.get(T0e),h=e.get(j0e),p=g.useMemo(()=>BWt.find(O=>O.entityType===e.get(Kx)),[e]),m=g.useMemo(()=>eSs(e),[e]),v=g.useCallback(O=>{t(_=>{const E=new URLSearchParams(_);for(const[T,N]of Object.entries(O)){const I=T==="logId"?E0e:T==="traceId"?T0e:j0e;N?E.set(I,N):E.delete(I)}return E},{replace:!0})},[t]),y=g.useCallback(O=>{t(_=>{const E=new URLSearchParams(_);return nSs(E,O),y8(E),E},{replace:!0})},[t]),b=y,x=g.useCallback((O,_)=>{if(u.current!=="custom")return;const E=_==="from"?rx:sx;t(T=>{const N=new URLSearchParams(T);return O?N.set(E,O.toISOString()):N.delete(E),y8(N),N},{replace:!0})},[t]),w=g.useCallback(O=>{u.current=O,t(_=>{const E=new URLSearchParams(_);return O==="last-24h"?(E.delete(nx),E.delete(rx),E.delete(sx)):O==="custom"?E.set(nx,"custom"):(E.set(nx,O),E.delete(rx),E.delete(sx)),y8(E),E},{replace:!0})},[t]),k=g.useCallback(()=>{t(O=>{const _=new URLSearchParams(O);_.delete(Kx);for(const E of r5)_.delete(Nl[E]);return _.delete(nx),_.delete(rx),_.delete(sx),y8(_),_},{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 Ab=Ra.KeyValueList;function hSs({spanId:e,span:t,isLoading:n,onClose:r}){const s=uRe(t?.startedAt,t?.endedAt),a=gtt(t?.startedAt),i=gtt(t?.endedAt);return o.jsxs(Ra,{children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Ra.CloseButton,{onClick:r})]}),n?o.jsx(Ra.LoadingData,{children:"Loading span..."}):t?o.jsxs(Ra.Content,{children:[o.jsxs(Ab,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(Ab.Key,{children:"Type"}),o.jsx(Ab.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(Ab.Key,{children:"Started"}),o.jsx(Ab.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Ab.Key,{children:"Ended"}),o.jsx(Ab.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Ab.Key,{children:"Duration"}),o.jsx(Ab.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Ra.CodeSection,{title:"Input",icon:o.jsx(_O,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Output",icon:o.jsx(dy,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Metadata",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Attributes",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Ra.NoData,{children:"Span not found."})]})}function pSs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>Y4(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(GQ(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Ra,{children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Ra.CloseButton,{onClick:r})]}),n?o.jsx(Ra.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Ra.NoData,{children:"No spans found for this trace."}):o.jsx(Ra.Content,{children:o.jsx(pRe,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function mSs(){const[e,t]=ya(),n=fSs(e,t),r=oSs(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=BRe(),{data:d=[],isPending:f}=LRe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:p}=FRe(),{data:m=[],isPending:v}=zRe(),y=g.useMemo(()=>Jws({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(()=>rSs({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:E}=Zws({filters:b}),{logIdMap:T,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=uSs(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:M}=xA(n.featuredTraceId??null),{data:B,isLoading:V}=ZQ(n.featuredTraceId??"",n.featuredSpanId??""),q=g.useCallback(()=>n.applyFilterTokens(sSs(y,n.filterTokens)),[y,n]),F=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),H=g.useCallback(Y=>n.handleFeaturedChange({traceId:Y,spanId:null}),[n]),D=g.useCallback((Y,te)=>n.handleFeaturedChange({traceId:Y,spanId:te}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),z=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(Y=>n.handleFeaturedChange({spanId:Y??null}),[n]),U=o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(KL,{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($Re,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:a})]})}),o.jsx(Dws,{isLoading:w,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:q,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(_ws,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const W=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!w&&!W?o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(Bws,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Ews,{logCollapsed:i,listSlot:o.jsx(Mws,{logs:x,isLoading:w,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:E,logIdMap:T,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Cws,{log:N,onClose:F,onTraceClick:H,onSpanClick:D,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(pSs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:M,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(hSs,{spanId:n.featuredSpanId,span:B?.span,isLoading:V,onClose:z}):null})]})}function gSs({server:e,rowProps:t}){const{paths:n,Link:r}=ln(),a=Ze().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=vqt(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=Rd(e.name,50);return o.jsxs(ve.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(ve.NameCell,{children:h}),o.jsx(ve.DescriptionCell,{children:i}),o.jsx(ve.TextCell,{className:"text-center",children:d||""}),o.jsx(ve.TextCell,{className:"text-center",children:u||""}),o.jsx(ve.TextCell,{className:"text-center",children:f||""})]})}function vSs({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}=ol({count:r.length});return t?o.jsx(Do,{columns:"auto 1fr auto auto auto"}):o.jsxs(ve,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"URL"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(co,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Tools",short:o.jsx(Uf,{}),tooltip:"Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Workflows",short:o.jsx(Su,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(ve.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(gSs,{server:i,rowProps:a(l)},i.id))]})}const ySs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),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.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Ds,{})]})})}),bSs=()=>{const{data:e=[],isLoading:t,error:n}=DQ(),[r,s]=g.useState("");return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Es,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"MCP servers"})}):n?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Zn,{children:o.jsx(ySs,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(Uc,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(vSs,{mcpServers:e,isLoading:t,search:r})]})},xSs=(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 wSs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=ln(),i=g.useMemo(()=>xSs(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=ol({count:l.length});return n?o.jsx(Do,{columns:"auto 1fr auto"}):o.jsxs(ve,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"Description"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(co,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(ve.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const h=Rd(d.id,50),p=Rd(d.description??"",200),m=d.agents.length;return o.jsxs(ve.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(ve.NameCell,{children:h}),o.jsx(ve.DescriptionCell,{children:p}),o.jsx(ve.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const SSs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),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.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Ds,{})]})})}),kSs=()=>{const e=Ze();return bn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new qC;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Ve.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},OSs=({toolId:e})=>{const{canExecute:t}=Vo(),n=t("tools"),{data:r={}}=zm(),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}=i2r(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=kSs(),{requestContext:h}=vs();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Ve.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?bm(Ax(c?.inputSchema)):xs({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(wt,{className:"mb-4 h-8 w-48"}),o.jsx(wt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(ZAe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:p,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 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-6 py-12 text-center",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function CSs({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}){const{data:u={},isLoading:d,isError:f,error:h}=aA(),{data:p={},isLoading:m,isError:v,error:y}=zm(),{navigate:b,paths:x}=ln();g.useEffect(()=>{if(f){const _=h instanceof Error?h.message:"Failed to load tools";Ve.error(`Error loading tools: ${_}`)}},[f,h]),g.useEffect(()=>{if(v){const _=y instanceof Error?y.message:"Failed to load agents";Ve.error(`Error loading agents: ${_}`)}},[v,y]);const w=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(E=>{w.has(E.id)||w.set(E.id,E)})}),Object.values(u).forEach(_=>{w.has(_.id)||w.set(_.id,_)});const k=Array.from(w.values()).map(_=>({label:_.id,value:_.id})),O=_=>{t?t(_):_&&_!==e&&b(x.toolLink(_))};return o.jsx(Fo,{options:k,value:e,onValueChange:O,placeholder:d||m?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||d||m||f||v,variant:l,size:c})}const _Ss=({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(Ox,{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(Ox,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",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-6",children:[o.jsx(yt,{icon:o.jsx(YVt,{}),size:"sm",children:"Version"}),o.jsx(yt,{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(yt,{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(Da,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(yt,{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(Da,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(yt,{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(Da,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(ESs,{server:t})})]})},ESs=({server:e})=>{const{data:t={},isLoading:n}=vqt(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(Je,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(R_,{})}),o.jsx(ge,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(jSs,{tool:a,serverId:e.id},s)})})]})};function TSs(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 jSs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=ln(),a=_qt[e.toolType||"tool"],i=TSs(e._meta);return o.jsxs(Gf,{onClick:()=>n.current?.click(),children:[o.jsx(GLt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Yf,{children:[o.jsx(Qf,{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(yt,{size:"xs",children:"App"})]})}),o.jsx(cp,{children:e.description})]})]})},NSs=()=>{const{serverId:e}=ur(),{data:t=[],isLoading:n}=DQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(_Ss,{isLoading:n,server:r})})};function ISs(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 ASs=({toolId:e,serverId:t})=>{const{canExecute:n}=Vo(),r=n("tools"),s=Ze(),{data:a,isLoading:i,error:l}=WAe(t,e),{mutateAsync:c,isPending:u,data:d}=ils(t,e),f=a?ISs(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";Ve.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(wt,{className:"mb-4 h-8 w-48"}),o.jsx(wt,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 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=bm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Ve.error("Failed to process tool input schema."),v=xs({})}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(gqt,{html:h,toolName:a.name??a.id,onToolCall:p})}),o.jsx(ZAe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},RSs=()=>{const{serverId:e,toolId:t}=ur(),{data:n,isLoading:r}=WAe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(ASs,{toolId:t,serverId:e})})},UWt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],rI="rootEntityType",sI={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"},bY=Object.keys(sI),ZRe="mastra:metrics:saved-filters";function PSs(e){const t=FSs(e);try{localStorage.setItem(ZRe,t.toString())}catch{}}function $Ss(){try{localStorage.removeItem(ZRe)}catch{}}function qWt(){try{const e=localStorage.getItem(ZRe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function MSs(e){if(e.has(rI))return!0;for(const t of bY)if(e.has(sI[t]))return!0;return!1}function DSs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:UWt.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 LSs(e){const t=[],n=new Map([[rI,"rootEntityType"]]);for(const s of bY)n.set(sI[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 FSs(e){const t=new URLSearchParams,n=e.getAll(rI);for(const r of n)t.append(rI,r);for(const r of bY){const s=sI[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function zSs(e,t){e.delete(rI);for(const n of bY)e.delete(sI[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?rI:sI[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 BSs="Any";function Ant(e){const t=e.trim();return t===""||t===BSs}const USs=new Set(UWt.map(e=>e.entityType));function Rnt(e){const t=e.trim();return USs.has(t)?t:void 0}function qSs(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=>!Ant(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?Rnt(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Ant(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=Rnt(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const VWt=[{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"}],VSs=new Set(VWt.map(e=>e.value));function HSs(e){return typeof e=="string"&&(VSs.has(e)||e==="custom")}const HWt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function xY(){return g.useContext(HWt)}function WSs(e,t){return e!=="custom"?VWt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${mr(t.from,"MMM d, yyyy")} – ${mr(t.to,"MMM d, yyyy")}`:mr(t.from,"MMM d, yyyy"):"Custom range"}function ZSs({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(()=>qSs(d),[d]),h=g.useMemo(()=>JSON.stringify(f),[f]),p=WSs(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(HWt.Provider,{value:m,children:e})}const GSs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function QSs(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 YSs(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 KSs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=xY(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(KL,{preset:QSs(e),onPresetChange:i=>{const l=YSs(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:GSs})}const N0e=1440*60*1e3,XSs={"24h":N0e,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function JSs(e,t,n){if(e!=="custom"){const r=XSs[e]??N0e;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-N0e),end:t?.to??new Date(n)}}function Vm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=xY(),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(()=>JSs(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 WWt(){const e=Ze(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function s5({href:e,LinkComponent:t="a"}){return o.jsx(oe,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(Ec,{})})}function e1s({href:e,LinkComponent:t="a"}){return o.jsx(oe,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(oen,{})})}function t1s(e){return e==="agents"||e==="workflows"||e==="tools"}function Pnt(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 n1s(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const r1s=[{dataKey:"p50",label:"p50",color:Gh.blue,aggregate:e=>({value:Pnt(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Gh.yellow,aggregate:e=>({value:Pnt(e,"p95"),suffix:"avg ms"})}];function goe({data:e,onPointClick:t}){return e.length===0?o.jsx(qt.NoData,{message:"No latency data yet"}):o.jsx(LD,{data:e,series:r1s,onPointClick:t?n=>n1s(n)?t(n):void 0:void 0})}function s1s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(qt.Summary,{value:y,label:"Avg p50"}),p?o.jsx(qt.Actions,{children:p}):null]}),t?o.jsx(qt.Loading,{}):n?o.jsx(qt.Error,{message:"Failed to load latency data"}):o.jsx(qt.Content,{children:m?o.jsxs(wl,{value:h,onValueChange:b=>{t1s(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(xl,{children:[o.jsx(wr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(wr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(wr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Qr,{value:"agents",children:o.jsx(goe,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Qr,{value:"workflows",children:o.jsx(goe,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Qr,{value:"tools",children:o.jsx(goe,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(qt.NoData,{message:"No latency data yet"})})]})}function a1s(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 i1s(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 ZWt(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=a1s(s);l&&e.set(t,l)}function Io(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function GWt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function $nt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(Bw,"branches"),ZWt(a,Uw,VT,HT,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Qx,i),r.status&&a.set(Yx,r.status),Io(a,jl.entityName,r.entityName??n.entityName),Io(a,jl.threadId,r.threadId??n.threadId),Io(a,jl.resourceId,r.resourceId??n.resourceId),Io(a,jl.entityId,n.entityId),Io(a,jl.runId,n.runId),Io(a,jl.sessionId,n.sessionId),Io(a,jl.requestId,n.requestId),Io(a,jl.userId,n.userId),Io(a,jl.organizationId,n.organizationId),Io(a,jl.experimentId,n.experimentId),Io(a,jl.serviceName,n.serviceName),Io(a,jl.environment,n.environment),GWt(a,jl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function o1s({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;ZWt(a,nx,rx,sx,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Kx,i),Io(a,Nl.entityName,r.entityName??n.entityName),Io(a,Nl.threadId,r.threadId??n.threadId),Io(a,Nl.resourceId,r.resourceId??n.resourceId),Io(a,Nl.runId,n.runId),Io(a,Nl.sessionId,n.sessionId),Io(a,Nl.requestId,n.requestId),Io(a,Nl.userId,n.userId),Io(a,Nl.organizationId,n.organizationId),Io(a,Nl.experimentId,n.experimentId),Io(a,Nl.serviceName,n.serviceName),Io(a,Nl.environment,n.environment),GWt(a,Nl.tags,n.tags),r.status==="error"&&a.append(Nl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function TA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=xY(),a=g.useCallback((c={})=>$nt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>o1s({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=i1s(u,d);return $nt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const QWt="1h";async function voe(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:QWt,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 l1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([voe(e,"mastra_agent_duration_ms",t),voe(e,"mastra_workflow_duration_ms",t),voe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:QWt}}})}const Mnt={agents:Yu.AGENT,workflows:Yu.WORKFLOW_RUN,tools:Yu.TOOL};function c1s(){const{data:e,isLoading:t,isError:n}=l1s(),{getTracesHref:r,getBucketTracesHref:s}=TA(),{Link:a}=ln(),i=Kr();return o.jsx(s1s,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Mnt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(s5,{href:r({rootEntityType:Mnt[l]}),LinkComponent:a})})}function u1s(e){return e==="threads"||e==="resources"}function yoe(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function d1s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(qt.Summary,{value:h.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(qt.Summary,{value:p.toLocaleString(),label:"Total threads"}),v?o.jsx(qt.Actions,{children:v}):null]}),m.isLoading?o.jsx(qt.Loading,{}):m.isError?o.jsx(qt.Error,{message:"Failed to load memory data"}):o.jsx(qt.Content,{children:o.jsxs(wl,{defaultTab:"threads",value:i,onValueChange:y=>{u1s(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(xl,{children:[o.jsx(wr,{value:"threads",children:"Threads"}),o.jsx(wr,{value:"resources",children:"Resources"})]}),o.jsx(Qr,{value:"threads",children:d?o.jsxs(ve,{columns:"auto auto auto auto auto",...f0e,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{className:"text-ui-sm",children:yoe(y.threadId)}),o.jsx(ve.NumberCell,{children:y.resourceId?yoe(y.resourceId):"—"}),o.jsx(ve.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?to(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Fd(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ve.RowStatic,{children:x},y.key)})]}):o.jsx(qt.NoData,{message:"No thread activity yet"})}),o.jsx(Qr,{value:"resources",children:f?o.jsxs(ve,{columns:"auto auto auto auto",...f0e,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{className:"text-ui-sm",children:yoe(y.resourceId)}),o.jsx(ve.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?to(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Fd(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ve.RowStatic,{children:x},y.key)})]}):o.jsx(qt.NoData,{message:"No resource activity yet"})})]})})]})}const boe=20;function f1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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:boe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:boe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:boe})]),l=new Map,c=d=>wA(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 xoe=20;function h1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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:xoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:xoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:xoe})]),l=new Map,c=d=>wA(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 p1s(){const e=f1s(),t=h1s(),{getTracesHref:n}=TA(),{Link:r}=ln();return o.jsx(d1s,{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 a5({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 m1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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 g1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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 v1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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 y1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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 b1s(){const{data:e,isLoading:t,isError:n}=WWt();return o.jsx(a5,{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 x1s(){const{data:e,isLoading:t,isError:n}=v1s();return o.jsx(a5,{label:"Total Model Cost",value:e?.cost!=null?Fd(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Fd(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function w1s(){const{data:e,isLoading:t,isError:n}=y1s();return o.jsx(a5,{label:"Total Tokens",value:e?.value!=null?to(e.value):null,prevValue:e?.previousValue!=null?to(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function S1s(){const{data:e,isLoading:t,isError:n}=g1s();return o.jsx(a5,{label:"Total Threads",value:e?.value!=null?to(e.value):null,prevValue:e?.previousValue!=null?to(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function k1s(){const{data:e,isLoading:t,isError:n}=m1s();return o.jsx(a5,{label:"Total Resources",value:e?.value!=null?to(e.value):null,prevValue:e?.previousValue!=null?to(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function O1s({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=>C1s(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(PRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ARe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function C1s(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 _1s({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.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?Fd(l):"—":c.size===1?u=l>0?Fd(l,[...c][0]):"—":u="Mixed",o.jsx(qt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(qt.Actions,{children:s}):null]}),t?o.jsx(qt.Loading,{}):n?o.jsx(qt.Error,{message:"Failed to load model usage data"}):o.jsx(qt.Content,{children:i?o.jsxs(ve,{columns:"auto auto auto auto auto auto",...f0e,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Model"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(ve.NumberCell,{children:l.input}),o.jsx(ve.NumberCell,{children:l.output}),o.jsx(ve.NumberCell,{children:l.cacheRead}),o.jsx(ve.NumberCell,{children:l.cacheWrite}),o.jsx(ve.NumberCell,{highlight:!0,children:l.cost!=null?Fd(l.cost,l.costUnit):"—"})]});return c?o.jsx(ve.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(ve.RowStatic,{children:u},l.model)})]}):o.jsx(qt.NoData,{message:"No model usage data yet"})})]})}function E1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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=>wA(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:to(f.input),output:to(f.output),cacheRead:to(f.cacheRead),cacheWrite:to(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function T1s(){const{data:e,isLoading:t,isError:n}=E1s(),{getTracesHref:r}=TA(),{Link:s}=ln();return o.jsx(_1s,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Yu.AGENT}),actions:o.jsx(s5,{href:r({rootEntityType:Yu.AGENT}),LinkComponent:s})})}function j1s(e){return e==="tokens"||e==="cost"}function N1s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(qt.Summary,{value:Fd(v,m),label:"Total cost"}):o.jsx(qt.Summary,{value:to(d),label:"Total tokens"})),u&&s?o.jsx(qt.Actions,{children:s}):null]}),t?o.jsx(qt.Loading,{}):n?o.jsx(qt.Error,{message:"Failed to load token usage data"}):o.jsx(qt.Content,{children:u?o.jsxs(wl,{defaultTab:"tokens",value:i,onValueChange:b=>{j1s(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(xl,{children:[o.jsx(wr,{value:"tokens",children:"Tokens"}),o.jsx(wr,{value:"cost",children:"Cost"})]}),o.jsx(Qr,{value:"tokens",children:o.jsx(nI,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Gh.blueDark},{label:"Output",color:Gh.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:to})}),o.jsx(Qr,{value:"cost",children:y?o.jsx(nI,{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:Gh.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Fd(b,m)}):o.jsx(qt.NoData,{message:"No cost data yet"})})]}):o.jsx(qt.NoData,{message:"No token usage data yet"})})]})}function I1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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=>wA(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 A1s(){const{data:e,isLoading:t,isError:n}=I1s(),{getTracesHref:r}=TA(),{Link:s}=ln();return o.jsx(N1s,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Yu.AGENT,entityName:a.name}),actions:o.jsx(s5,{href:r({rootEntityType:Yu.AGENT}),LinkComponent:s})})}function I0e(e,t=to){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const R1s=[{dataKey:"input",label:"Input tokens",color:Gh.blue,aggregate:I0e("input")},{dataKey:"output",label:"Output tokens",color:Gh.yellow,aggregate:I0e("output")}];function P1s(e){return e==="tokens"||e==="cost"}function $1s({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:Gh.purple,aggregate:I0e("cost",k=>Fd(k,v))}];return o.jsxs(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(qt.Summary,{value:Fd(y,v),label:"Total cost"}):o.jsx(qt.Summary,{value:to(d),label:"Total tokens"})),u&&s?o.jsx(qt.Actions,{children:s}):null]}),n?o.jsx(qt.Loading,{}):r?o.jsx(qt.Error,{message:"Failed to load token usage timeline"}):o.jsx(qt.Content,{children:u?o.jsxs(wl,{defaultTab:"tokens",value:a,onValueChange:k=>{P1s(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(xl,{children:[o.jsx(wr,{value:"tokens",children:"Tokens"}),o.jsx(wr,{value:"cost",children:"Cost"})]}),o.jsx(Qr,{value:"tokens",children:o.jsx(LD,{data:c,series:R1s})}),o.jsx(Qr,{value:"cost",children:b?o.jsx(LD,{data:h,series:w}):o.jsx(qt.NoData,{message:"No cost data yet"})})]}):o.jsx(qt.NoData,{message:"No token usage data yet"})})]})}function M1s(e){return e==="24h"?"1h":"1d"}function D1s(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 Dnt(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 L1s(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function F1s(){const e=Ze(),{datePreset:t,filters:n,filterKey:r}=Vm(),s=M1s(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 Dnt(l,a.series[0],"input"),Dnt(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:D1s(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:L1s(u)}}),interval:s}}})}function z1s(){const{data:e,isLoading:t,isError:n}=F1s(),{getTracesHref:r}=TA(),{Link:s}=ln();return o.jsx($1s,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(s5,{href:r(),LinkComponent:s})})}function woe({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(nI,{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:Gh.blueDark},{label:"Errors",color:Gh.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:to})}function B1s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(qt.Summary,{value:to(f),label:"Total runs"}),u?o.jsx(qt.Actions,{children:u}):null]}),t?o.jsx(qt.Loading,{}):n?o.jsx(qt.Error,{message:"Failed to load trace volume data"}):o.jsx(qt.Content,{children:d?o.jsxs(wl,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(xl,{children:[o.jsx(wr,{value:"agents",children:"Agents"}),o.jsx(wr,{value:"workflows",children:"Workflows"}),o.jsx(wr,{value:"tools",children:"Tools"})]}),o.jsx(Qr,{value:"agents",children:e.agentData.length>0?o.jsx(woe,{data:e.agentData,rowHrefs:h("agents"),errorHrefs:p("agents"),LinkComponent:i}):o.jsx(qt.NoData,{message:"No agent data yet"})}),o.jsx(Qr,{value:"workflows",children:e.workflowData.length>0?o.jsx(woe,{data:e.workflowData,rowHrefs:h("workflows"),errorHrefs:p("workflows"),LinkComponent:i}):o.jsx(qt.NoData,{message:"No workflow data yet"})}),o.jsx(Qr,{value:"tools",children:e.toolData.length>0?o.jsx(woe,{data:e.toolData,rowHrefs:h("tools"),errorHrefs:p("tools"),LinkComponent:i}):o.jsx(qt.NoData,{message:"No tool data yet"})})]}):o.jsx(qt.NoData,{message:"No trace volume data yet"})})]})}async function Soe(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=wA(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 U1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([Soe(e,"mastra_agent_duration_ms",t),Soe(e,"mastra_workflow_duration_ms",t),Soe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const b8={agents:Yu.AGENT,workflows:Yu.WORKFLOW_RUN,tools:Yu.TOOL};function q1s(){const{data:e,isLoading:t,isError:n}=U1s(),{getTracesHref:r,getLogsHref:s}=TA(),{Link:a}=ln();return o.jsx(B1s,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:b8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:b8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(s5,{href:r({rootEntityType:b8[i]}),LinkComponent:a}),o.jsx(e1s,{href:s({rootEntityType:b8[i],status:"error"}),LinkComponent:a})]})})}const koe="period",x8="dateFrom",w8="dateTo";function V1s(){const[e,t]=ya(),n=e.get(koe),r=HSs(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(x8)),h=d(e.get(w8));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),a=g.useMemo(()=>LSs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(koe):h.set(koe,d),d!=="custom"&&(h.delete(x8),h.delete(w8)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(x8,d.from.toISOString()):h.delete(x8),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 zSs(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,MSs(e)))return;const d=qWt();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),o.jsx(ZSs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(H1s,{})})}function H1s(){const[e]=ya(),{error:t,isLoading:n}=WWt(),{filterTokens:r,setFilterTokens:s}=xY(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=HQ(),{data:d,isLoading:f}=BRe(),{data:h,isLoading:p}=LRe(),{data:m,isLoading:v}=zRe(),{data:y,isLoading:b}=FRe(),x=g.useMemo(()=>DSs({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(()=>qWt()!==null),O=g.useCallback(()=>{PSs(e),k(!0),Ve.success("Filters setting for Metrics saved")},[e]),_=g.useCallback(()=>{$Ss(),k(!1),Ve.success("Filters setting for Metrics cleared up")},[]),E=g.useCallback(()=>{s([])},[s]),T=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(R=>R.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&&hs(t)?o.jsx(Zn,{children:o.jsx(Es,{})}):t&&ps(t)?o.jsx(Zn,{children:o.jsx(Os,{resource:"metrics"})}):t?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(KSs,{}),o.jsx($Re,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(O1s,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:T,onRemoveAll:E,onSave:O,onRemoveSaved:w?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(An,{variant:"info",title:"Metrics are not persisted",children:o.jsx(An.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(C0e,{children:[o.jsx(b1s,{}),o.jsx(x1s,{}),o.jsx(w1s,{}),o.jsx(S1s,{}),o.jsx(k1s,{})]}),o.jsxs(C0e,{children:[o.jsx(T1s,{}),o.jsx(A1s,{}),o.jsx(z1s,{}),o.jsx(p1s,{}),o.jsx(q1s,{}),o.jsx(c1s,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),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.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Ds,{})]})})})]})}const W1s=50;function Z1s(){const{paths:e}=ln(),{isCmsAvailable:t}=O1(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=Iqt({page:s,perPage:W1s}),d=i?.promptBlocks??[],f=i?.hasMore??!1,h=g.useCallback(()=>{u||a(v=>v+1)},[u]),p=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&hs(c)?o.jsx(Zn,{children:o.jsx(Es,{})}):c&&ps(c)?o.jsx(Zn,{children:o.jsx(Os,{resource:"prompt blocks"})}):c?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(Zn,{children:o.jsx(fus,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Uc,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(oe,{as:yo,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Fr,{}),"Create Prompt"]})]})}),o.jsx(dus,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:h,onPrevPage:p})]})}function G1s(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(Xls,{children:o.jsx(e0e,{})})})})}const Q1s=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:_Xt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:put,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Ds,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:c3,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:yut,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:mut,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Y1s(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:Q1s.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(Ds,{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 leading-relaxed",children:e.description})]},e.href))})})})}function K1s(){const{data:e={},isLoading:t,error:n}=up(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&hs(n))return o.jsx(Zn,{children:o.jsx(Es,{})});if(n&&ps(n))return o.jsx(Zn,{children:o.jsx(Os,{resource:"scorers"})});if(n)return o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(Zn,{children:o.jsx($Hr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(DHr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(PHr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}const YWt=["input","entity"],X1s={input:"Input",entity:"Entity"};function J1s(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 eks(){const[e,t]=g.useState(new Set),n=g.useMemo(()=>new Set(YWt.filter(a=>!e.has(a))),[e]),r=g.useMemo(()=>J1s(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 tks({visibleColumns:e,toggleColumn:t}){return o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsxs(oe,{children:[o.jsx(but,{}),"Columns"]})}),o.jsxs(ot.Content,{align:"end",children:[o.jsx(ot.Label,{children:"Toggle columns"}),YWt.map(n=>o.jsx(ot.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:X1s[n]},n))]})]})}function nks(){const{scorerId:e}=ur(),[t,n]=ya(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=Kr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=pHr(e),p=eks(),{data:m={},isLoading:v,error:y}=zm(),{isLoading:b,error:x}=Yy(),{data:w=[],isLoading:k,error:O,isFetchingNextPage:_,hasNextPage:E,setEndOfListElement:T}=hHr({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),N=g.useMemo(()=>f?.agentIds?.filter(W=>m[W]).map(W=>({value:W,label:m[W].name,type:"AGENT"}))||[],[f?.agentIds,m]),I=g.useMemo(()=>f?.workflowIds?.map(W=>({value:W,label:W,type:"WORKFLOW"}))||[],[f?.workflowIds]),A=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...N,...I],[N,I]),R=t.get("entity")??"all",L=A.find(W=>W.value===R);L&&L.value!==u?.value&&d(L),g.useEffect(()=>{if(h){const W=h instanceof Error?h.message:"Failed to load scorer";Ve.error(`Error loading scorer: ${W}`)}},[h]),g.useEffect(()=>{if(y){const W=y instanceof Error?y.message:"Failed to load agents";Ve.error(`Error loading agents: ${W}`)}},[y]),g.useEffect(()=>{if(x){const W=x instanceof Error?x.message:"Failed to load workflows";Ve.error(`Error loading workflows: ${W}`)}},[x]);const M=W=>{W?.value&&n(Y=>{const te=new URLSearchParams(Y);return te.set("entity",W.value),te})};g.useEffect(()=>{const W=t.get("scoreId")??void 0;if(W===s)return;if(!W){a(void 0);return}w.find(te=>te.id===W)&&a(W)},[t,w]);const B=g.useCallback(W=>{a(W||void 0),n(Y=>{const te=new URLSearchParams(Y);return W?te.set("scoreId",W):te.delete("scoreId"),te})},[n]);if(!f)return null;const V=hs(h)||hs(y)||hs(x),q=h&&ps(h),F=!V&&!q&&(h||y||x),H=!k&&w.length===0,D=u?.value!=="all",G=f?.scorer?.source==="stored",z=e?o.jsx(mY,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:W=>{c(`/experiments/${W}`)}}):null,$=G?o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(oe,{size:"lg","aria-label":"Scorer actions menu",children:o.jsx(XS,{})})}),o.jsx(ot.Content,{align:"end",className:"w-48",children:o.jsxs(ot.Item,{onSelect:()=>{c(`/cms/scorers/${e}/edit`)},children:[o.jsx(Qh,{})," Edit Scorer"]})})]}):null;if(V||q||F||H&&!D){const W=(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",Y=V||q||F;return o.jsxs(Lt,{width:"wide",height:"full",className:Y||!$?"grid-rows-[1fr]":void 0,children:[!Y&&$&&o.jsx(Lt.TopArea,{children:o.jsx(ts,{className:"ml-auto",children:$})}),o.jsx(Lt.MainArea,{isCentered:!0,children:V?o.jsx(Es,{}):q?o.jsx(Os,{resource:"scorers"}):F?o.jsx(Fs,{title:"Failed to load scorer",message:W}):o.jsx(iHr,{onRunExperiment:()=>l(!0)})}),z]})}return o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(oHr,{selectedEntity:u,entityOptions:A,onEntityChange:M,onReset:()=>{n(W=>{const Y=new URLSearchParams(W);return Y.set("entity","all"),Y})},isLoading:k||v||b}),o.jsxs(ts,{children:[o.jsx(tks,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),o.jsxs(oe,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Pc,{}),"Run Experiment"]}),$]})]})}),o.jsx(aHr,{scores:w,isLoading:k,selectedScoreId:s,isFetchingNextPage:_,hasNextPage:E,setEndOfListElement:T,onScoreClick:B,errorMsg:O?.message,columnsState:p}),z]})}const rks=io("flex min-w-0 flex-col",{variants:{variant:{default:"gap-3 sm:flex-row sm:items-center sm:justify-between",factory:"gap-2 px-4 py-3 lg:flex-row lg:items-center lg:justify-between lg:gap-4"}},defaultVariants:{variant:"default"}}),sks=io("flex min-w-0 flex-col",{variants:{variant:{default:"",factory:"gap-0.5"}},defaultVariants:{variant:"default"}}),Lnt=io("",{variants:{variant:{default:"text-sm font-medium",factory:"text-ui-md leading-ui-md text-neutral5"}},defaultVariants:{variant:"default"}}),aks=io("flex flex-col gap-0.5",{variants:{variant:{default:"text-sm text-neutral3",factory:"text-ui-sm text-neutral3"}},defaultVariants:{variant:"default"}});function iks({label:e,description:t,htmlFor:n,variant:r,className:s,children:a}){return o.jsxs("div",{className:K(rks({variant:r}),s),"data-slot":"settings-row",children:[o.jsxs("div",{className:sks({variant:r}),children:[n?o.jsx(Mt,{htmlFor:n,className:Lnt({variant:r}),children:e}):o.jsx("span",{className:Lnt({variant:r}),children:e}),t&&o.jsx("div",{className:aks({variant:r}),children:t})]}),a]})}const KWt=[{value:"dark",label:"Dark",Icon:Oen},{value:"light",label:"Light",Icon:Ytn},{value:"system",label:"System",Icon:Rut}],oks=e=>KWt.some(t=>t.value===e);function lks({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const cks=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=UH(),{theme:r,setTheme:s}=c_();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(Oxe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(iks,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ka,{value:r,onValueChange:a=>{oks(a)&&s(a)},children:[o.jsx(Ca,{id:"theme",className:"w-full sm:w-48",children:o.jsx(Oa,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(_a,{children:KWt.map(a=>o.jsx(jr,{value:a.value,children:o.jsx(lks,{option:a})},a.value))})]})})}),o.jsx(Oxe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(L4t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function uks(){const[e]=ya(),t=Kr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(zWt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function dks(e){return e.replace(/\/$/,"").split("/").pop()}function wY({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function fks({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-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg 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(co,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Uf,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Put,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(mI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(R_,{})," ",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(xG,{})," ",dks(a.githubUrl)]})})]},a.slug)})})}function hks({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-8","[&>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-8",u),children:[o.jsx(ED,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Kd,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Kd,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(oe,{onClick:c,children:["Reset ",o.jsx(or,{})]})]})}function pks(){const{data:e,isLoading:t}=Dsr(),{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(ia,{children:[o.jsx(V1e,{children:o.jsxs(Bxt,{children:[o.jsx(Je,{children:o.jsx(ux,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(hks,{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(fks,{templates:y,linkComponent:yo,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const mks="1.66.0-alpha.4";function gks({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(jc,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(FXt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(wY,{className:"text-neutral3 mb-8 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-xs",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:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs 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:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function vks({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(wY,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",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($ut,{})]}),o.jsx(Kd,{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(Vt,{})," Loading variables..."]}):Object.entries(r).map(([h,p])=>o.jsxs(g.Fragment,{children:[o.jsx(Jh,{name:`env-${h}`,labelIsHidden:!0,label:"Key",value:h,disabled:!0,className:"w-full"}),o.jsx(Jh,{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-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(D4t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(oe,{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(Vt,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Mf,{})]})})]})})}function yks({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-8 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(ux,{}),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 leading-7",{"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(Cm,{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(Z0e,{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(xG,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(Uje,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Fnt(e){switch(e){case"running":return o.jsx(Vt,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Dr,{"aria-hidden":!0});case"failed":return o.jsx(or,{"aria-hidden":!0});default:return null}}function bks(){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 xks({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",Yr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(bks,{}):Fnt(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Yr.colors,Yr.transform,Yr.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:Fnt(e)})}function wks({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",Yr.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",Yr.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",Yr.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(xks,{status:e.status,variant:r})]})}function Sks({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(wks,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function kks({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",Yr.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",Yr.colors,Yr.transform,Yr.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(Vt,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-xs text-neutral3",Yr.colors),children:[n," of ",t," steps completed"]})]})}function Oks({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(wY,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg 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-6",children:o.jsx(kks,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-6 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(Den,{}),l||"Something went wrong"]}),u&&o.jsx(Sks,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(Vt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Cks({name:e,installedEntities:t}){return o.jsxs(wY,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx($ut,{}),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(Uje,{data:t})]})}function _ks(){const{templateSlug:e}=ur(),[t,n]=ya(),[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),[E,T]=g.useState([]),{data:N,isLoading:I}=Lsr({repoOrSlug:e,owner:"mastra-ai"}),R=mks?.includes("beta")??!1?"beta":"main",{data:L,isLoading:M}=Fsr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:B,isLoading:V}=zsr(),{mutateAsync:q,isPending:F}=Bsr(),{mutateAsync:H}=Usr(),{streamInstall:D,streamResult:G,isStreaming:z}=Vsr(B),{observeInstall:$,streamResult:U,isStreaming:W}=Hsr(B);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!p&&!z&&!W&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),H({runId:ne}).then(se=>{const de=se.snapshot;if(de?.status==="success"&&de?.result?.success)y(!0);else if(de?.result?.success===!1)if(de?.result?.validationResults&&!de?.result?.validationResults?.valid&&de?.result?.validationResults?.remainingErrors>0){const{remainingErrors:ye,errors:he}=de.result.validationResults,xe=`Template installation completed but ${ye} validation issue${ye>1?"s":""} remain unresolved.`;m(xe),T(he||[])}else{const ye=de?.result?.message||de?.result?.error||"Template installation failed";m(typeof ye=="string"?ye:String(ye))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,p,z,W,H]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),de=t.get("provider");if(ne&&se==="true"&&de&&!z&&!W&&!w&&!O&&B){x(ne),k(!0);try{H({runId:ne}).then(ue=>{if(ue.snapshot?.status==="running")return $.mutateAsync({runId:ne})}).then(()=>{n(ue=>{const ye=new URLSearchParams(ue);return ye.delete("resume"),ye})}).catch(ue=>{console.error("❌ Failed to resume template installation:",ue),ue.message?.includes("404")||ue.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(ue){console.error("❌ Auto-resume failed with error:",ue),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,z,W,w,O,B,H,$,n]);const Y=[{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(Uf,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(co,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(mI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Gv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(pI,{})}],ee=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const ne=G||U;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,U?.phase,U?.error]);const J=ne=>{s(ne)},re=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),le=async()=>{const ne=Object.entries(u).reduce((se,[de,ue])=>(ue===""&&se.push(de),se),[]);if(ne.length>0){h(ne);return}if(N){m(null),y(!1),x(""),_(!0);try{const de={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:ue}=await q({});x(ue),n(ye=>{const he=new URLSearchParams(ye);return he.set("runId",ue),he.set("resume","true"),he.set("provider",r||"openai"),he}),await D.mutateAsync({inputData:de,selectedModel:{provider:a,modelId:l},runId:ue})}catch(se){_(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=ne=>{const{name:se,value:de}=ne.target;de.trim()===""?h(ue=>[...ue,se]):h(ue=>ue.filter(ye=>ye!==se)),d(ue=>({...ue,[se]:de}))};return o.jsx(ia,{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-6",children:[o.jsx(yks,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(z||W)&&o.jsx(Oks,{name:N.title,streamResult:W?U:G,runId:b,workflowInfo:B}),v&&o.jsx(Cks,{name:N.title,installedEntities:ee,linkComponent:yo}),p&&o.jsx(gks,{errorMsg:p,validationErrors:E.length>0?E:G?.validationResults?.errors||U?.validationResults?.errors}),!z&&!W&&!v&&!p&&o.jsx(vks,{providerOptions:Y,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:h,handleInstallTemplate:le,handleVariableChange:X,isLoadingEnvVars:M||V,isInstalling:F,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const Eks=()=>{const{toolId:e,agentId:t}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(mcs,{toolId:e,agentId:t})})},Tks=()=>{const{toolId:e}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(OSs,{toolId:e})})};function jks(){const{data:e,isLoading:t,error:n}=Yy(),[r,s]=g.useState("");return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Es,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"workflows"})}):n?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Zn,{children:o.jsx(nXr,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Uc,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(oe,{as:yo,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(RC,{}),"Schedules"]})]})}),o.jsx(tXr,{workflows:e||{},isLoading:t,search:r})]})}const Nks={active:"bg-accent1",paused:"bg-accent3"},Iks={active:"text-accent1",paused:"text-accent3"},XWt=({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 ${Nks[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Iks[e]}`,children:e})]}),Aj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),wM=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 JWt({status:e}){const{icon:t,color:n}=Aks(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 Aks(e){switch(e){case"success":return{icon:o.jsx(Dr,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(or,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Vt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(FV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(ks,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(lS,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const znt="auto auto auto auto 1fr";function Rks(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 Pks(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 $ks=3e4,Mks=5*6e4;function Dks({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}=ol({count:u});let h=-1;return t?o.jsx(Do,{columns:znt}):e.length===0?o.jsx(ge,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(ve,{columns:znt,className:"min-w-0",scrollRef:d,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Run"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Started"}),o.jsx(ve.TopCell,{children:"Duration"}),o.jsx(ve.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=Pks(m),y=`Scheduled ${Aj(p.scheduledFireAt)} — published ${Aj(p.actualFireAt)} (drift ${v})`,b=p.outcome==="failed",x=b?p.error:p.run?.error,w=Math.abs(m),k=!b&&w>$ks&&w<=Mks,O=`${p.scheduleId}-${p.runId}-${p.actualFireAt}`,_=c(p);_&&(h+=1);const E=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}),T=o.jsxs(o.Fragment,{children:[o.jsx(ve.Cell,{children:E}),o.jsx(ve.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(jc,{size:14}),"publish failed"]}):p.run?o.jsx(JWt,{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(fn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(jc,{size:14})})}),o.jsx(hn,{children:x})]}):null]})}),o.jsx(ve.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:wM(p.actualFireAt)}),k?o.jsxs(gn,{children:[o.jsx(fn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(jc,{size:14})})}),o.jsxs(hn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(ve.Cell,{children:p.run?o.jsx("span",{children:Rks(p.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(ve.Cell,{children:" "})]});return _?o.jsx(ve.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:i,...f(h),children:T},O):o.jsx(ve.RowStatic,{children:T},O)}),o.jsx(ve.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const Lks=e=>{const t=Ze();return mt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},Bnt=25,Fks=e=>{const t=Ze(),{inView:n,setRef:r}=s0(),s=Fy({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:Bnt,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<Bnt))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}},zks=e=>{const t=Ze(),n=Or();return bn({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"]}),Ve.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Ve.error(r.message)}})};function S8({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 Bks(){const{scheduleId:e}=ur(),{paths:t}=ln(),{data:n,error:r}=Lks(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=Fks(e),d=zks(e);if(r&&hs(r))return o.jsx(Zn,{children:o.jsx(Es,{})});if(r&&ps(r))return o.jsx(Zn,{children:o.jsx(Os,{resource:"schedules"})});if(r)return o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,h=n?.agentId;return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{className:"justify-end",children:o.jsxs(Lt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(oe,{as:yo,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(wu,{}),"Back to schedules"]}),f?o.jsx(oe,{as:yo,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(oe,{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(VV,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Pc,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(S8,{label:h?"Agent":"Workflow",children:f?o.jsx(yo,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):h?o.jsx(yo,{to:t.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),o.jsxs(S8,{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(S8,{label:"Status",children:o.jsx(XWt,{status:n.status})}),o.jsx(S8,{label:"Next fire",children:o.jsx("span",{title:Aj(n.nextFireAt),children:wM(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(Dks,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const Unt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function Uks({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}=ol({count:a.length});return t?o.jsx(Do,{columns:Unt}):o.jsxs(ve,{columns:Unt,className:"min-w-0",scrollRef:i,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Target"}),o.jsx(ve.TopCell,{children:"Schedule ID"}),o.jsx(ve.TopCell,{children:"Cron"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Next fire"}),o.jsx(ve.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(ve.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(ve.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(ve.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(ve.NameCell,{children:c.workflowId??c.agentId}),o.jsx(ve.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(ve.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(ve.Cell,{children:o.jsx(XWt,{status:c.status})}),o.jsx(ve.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:Aj(c.nextFireAt),children:wM(c.nextFireAt)})}),o.jsx(ve.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(JWt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Aj(c.lastFireAt),children:c.lastFireAt?wM(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Aj(c.lastFireAt),children:wM(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function qks({workflowId:e}={}){const{data:t,isLoading:n,error:r}=U1e(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(Uc,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(Uks,{schedules:t??[],isLoading:n,search:s})})]})}function Vks(){const[e]=ya(),t=e.get("workflowId")??void 0,{error:n}=U1e(t?{workflowId:t}:{});return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Es,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(qks,{workflowId:t})})})}function Hks({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=gCe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=pEt(r),[d]=mEt(s),{edgeTypes:f,nodeTypes:h,styledEdges:p}=eFt({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.jsxs(hEt,{nodes:l,edges:p,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:h,onNodesChange:u,children:[o.jsx(SNe,{position:"bottom-left"}),o.jsx(vEt,{variant:my.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Vt,{})})})}function Wks(){const{stepDetail:e,closeStepDetail:t}=UW();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(cS,{className:"h-4 w-4",style:{color:Du.map}}),e.type==="nested-graph"&&o.jsx(Su,{className:"h-4 w-4",style:{color:Du.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(or,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(gM,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(mCe,{children:o.jsx(Hks,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function Zks(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function Gks(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 Qks({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(Je,{children:o.jsx(FV,{})}),"Step suspended"]}),o.jsx(yt,{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?bm(Ax(i.resumeSchema)):mf(cr(),_f());return o.jsx(Yks,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function Yks({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(Je,{children:o.jsx(_en,{})}),"The step is asking"]}),o.jsxs(lc,{open:a,onOpenChange:i,children:[o.jsxs(Bl,{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(Je,{children:o.jsx(qr,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ge,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:Gks(e.suspendPayload,e.stepId)})]}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:Zks(e.suspendPayload)})]}),o.jsx(Ul,{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(Je,{children:o.jsx(Nen,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(OU,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Pc,{}),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 Kks(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Wl),{runId:a}=ur(),i=OEt(e,r??""),l=rnr(),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(Qks,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const Xks=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"})]}),Jks=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"})]}),eOs=e=>e.includes("."),tOs=e=>e==="input"||e.endsWith(".input"),nOs=1;function rOs(e){return`${Number((e/1e3).toPrecision(3))}s`}function sOs(e,t){const n=Object.entries(e).filter(([i])=>!tOs(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,nOs);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:h,durationMs:d,isRunning:c,isNestedEntry:eOs(i)}})}const aOs=({status:e})=>o.jsxs(Je,{children:[e==="success"&&o.jsx(Xks,{className:"text-accent1"}),e==="failed"&&o.jsx(Jks,{className:"text-accent2"}),e==="suspended"&&o.jsx(FV,{className:"text-accent3"}),e==="waiting"&&o.jsx(mpe,{className:"text-accent5"}),e==="skipped"&&o.jsx(mpe,{className:"text-icon3"}),e==="running"&&o.jsx(Vs,{className:"text-accent6 animate-spin"})]}),iOs={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function eZt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const qnt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},oOs=e=>{const t=e;return H6t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},lOs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=oOs(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(aOs,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(oe,{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(Vtn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(fV,{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:eZt(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 ${iOs[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(oe,{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(Utn,{})})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:rOs(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function cOs(){const{steps:e}=u4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=JH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);e0t(f,{enabled:!l});const h=sOs(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(Js,{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(lOs,{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:qnt(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:qnt(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(_Et,{data:u.data,title:`${eZt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const uOs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=UW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(oFt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(Kks,{}),o.jsx(cOs,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(Wks,{})})]})},Vnt=()=>{const{workflowId:e}=ur(),{data:t,isLoading:n,error:r}=xL(e);return r&&hs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Es,{})}):r&&ps(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"workflows"})}):o.jsx(DCe,{children:o.jsx(uOs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function dOs(e,t){if(e==null)return{};var n,r,s=jOt(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 A0e(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 fOs(e){if(Array.isArray(e))return A0e(e)}function hOs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function pOs(e,t){if(e){if(typeof e=="string")return A0e(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)?A0e(e,t):void 0}}function mOs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
673
|
+
]`,cnt="flex min-h-0 flex-1 flex-col py-0";function Gbs({tab:e,onTabChange:t,file:n,onFileSelect:r,onReplace:s,pastedText:a,onPastedTextChange:i,validation:l,isImporting:c}){return o.jsxs(wl,{value:e,defaultTab:"upload",onValueChange:t,className:"flex h-full flex-col gap-3",children:[o.jsxs(xl,{variant:"pill",children:[o.jsx(wr,{value:"upload",children:"Upload file"}),o.jsx(wr,{value:"paste",children:"Paste JSON"})]}),o.jsx(Qr,{value:"upload",className:cnt,children:n?o.jsx(Xbs,{file:n,validation:l,onReplace:s,isImporting:c}):o.jsx(Qbs,{onFileSelect:r,disabled:c})}),o.jsx(Qr,{value:"paste",className:cnt,children:o.jsx(Mo,{"aria-label":"JSON items",className:"text-ui-sm min-h-[200px] flex-1 resize-none font-mono",placeholder:Zbs,spellCheck:!1,value:a,onChange:u=>i(u.target.value),disabled:c})})]})}function Qbs({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-6 py-10 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(d3,{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 ",URe]})]})}function Ybs(e){return e>=1024*1024?`${(e/(1024*1024)).toFixed(1)} MB`:`${Math.max(1,Math.round(e/1024))} KB`}function Kbs(e){return typeof e=="string"?e:JSON.stringify(e)??""}function Xbs({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,noe);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(dI,{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:Ybs(e.size)}),o.jsx(oe,{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:Kbs(l.input)}),l.hasInput?l.hasGroundTruth?null:o.jsx(yt,{variant:"yellow",size:"xs",children:"no groundTruth"}):o.jsx(yt,{variant:"red",size:"xs",children:"no input"})]},l.index)),a>noe&&o.jsxs("div",{className:"border-border1 text-ui-xs text-neutral3 border-t px-3 py-1.5",children:["+ ",a-noe," more"]})]})}const Jbs=e=>new Promise((t,n)=>{const r=new FileReader;r.onload=()=>t(r.result),r.onerror=()=>n(r.error),r.readAsText(e)});function exs({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}=Fa(),w=a==="upload"?u:p,k=g.useMemo(()=>a==="upload"&&f?{status:"error",kind:"parse",message:f}:Vys(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>lWt){h(`File is larger than ${URe}`);return}try{const R=await Jbs(I);if(A!==b.current)return;c({name:I.name,size:I.size}),d(R),h(null)}catch{if(A!==b.current)return;h("Could not read the file")}},[]),_=g.useCallback(()=>{b.current++,c(null),d(""),h(null)},[]),E=g.useCallback(()=>{b.current++,i("upload"),c(null),d(""),h(null),m("")},[]),T=g.useCallback(()=>{v||(r(!1),setTimeout(E,150))},[v,r,E]),N=g.useCallback(async()=>{if(k.status==="ready"){y(!0);try{await x.mutateAsync({datasetId:e,items:k.items}),Ve.success(`Imported ${k.total} item${k.total!==1?"s":""}`),s?.(),r(!1),setTimeout(E,150)}catch(I){Ve.error(I instanceof Error?I.message:"Failed to import items")}finally{y(!1)}}},[k,x,e,s,r,E]);return o.jsx(vr,{open:n,onOpenChange:T,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-6 py-4",children:[o.jsx(fr,{children:"Import into dataset"}),o.jsxs($s,{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(Pr,{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-6",children:o.jsx(Gbs,{tab:a,onTabChange:i,file:l,onFileSelect:O,onReplace:_,pastedText:p,onPastedTextChange:m,validation:k,isImporting:v})}),o.jsx("div",{className:"p-6",children:o.jsx(Wbs,{})})]})}),o.jsxs(Fl,{className:"border-border1 items-center border-t px-6 py-3 sm:justify-between",children:[o.jsx(txs,{validation:k}),o.jsxs("div",{className:"flex gap-2",children:[o.jsx(oe,{onClick:T,disabled:v,children:"Cancel"}),o.jsxs(oe,{variant:"primary",onClick:N,disabled:k.status!=="ready"||v,children:[v&&o.jsx(Vt,{}),k.status==="ready"?`Import ${k.total} item${k.total!==1?"s":""}`:"Import"]})]})]})]})})}function txs({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 ${URe}`;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 nxs(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 pWt({active:e,onPrevious:t,onNext:n,onClose:r}){g.useEffect(()=>{if(!e)return;const s=a=>{a.defaultPrevented||nxs(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 mWt=g.createContext(null);function rxs({datasetId:e,items:t,isLoadingItems:n,children:r}){const s=Kr(),i=nyt("/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]);pWt({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(mWt.Provider,{value:h,children:r})}function gWt(){const e=g.useContext(mWt);if(!e)throw new Error("useDatasetItemPanel must be used within a DatasetItemPanelProvider");return e}function sxs({datasetId:e,onAddItemClick:t,onNavigateToDataset:n,leftSlot:r,rightSlot:s,belowToolbarSlot:a}){const[i,l]=ya(),{activeVersion:c}=qRe(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),[E,T]=g.useState([]),[N,I]=g.useState(0),[A,R]=g.useState(""),[L]=vke(A,300),{data:M}=Yg(e),{data:B=[],isLoading:V,setEndOfListElement:q,isFetchingNextPage:F,hasNextPage:H}=IC(e,L||void 0,c),{deleteItems:D}=Fa(),{currentItemId:G,openItem:z,close:$}=gWt(),U=X=>{G===X?$():z(X)},W=X=>{y(X),m(!0)},Y=X=>{k(X),x(!0)},te=X=>{x(X),X||(k([]),I(ne=>ne+1))},ee=X=>{T(X),_(!0)},J=async()=>{await D.mutateAsync({datasetId:e,itemIds:E}),Ve.success(`Deleted ${E.length} items`),_(!1),T([]),I(X=>X+1)},re=X=>{m(!1),y([]),I(ne=>ne+1),n?.(X)},le=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(qbs,{items:B,leftSlot:r,rightSlot:s,belowToolbarSlot:a,isLoading:V,onItemClick:U,featuredItemId:G,onAddClick:t??(()=>{}),onImportClick:()=>d(!0),onImportJsonClick:()=>h(!0),onBulkDeleteClick:ee,onCreateDatasetClick:W,onAddToDatasetClick:Y,datasetName:M?.name,clearSelectionTrigger:N,setEndOfListElement:q,isFetchingNextPage:F,hasNextPage:H,searchQuery:A,activeSearchQuery:L,onSearchChange:R,currentDatasetVersion:M?.version})}),o.jsx(Dbs,{datasetId:e,open:u,onOpenChange:d}),o.jsx(exs,{datasetId:e,datasetName:M?.name,open:f,onOpenChange:h}),o.jsx(vbs,{open:p,onOpenChange:le,items:v,onSuccess:re}),o.jsx(ybs,{open:b,onOpenChange:te,items:w,currentDatasetId:e}),o.jsx(Dt,{open:O,onOpenChange:_,children:o.jsxs(Dt.Content,{children:[o.jsxs(Dt.Header,{children:[o.jsx(Dt.Title,{children:"Delete Items"}),o.jsxs(Dt.Description,{children:["Are you sure you want to delete ",E.length," item",E.length!==1?"s":"","? This action cannot be undone."]})]}),o.jsxs(Dt.Footer,{children:[o.jsx(Dt.Cancel,{children:"Cancel"}),o.jsx(Dt.Action,{onClick:J,children:D.isPending?"Deleting...":"Delete"})]})]})})]})}const unt="__create_tag__";function axs({datasetId:e}){const{data:t}=Yg(e),{data:n}=Rm(),{updateDataset:r}=Fa(),[s,a]=g.useState(""),i=g.useMemo(()=>Array.isArray(t?.tags)?t.tags:[],[t?.tags]),l=g.useMemo(()=>cWt(n?.datasets??[]),[n?.datasets]),c=g.useMemo(()=>{const h=l.map(v=>({label:v,value:v,end:i.includes(v)?o.jsx(Dr,{"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:unt},...h]:h},[l,i,s]),u=h=>{r.mutate({datasetId:e,tags:h},{onError:()=>Ve.error("Failed to update tags")})},d=h=>{const p=h===unt?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(WQ,{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(or,{className:"size-3"})})]},h)),o.jsx(Fo,{options:c,value:void 0,onValueChange:d,onInputValueChange:a,placeholder:o.jsxs("span",{className:"flex items-center gap-1.5",children:[o.jsx(pI,{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 vWt({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(yl,{id:"override-dataset-scorers",checked:e,onCheckedChange:t,disabled:s}),o.jsx(Mt,{htmlFor:"override-dataset-scorers",children:"Override dataset scorers"})]}),o.jsx("p",{className:"text-muted-foreground text-xs",children:e?"Only selected scorers run for this item. Leave empty to run no scorers.":"Use scorers attached to the dataset."}),e?o.jsx(pY,{selectedScorers:n,setSelectedScorers:r,disabled:s,label:"Item scorers",helperText:"Choose from scorers that can be resolved by this Mastra instance."}):null]})}function ixs(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 roe({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-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function oxs({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}=Fa(),O=()=>{a("{}"),l(""),u(""),f(""),p(!1),v([]),b(""),w(null)},_=R=>{O(),n(R)},E=async R=>{R.preventDefault();let L;try{L=JSON.parse(s)}catch{Ve.error("Input must be valid JSON");return}let M;if(i.trim())try{M=JSON.parse(i)}catch{Ve.error("Ground Truth must be valid JSON");return}let B;if(c.trim())try{B=JSON.parse(c)}catch{Ve.error("Expected Trajectory must be valid JSON");return}let V;if(d.trim())try{const F=JSON.parse(d);if(!Array.isArray(F)){Ve.error("Tool Mocks must be a JSON array");return}V=F}catch{Ve.error("Tool Mocks must be valid JSON");return}let q;if(y.trim())try{q=JSON.parse(y)}catch{Ve.error("Request Context must be valid JSON");return}try{await k.mutateAsync({datasetId:e,input:L,groundTruth:M,expectedTrajectory:B,toolMocks:V,scorerIds:h?m:void 0,requestContext:q}),Ve.success("Item added successfully"),_(!1),r?.()}catch(F){const H=ixs(F);H?w(H):Ve.error(`Failed to add item: ${F instanceof Error?F.message:"Unknown error"}`)}},T=R=>{a(R),x?.field==="input"&&w(null)},N=R=>{l(R),x?.field==="groundTruth"&&w(null)},I=R=>{f(R),x?.field==="toolMocks"&&w(null)},A=()=>{_(!1)};return o.jsxs(ki,{dialogTitle:"Add Item",dialogDescription:"Create a new dataset item",isOpen:t,onClose:A,level:1,children:[o.jsx(ki.Top,{children:"Add Item"}),o.jsxs(ki.Content,{children:[o.jsx(ki.Header,{children:o.jsx(ki.Heading,{children:"Add Item"})}),o.jsxs("form",{onSubmit:E,className:"grid gap-6",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"item-input",children:"Input (JSON) *"}),o.jsx(Vr,{value:s,onChange:T,showCopyButton:!1,className:"min-h-[240px]"}),x?.field==="input"&&o.jsx(roe,{field:"input",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{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(roe,{field:"groundTruth",errors:x.errors})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{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(Mt,{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(roe,{field:"toolMocks",errors:x.errors})]}),o.jsx(vWt,{overrideEnabled:h,onOverrideEnabledChange:p,selectedScorerIds:m,onSelectedScorerIdsChange:v,disabled:k.isPending}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{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(oe,{type:"button",onClick:A,children:"Cancel"}),o.jsx(oe,{type:"submit",variant:"primary",disabled:k.isPending,children:k.isPending?"Adding...":"Add Item"})]})]})]})]})}const wk=e=>JSON.stringify(e??null,null,2),lxs=[{key:"input",title:"Input",icon:o.jsx(_O,{}),value:e=>wk(e.input)},{key:"groundTruth",title:"Ground Truth",icon:o.jsx(dy,{}),value:e=>wk(e.groundTruth)},{key:"expectedTrajectory",title:"Expected Trajectory",icon:o.jsx(Mut,{}),value:e=>e.expectedTrajectory!=null?wk(e.expectedTrajectory):void 0},{key:"toolMocks",title:"Tool Mocks",icon:o.jsx(Ud,{}),value:e=>wk(e.toolMocks??[])},{key:"scorerIds",title:"Scorers",icon:o.jsx(Y0e,{}),value:e=>e.scorerIds===void 0?"Inherited from dataset":wk(e.scorerIds)},{key:"requestContext",title:"Request Context",icon:o.jsx(nc,{}),value:e=>e.requestContext!=null?wk(e.requestContext):void 0},{key:"metadata",title:"Metadata",icon:o.jsx(pI,{}),value:e=>wk(e.metadata)}];function O0e({item:e,diff:t}){return o.jsxs(o.Fragment,{children:[o.jsxs(Fn,{children:[o.jsx(Fn.Key,{children:"Dataset Id"}),o.jsx(Fn.ValueWithCopyBtn,{copyTooltip:"Copy Dataset Id to clipboard",copyValue:e.datasetId,children:e.datasetId}),o.jsx(Fn.Key,{children:"Version"}),o.jsxs(Fn.Value,{children:["v",e.datasetVersion]}),o.jsx(Fn.Key,{children:"Created"}),o.jsx(Fn.Value,{children:mr(new Date(e.createdAt),"MMM d, yyyy h:mm aaa")}),o.jsx(Fn.Key,{children:"Updated"}),o.jsx(Fn.Value,{children:e.updatedAt&&new Date(e.updatedAt).getTime()!==new Date(e.createdAt).getTime()?mr(new Date(e.updatedAt),"MMM d, yyyy h:mm aaa"):"n/a"})]}),o.jsx("div",{className:"mt-3 grid gap-3",children:lxs.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(wn.CodeSection,{title:n.title,icon:n.icon,codeStr:r??"",diff:t?{against:s??"",side:t.side}:void 0},n.key)})})]})}function soe({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-xs",children:[o.jsxs("code",{className:"bg-destructive/10 rounded px-1",children:[e,n.path!=="/"?n.path:""]}),": ",n.message]},r))}):null}function cxs({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:"flex items-center gap-2 text-lg font-medium",children:[o.jsx(Qh,{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(Mt,{children:"Input (JSON) *"}),o.jsx(Vr,{value:e,onChange:t,showCopyButton:!1,className:"min-h-[120px]"}),y?.field==="input"&&o.jsx(soe,{field:"input",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{children:"Ground Truth (JSON, optional)"}),o.jsx(Vr,{value:n,onChange:r,showCopyButton:!1,className:"min-h-[100px]"}),y?.field==="groundTruth"&&o.jsx(soe,{field:"groundTruth",errors:y.errors})]}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{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(Mt,{children:"Tool Mocks (JSON array, optional)"}),o.jsxs("p",{className:"text-muted-foreground text-xs",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(soe,{field:"toolMocks",errors:y.errors})]}),o.jsx(vWt,{overrideEnabled:d,onOverrideEnabledChange:f,selectedScorerIds:h,onSelectedScorerIdsChange:p,disabled:w}),o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{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(Mt,{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(oe,{variant:"primary",onClick:b,disabled:w,children:w?"Saving...":"Save Changes"}),o.jsx(oe,{onClick:x,disabled:w,children:"Cancel"})]})]})]})}const uxs={light:"bg-gray-100 border-gray-300 text-gray-700 shadow-[0_1px_0_rgba(0,0,0,0.1)]",dark:"bg-surface4 border-border1 text-neutral5 shadow-[0_1px_0_rgba(0,0,0,0.3)]"},dxs={default:"h-6 min-w-6 rounded-md px-1.5 text-ui-sm",sm:"h-5 min-w-5 rounded-md px-1 text-ui-xs",xs:"h-4 min-w-4 rounded px-1 text-ui-xs leading-none"},WT=({children:e,theme:t="dark",size:n="default",className:r})=>o.jsx("kbd",{className:K("inline-flex items-center justify-center border font-mono",dxs[n],Yr.transform,"active:scale-95 active:shadow-none",uxs[t],r),children:e}),fxs=[{value:"agent",label:"Agent"},{value:"workflow",label:"Workflow"},{value:"scorer",label:"Scorer"}];function hxs({targetType:e,setTargetType:t,targetId:n,setTargetId:r,container:s}){const{data:a,isLoading:i}=zm(),{data:l,isLoading:c}=Yy(),{data:u,isLoading:d}=up(),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(Mt,{children:"Target Type"}),o.jsx(Fo,{options:fxs,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(Mt,{children:m}),o.jsx(Fo,{options:f,value:n,onValueChange:r,placeholder:`Select ${e}`,searchPlaceholder:"Search...",emptyText:"No targets available",disabled:h,container:s})]})]})}const pxs=typeof navigator<"u"&&/Mac|iPhone|iPad/.test(navigator.platform);function mxs({requestContextSchema:e,onChange:t}){const n=g.useMemo(()=>{try{return bm(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(Mt,{children:"Request Context"}),o.jsx(rL,{schema:n,onValuesChange:t,className:"[&_button[type=submit]]:hidden"})]}):o.jsx("p",{className:"text-destructive text-sm",children:"Failed to parse request context schema"})}function aoe({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-6"),children:r})]})}function mY({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??""),[E,T]=g.useState(n??null),[N,I]=g.useState({}),[A,R]=g.useState(""),{triggerExperiment:L}=Fa(),{data:M}=Yg(v),{total:B}=IC(v,void 0,b),V=M?.requestContextSchema,q=M?.scorerIds??[],F=E===null&&q.length>0,H=E??q,D=!!(V&&Object.keys(V).length>0),G=!!(v&&w&&O&&f.trim()),z=L.isPending,$=[!f.trim()&&"name",!v&&"dataset",!O&&"target"].filter(Boolean),U=D?Object.values(N).some(le=>le!==void 0&&le!==""):A.trim().length>0,W=le=>{y(le),x(null),T(n??null),I({})},Y=()=>{h(a??""),m(i??""),y(e??""),x(t??null),k(r??""),_(s??""),T(n??null),I({}),R("")},te=()=>{if(D){const le=Object.entries(N).filter(([,X])=>X!==void 0&&X!=="");return le.length>0?Object.fromEntries(le):void 0}if(A.trim()){let le;try{le=JSON.parse(A)}catch{throw new Error("Request Context must be valid JSON")}if(!le||typeof le!="object"||Array.isArray(le))throw new Error("Request Context must be a JSON object");return le}},ee=async()=>{if(!v||!w||!O||!f.trim())return;let le;try{le=te()}catch(X){const ne=X instanceof Error?X.message:"Request Context must be valid JSON";du.error(ne);return}try{const X=await L.mutateAsync({datasetId:v,name:f.trim(),description:p.trim()||void 0,targetType:w,targetId:O,scorerIds:H.length>0?H:void 0,version:b??void 0,requestContext:le});du.success("Experiment triggered successfully"),c(!1),u?.(X.experimentId),Y()}catch(X){const ne=X instanceof Error?X.message:"Failed to trigger experiment";du.error(ne)}},J=()=>{z||(c(!1),Y())},re=le=>{(le.metaKey||le.ctrlKey)&&le.key==="Enter"&&G&&!z&&(le.preventDefault(),ee())};return o.jsx(vr,{open:l,onOpenChange:J,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-6 py-4",children:[o.jsx(fr,{children:"Run experiment"}),o.jsx($s,{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(Pr,{className:"max-h-[70vh] space-y-6 overflow-y-auto px-6 py-5",children:[o.jsxs("div",{className:"space-y-4",children:[o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"experiment-name",children:"Name *"}),o.jsx(jn,{id:"experiment-name",value:f,onChange:le=>h(le.target.value),placeholder:"Enter experiment name",autoFocus:!0,disabled:z})]}),o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{htmlFor:"experiment-description",children:"Description"}),o.jsx(Mo,{id:"experiment-description",value:p,onChange:le=>m(le.target.value),placeholder:"Enter experiment description (optional)",disabled:z,rows:2})]})]}),o.jsxs("ol",{className:"list-none",children:[o.jsxs(aoe,{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(Mt,{children:"Dataset"}),o.jsx(Obs,{value:v,onValueChange:W,container:d})]}),v&&o.jsxs("div",{className:"grid gap-2",children:[o.jsx(Mt,{children:"Version"}),o.jsx(hWt,{datasetId:v,value:b,onValueChange:x,container:d})]})]}),v&&B!==void 0&&o.jsxs("p",{className:"text-ui-xs text-neutral3",children:[B," ",B===1?"item":"items"]})]}),o.jsxs(aoe,{index:2,done:!!O,children:[o.jsx(hxs,{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(aoe,{index:3,done:H.length>0,isLast:!0,children:o.jsx(pY,{selectedScorers:H,setSelectedScorers:T,disabled:z,container:d,helperText:F?"Pre-filled from the dataset's default scorers.":"Scores are computed after each item runs."})})]}),o.jsxs(lc,{children:[o.jsxs(Bl,{className:"text-ui-sm flex items-center gap-2",children:[o.jsx(qr,{className:"size-4"}),"Request Context (JSON, optional)",U&&o.jsx(yt,{size:"xs",variant:"blue",children:"set"})]}),o.jsx(Ul,{className:"pt-3",children:D?o.jsx(mxs,{requestContextSchema:V,onChange:I}):o.jsx(Vr,{value:A,onChange:R,showCopyButton:!1,"aria-label":"Request context JSON",className:"min-h-[160px]"})})]})]}),o.jsxs(Fl,{className:"border-border1 items-center border-t px-6 py-4 sm:justify-between",children:[o.jsx("p",{"data-testid":"experiment-run-status","aria-live":"polite",className:"flex items-center gap-2",children:$.length===0?o.jsxs(o.Fragment,{children:[o.jsx(yt,{variant:"green",indicator:"dot",children:"Ready"}),o.jsxs("span",{className:"text-ui-xs text-neutral3",children:[B??0," items · ",w," · ",H.length," scorers"]})]}):o.jsxs(yt,{variant:"neutral",indicator:"dot",children:["Missing ",$.join(", ")]})}),o.jsxs("div",{className:"flex items-center gap-2",children:[o.jsx(oe,{onClick:J,disabled:z,children:"Cancel"}),o.jsx(oe,{variant:"primary",onClick:ee,disabled:!G||z,children:z?o.jsxs(o.Fragment,{children:[o.jsx(Vt,{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(WT,{size:"xs",children:pxs?"⌘":"Ctrl"}),o.jsx(WT,{size:"xs",children:"↵"})]})]})})]})]})]})})}const yWt=g.createContext(null);function gxs({experimentId:e,datasetId:t,experimentStatus:n,results:r,isLoadingResults:s,hasNextPage:a,children:i}){const l=Kr(),u=nyt("/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]);pWt({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(yWt.Provider,{value:v,children:i})}function bWt(){const e=g.useContext(yWt);if(!e)throw new Error("useExperimentItemPanel must be used within an ExperimentItemPanelProvider");return e}function vxs({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}=bWt(),h=g.useMemo(()=>u?n.find(b=>b.itemId===u)?.id??null:null,[n,u]),{data:p}=Ny(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(dY,{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 yxs(e,t){if(t){const n=typeof t=="string"?new Date(t):t;return`v${e} ${mr(n,"MMM dd 'at' H:mm:ss a")}`}return`v${e}`}function bxs({datasetId:e,versionA:t,versionB:n,onVersionChange:r}){const{data:s}=aRe(e),a=(s??[]).map(i=>({value:String(i.version),label:`${yxs(i.version,i.createdAt)}${i.isCurrent?" (current)":""}`}));return o.jsxs(el.Toolbar,{className:"grid w-full grid-cols-[1fr_1fr_1fr_10rem] gap-4",children:[o.jsx("div",{}),o.jsx(Kd,{label:"Version A",labelIsHidden:!0,name:"version-a",placeholder:"Select version",options:a,value:t??"",onValueChange:i=>r?.(i,n??"")}),o.jsx(Kd,{label:"Version B",labelIsHidden:!0,name:"version-b",options:a,value:n??"",onValueChange:i=>r?.(t??"",i)}),o.jsx("div",{})]})}function xWt({children:e,className:t}){return o.jsx("div",{className:K("",t),children:e})}function xxs({date:e,className:t,withTime:n=!1}){const r=e?q0t(new Date(e)):!1,s=e?Y3(new Date(e))?"Today":mr(new Date(e),"MMM dd"):"",a=e&&!r?mr(new Date(e),"yyyy"):"",i=e&&n?`${mr(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 VRe(e){return!e||e.length===0?"":e?.map(t=>t.size).join(" ")}function wxs({columns:e,isSelectionActive:t,children:n}){return o.jsx("div",{className:K("sticky top-0 z-10 mb-4 rounded-lg bg-surface3 px-4"),children:o.jsx("div",{className:K("grid items-center gap-4 text-left text-ui-xs tracking-widest text-neutral3 uppercase",{"pl-12 [&>label]:absolute [&>label]:left-0":t}),style:{gridTemplateColumns:VRe(e)},children:n})})}function Sxs({children:e,className:t}){return o.jsx("span",{className:K("py-3",t),children:e})}function kxs({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 Oxs({children:e}){return o.jsx("ul",{className:"grid content-start",children:e})}function Cxs({children:e}){const t=g.useRef(null);return o.jsx("div",{ref:t,className:K("overflow-y-auto"),children:e})}function _xs({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 Exs({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-6 rounded-lg px-3 py-[0.6rem] text-left","hover:bg-surface4",Yr.colors,W3.visible,n),children:e});return s==null?a:o.jsxs(gn,{children:[o.jsx(fn,{render:a}),o.jsx(hn,{children:s})]})}function Txs({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-8 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(jc,{}):o.jsx(Cm,{})," ",t]}):e})}function jxs({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-8 flex justify-center opacity-50",children:[e&&r,!t&&!e&&s]}):null}function Nxs({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-8 pt-6 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(wu,{}),"Previous"]}),t&&o.jsxs("button",{onClick:n,children:["Next",o.jsx(Mf,{})]})]})]})}function Ixs({children:e,className:t}){return o.jsx("div",{className:K("grid grid-rows-[auto_1fr] overflow-y-auto",t),children:e})}function Axs({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",Yr.colors,{"selected-row":e,"grid px-4 gap-4 ":n}),style:{gridTemplateColumns:VRe(n)},children:t})}function Rxs({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-4 rounded-lg px-4 text-left",Yr.colors,W3.visible,{"bg-surface4":t,"hover:bg-surface4":e&&!t&&!i},a),style:{gridTemplateColumns:VRe(s)},disabled:i,children:r});return l==null?d:o.jsxs(gn,{children:[o.jsx(fn,{render:d}),o.jsx(hn,{children:l})]})}function Pxs(e){return e.charAt(0).toUpperCase()+e.slice(1)}function $xs({status:e}){return e?o.jsxs(gn,{children:[o.jsx(fn,{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(hn,{children:Pxs(e)})]}):null}function Mxs({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 dnt={latest:"Latest version",deleted:"Deleted in this version"};function Dxs({version:e,date:t,isLatest:n,isDeleted:r}){return o.jsxs(xWt,{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?mr(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":dnt.latest,children:o.jsx(yt,{variant:"blue",size:"sm",icon:o.jsx(lS,{})})}),r&&o.jsx("span",{className:"inline-flex",role:"img","aria-label":dnt.deleted,children:o.jsx(yt,{variant:"red",size:"sm",icon:o.jsx(B0e,{})})})]})]})}const Ap=Object.assign(Ixs,{Header:wxs,HeaderCol:Sxs,Items:Oxs,Scroller:Cxs,Row:Axs,RowButton:Rxs,Message:Txs,NextPageLoading:jxs,Pagination:Nxs,Cell:xWt,TextCell:Mxs,StatusCell:$xs,VersionCell:Dxs,IdCell:kxs,DateCell:xxs,LinkCell:Exs,LabelCell:_xs}),Lxs=[{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"}],H9={added:{badgeVariant:"blue",borderColor:"border-blue-900",icon:o.jsx(Fr,{}),tooltip:"Added in this version"},changed:{badgeVariant:"yellow",borderColor:"border-yellow-900",icon:o.jsx(Qen,{}),tooltip:"Changed in this version"},same:{badgeVariant:"green",borderColor:"border-green-900",icon:o.jsx(Sut,{}),tooltip:"Same in both versions"}};function ioe({red:e=!1,tooltip:t}){return o.jsxs(gn,{children:[o.jsx(fn,{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(B0e,{className:K("text-neutral3/40 w-5 h-5 ",{"text-red-900":e})})}),o.jsx(hn,{children:t})]})}function ooe({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}=H9[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(yt,{variant:n,size:"xs",icon:r})})]})}function Fxs(e,t){return e&&t&&e.datasetVersion===t.datasetVersion?"same":e&&t&&e.datasetVersion!==t.datasetVersion?"changed":e?"added":"removed"}function fnt({otherVersionExists:e,status:t,isNewer:n}){if(!e&&n)return"added";if(t==="changed"&&n)return"changed"}function zxs({datasetId:e,versionA:t,versionB:n,allItems:r,itemsAMap:s,itemsBMap:a}){const{Link:i}=ln(),l=t>n;return o.jsx(Ap,{children:o.jsx(Ap.Scroller,{children:o.jsx(Ap.Items,{children:r.map(({id:c})=>{const u=s.get(c),d=a.get(c),f=Fxs(u,d),h=fnt({otherVersionExists:d!==void 0,status:f,isNewer:l}),p=fnt({otherVersionExists:u!==void 0,status:f,isNewer:!l});return o.jsxs(Ap.Row,{columns:Lxs,children:[o.jsx(Ap.IdCell,{id:c,isShortened:!1}),f!=="same"?o.jsxs(o.Fragment,{children:[u?.datasetVersion?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:h?H9[h].tooltip:void 0,children:o.jsx(ooe,{variant:h,version:u.datasetVersion})}):o.jsx(Ap.Cell,{className:"flex items-center justify-center",children:o.jsx(ioe,{red:l,tooltip:l?"Deleted in this version":"Not present in this version"})}),d?.datasetVersion?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"gap-2",tooltip:p?H9[p].tooltip:void 0,children:o.jsx(ooe,{variant:p,version:d.datasetVersion})}):o.jsx(Ap.Cell,{className:"flex items-center justify-center",children:o.jsx(ioe,{red:!l,tooltip:l?"Not present in this version":"Deleted in this version"})})]}):o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}`,className:"col-span-2 gap-2",tooltip:H9.same.tooltip,children:o.jsx(ooe,{variant:"same",version:d?.datasetVersion})}),f==="changed"?o.jsx(Ap.LinkCell,{LinkComponent:i,href:`/datasets/${e}/items/${c}/versions?version=${u?.datasetVersion}&compare=${d?.datasetVersion}`,children:"Compare"}):o.jsx(Ap.Cell,{children:o.jsx(ioe,{tooltip:"Comparing is available only for changed items"})})]},c)})})})})}function Bxs(){const e=Kr(),[t,n]=g.useState(""),[r,s]=g.useState("all"),[a,i]=g.useState("all"),{data:l=[],isLoading:c,error:u,isFetchingNextPage:d,hasNextPage:f,setEndOfListElement:h}=m$n(),{data:p,isLoading:m,error:v}=QH(),y=g.useMemo(()=>p?.experiments??[],[p?.experiments]),b=g.useMemo(()=>Xys(l),[l]),x=c||m,w=u||v,k=()=>{e("/datasets/new")};if(w&&hs(w))return o.jsx(Zn,{children:o.jsx(Es,{})});if(w&&ps(w))return o.jsx(Zn,{children:o.jsx(Os,{resource:"datasets"})});if(w)return o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load datasets",message:w.message})});if(l.length===0&&!x)return o.jsx(Zn,{children:o.jsx(Jys,{onCreateClick:k})});const O=r!=="all"||a!=="all"||t!=="",_=()=>{n(""),s("all"),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(sbs,{search:t,onSearchChange:n,experimentFilter:r,onExperimentFilterChange:s,tagFilter:a,onTagFilterChange:i,tagOptions:b,onReset:_,hasActiveFilters:O,onCreateClick:k})}),o.jsx(Yys,{datasets:l,experiments:y,isLoading:x,search:t,experimentFilter:r,tagFilter:a,isFetchingNextPage:d,hasNextPage:f,setEndOfListElement:h})]})}function h8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function Uxs(){const{datasetId:e}=ur(),t=Kr(),[n,r]=ya(),{activeVersion:s,handleVersionChange:a}=qRe(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}=Yg(e),{data:b=[],isLoading:x}=IC(e,void 0,s),w=!x&&b.length===0;if(y)return null;if(v&&hs(v))return o.jsx(h8,{children:o.jsx(Es,{})});if(v&&ps(v))return o.jsx(h8,{children:o.jsx(Os,{resource:"datasets"})});if(v&&h0(v)||!y&&!v&&!m)return o.jsx(h8,{children:o.jsx(pr,{iconSlot:o.jsx($g,{}),titleSlot:"Dataset not found",descriptionSlot:`No dataset with id "${e}".`,actionSlot:o.jsxs(oe,{as:yo,to:"/datasets",children:[o.jsx(wu,{}),"Back to Datasets"]})})});if(v)return o.jsx(h8,{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(rxs,{datasetId:e,items:b,isLoadingItems:x,children:[o.jsxs("div",{className:"h-full",children:[o.jsx(Lt,{height:"full",className:"grid-rows-[1fr] p-0",children:o.jsx(Lt.MainArea,{children:o.jsx(sxs,{datasetId:e,onAddItemClick:()=>u(!0),belowToolbarSlot:o.jsx(axs,{datasetId:e}),leftSlot:o.jsx("span",{className:"text-ui-sm text-neutral3 mr-3 whitespace-nowrap",children:m?.createdAt?`Created ${mr(new Date(m.createdAt),"MMM d")}`:""}),rightSlot:o.jsxs(ts,{children:[o.jsxs(oe,{as:yo,to:`/experiments?dataset=${e}`,children:[o.jsx(W0e,{}),"View experiments"]}),o.jsx(hWt,{datasetId:e,value:s,onValueChange:a,currentVersion:m?.version,className:"w-36"}),w?o.jsxs(gn,{children:[o.jsx(fn,{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.jsxs(oe,{variant:"primary",children:[o.jsx(Pc,{}),"Run Experiment"]})})})}),o.jsx(hn,{children:"Add items to the dataset before running an experiment"})]}):o.jsxs(oe,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Pc,{}),"Run Experiment"]}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(oe,{size:"lg","aria-label":"Dataset actions menu",children:o.jsx(XS,{})})}),o.jsxs(ot.Content,{align:"end",className:"w-48",children:[o.jsxs(ot.Item,{onSelect:()=>{t(`/datasets/${e}/edit`)},children:[o.jsx(Qh,{})," Edit Dataset"]}),o.jsxs(ot.Item,{onSelect:()=>p(!0),children:[o.jsx(zd,{})," Duplicate Dataset"]}),o.jsxs(ot.Item,{onSelect:()=>f(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(ll,{})," Delete Dataset"]})]})]})]})})})}),o.jsx(Fg,{})]}),o.jsx(mY,{initialDatasetId:e,initialDatasetVersion:s??void 0,open:i,onOpenChange:l,onSuccess:k},`${e}:${s??"latest"}`),o.jsx(oxs,{datasetId:e,open:c,onOpenChange:u}),m&&o.jsx(bbs,{open:h,onOpenChange:p,sourceDatasetId:m.id,sourceDatasetName:m.name,sourceDatasetDescription:m.description,sourceDatasetTargetType:m.targetType}),m&&o.jsx(kbs,{open:d,onOpenChange:f,datasetId:m.id,datasetName:m.name,onSuccess:O})]})}function loe({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function qxs(){const{datasetId:e}=ur(),t=Kr(),{data:n,error:r,isLoading:s}=Yg(e),a=()=>{t(`/datasets/${e}`)};return s?null:r&&hs(r)?o.jsx(loe,{children:o.jsx(Es,{})}):r&&ps(r)?o.jsx(loe,{children:o.jsx(Os,{resource:"datasets"})}):r||!n?o.jsx(loe,{children:o.jsx(Fs,{title:"Failed to load dataset",message:r instanceof Error?r.message:"An unexpected error occurred. Please try again."})}):o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Nh,{className:"mb-6 p-0",children:o.jsxs(Nh.Column,{children:[o.jsxs(Nh.Title,{children:[o.jsx($g,{})," Edit dataset"]}),o.jsx(Nh.Description,{children:n.name})]})}),o.jsx(Ic,{className:"p-6",children:o.jsx(Sbs,{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 gY({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 Vxs(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 Hxs({datasetId:e,item:t,items:n,onItemChange:r,onClose:s}){const{Link:a}=ln(),{updateItem:i,deleteItem:l}=Fa(),[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),[_,E]=g.useState(t.scorerIds??[]),[T,N]=g.useState(""),[I,A]=g.useState(null),[R,L]=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),E(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),L(!1),A(null))},[t?.id]);const M=n.findIndex(z=>z.id===t.id),B=M>0?()=>r(n[M-1].id):void 0,V=M>=0&&M<n.length-1?()=>r(n[M+1].id):void 0,q=async()=>{let z;try{z=JSON.parse(d)}catch{Ve.error("Input must be valid JSON");return}let $;if(h.trim())try{$=JSON.parse(h)}catch{Ve.error("Ground Truth must be valid JSON");return}let U;if(m.trim())try{U=JSON.parse(m)}catch{Ve.error("Metadata must be valid JSON");return}let W=null;if(y.trim())try{W=JSON.parse(y)}catch{Ve.error("Expected Trajectory must be valid JSON");return}let Y;if(x.trim())try{const J=JSON.parse(x);if(!Array.isArray(J)){Ve.error("Tool Mocks must be a JSON array");return}Y=J}catch{Ve.error("Tool Mocks must be valid JSON");return}else Y=[];let te;if(T.trim())try{te=JSON.parse(T)}catch{Ve.error("Request Context must be valid JSON");return}let ee;k?ee=_:t.scorerIds!==void 0&&(ee=null);try{const J=await i.mutateAsync({datasetId:e,itemId:t.id,input:z,groundTruth:$,metadata:U,expectedTrajectory:W,toolMocks:Y,scorerIds:ee,requestContext:te});Ve.success("Item updated successfully"),O(J.scorerIds!==void 0),E(J.scorerIds??[]),u(!1),A(null)}catch(J){const re=Vxs(J);re?A(re):Ve.error(`Failed to update item: ${J instanceof Error?J.message:"Unknown error"}`)}},F=()=>{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),E(t.scorerIds??[]),N(t.requestContext?JSON.stringify(t.requestContext,null,2):""),u(!1),A(null)},H=z=>{f(z),I?.field==="input"&&A(null)},D=z=>{p(z),I?.field==="groundTruth"&&A(null)},G=async()=>{try{await l.mutateAsync({datasetId:e,itemId:t.id}),Ve.success("Item deleted successfully"),L(!1),s()}catch(z){Ve.error(`Failed to delete item: ${z instanceof Error?z.message:"Unknown error"}`)}};return o.jsxs(o.Fragment,{children:[o.jsxs(wn,{children:[o.jsxs(wn.Header,{children:[o.jsxs(wn.Heading,{children:["Item ",o.jsxs("b",{children:["# ",t.id.length>12?`${t.id.slice(0,12)}…`:t.id]})]}),o.jsxs(ts,{className:"ml-auto shrink-0",children:[o.jsx(wn.NextPrevNav,{onPrevious:B,onNext:V,previousLabel:"Previous item",nextLabel:"Next item"}),!c&&o.jsxs(o.Fragment,{children:[o.jsx(oe,{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(X0e,{})}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(oe,{size:"md","aria-label":"Actions menu",children:o.jsx(XS,{})})}),o.jsxs(ot.Content,{align:"end",className:"w-48",children:[o.jsxs(ot.Item,{onSelect:()=>u(!0),children:[o.jsx(Qh,{}),"Edit"]}),o.jsxs(ot.Item,{onSelect:()=>L(!0),className:"text-red-500 focus:text-red-400",children:[o.jsx(ll,{}),"Delete Item"]})]})]})]}),o.jsx(wn.CloseButton,{onClick:s,tooltip:"Close detail panel"})]})]}),o.jsx(wn.Content,{children:c?o.jsx(cxs,{inputValue:d,setInputValue:H,groundTruthValue:h,setGroundTruthValue:D,metadataValue:m,setMetadataValue:v,trajectoryValue:y,setTrajectoryValue:b,toolMocksValue:x,setToolMocksValue:w,scorerOverrideEnabled:k,setScorerOverrideEnabled:O,selectedScorerIds:_,setSelectedScorerIds:E,requestContextValue:T,setRequestContextValue:N,validationErrors:I,onSave:q,onCancel:F,isSaving:i.isPending}):o.jsx(O0e,{item:t})})]}),o.jsx(Dt,{open:R,onOpenChange:L,children:o.jsxs(Dt.Content,{children:[o.jsxs(Dt.Header,{children:[o.jsx(Dt.Title,{children:"Delete Item"}),o.jsx(Dt.Description,{children:"Are you sure you want to delete this item? This action cannot be undone."})]}),o.jsxs(Dt.Footer,{children:[o.jsx(Dt.Cancel,{children:"Cancel"}),o.jsx(Dt.Action,{onClick:G,children:l.isPending?"Deleting...":"Yes, Delete"})]})]})})]})}function Wxs(){const{itemId:e}=ur(),{datasetId:t,items:n,isLoadingItems:r,openItem:s,close:a}=gWt(),i=g.useMemo(()=>n.find(d=>d.id===e)??null,[n,e]),{data:l,isLoading:c}=CVt(i?"":t,!i&&e?e:""),u=i??l??null;return e?o.jsx(gY,{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(Hxs,{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(Vt,{})})}):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(pr,{iconSlot:o.jsx($g,{}),titleSlot:"Item not found",descriptionSlot:`No loaded item "${e}".`,actionSlot:o.jsx(oe,{onClick:a,children:"Close"})})})})}):null}function hnt(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 pnt(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]})," · ",mr(r,"MMM d, HH:mm")]}),n.isLatest?o.jsx(yt,{variant:"blue",size:"xs",className:"ml-auto",children:"Latest"}):null]}),disabled:t?.has(n.datasetVersion)??!1}})}function mnt(e){const t=Number(e);return e!=null&&Number.isFinite(t)&&t>0?t:null}function Zxs(){const{datasetId:e,itemId:t}=ur(),[n,r]=ya(),s=mnt(n.get("version")),a=mnt(n.get("compare")),i=n.get("view")==="diff",{data:l,error:c}=Yg(e??""),{data:u,isLoading:d}=Rys(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}=Pys(e??"",t??"",p??0,l?.version),y=(_,E)=>r(T=>{const N=new URLSearchParams(T);return E==null?N.delete(_):N.set(_,String(E)),N},{replace:!0});if(c&&hs(c))return o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Es,{})})});if(c&&ps(c))return o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"datasets"})})});if(!e||!t)return o.jsx(ia,{children:o.jsx(Ox,{children:o.jsx("div",{className:"text-neutral4 py-8 text-center",children:o.jsx("p",{children:"Item not found."})})})});const b=!!(f&&m),x=i&&b,w=f?hnt(f,e):null,k=m?hnt(m,e):null,O=(f?.datasetVersion??0)<(m?.datasetVersion??0);return o.jsxs(ia,{children:[o.jsx(l_,{owner:"dataset-item-versions",children:b&&o.jsx(oe,{variant:"outline",onClick:()=>y("view",i?null:"diff"),children:i?o.jsxs(o.Fragment,{children:[o.jsx(V0e,{})," Default View"]}):o.jsxs(o.Fragment,{children:[o.jsx(gJt,{})," Diff View"]})})}),o.jsx(Lt,{height:"full",className:"grid-rows-[minmax(0,1fr)]",children:o.jsxs("div",{className:"grid min-h-0 grid-cols-1 gap-6 md:grid-cols-2",children:[o.jsxs(Ic,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(tS,{children:o.jsx(gnt,{name:"version",value:h!=null?String(h):"",options:pnt(u??[],p!=null?new Set([p]):void 0),onValueChange:_=>y("version",Number(_))})}),o.jsx($f,{className:"grid content-start gap-8 overflow-y-auto",children:d?o.jsx("div",{className:"text-neutral4 text-sm",children:"Loading..."}):w?o.jsx(O0e,{item:w,diff:x&&k?{against:k,side:O?"a":"b"}:void 0}):o.jsx("div",{className:"text-neutral4 text-sm",children:"Item data not available"})})]}),o.jsxs(Ic,{className:"grid min-h-0 grid-rows-[auto_1fr] overflow-hidden",children:[o.jsx(tS,{children:o.jsx(gnt,{name:"compare",value:p!=null?String(p):"",placeholder:"Select a version to compare",options:pnt(u??[],h!=null?new Set([h]):void 0),onValueChange:_=>y("compare",Number(_))})}),o.jsx($f,{className:"grid content-start gap-8 overflow-y-auto",children:p==null?o.jsx(pr,{className:"h-full",iconSlot:o.jsx(hpe,{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-sm",children:"Loading..."}):k?o.jsx(O0e,{item:k,diff:x&&w?{against:w,side:O?"b":"a"}:void 0}):o.jsxs("div",{className:"text-neutral4 text-sm",children:["Version ",p," not found"]})})]})]})})]})}function gnt({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(X0e,{className:"size-4 opacity-50"}),o.jsxs(ka,{name:e,value:t,onValueChange:s,children:[o.jsx(Ca,{"aria-label":e==="compare"?"Compare version":"Version",className:"w-full",children:o.jsx(Oa,{placeholder:r,className:"flex-1"})}),o.jsx(_a,{children:n.map(a=>o.jsx(jr,{value:a.value,disabled:a.disabled,children:a.label},a.value))})]})]})}function Gxs(){const{datasetId:e}=ur(),[t]=ya(),n=t.get("ids")?.split(",").map(Number).filter(m=>!isNaN(m)&&m>0)??[],r=Kr(),{data:s,error:a}=Yg(e??""),i=IC(e??"",void 0,n[0]??null),l=IC(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&&hs(a))return o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Es,{})})});if(a&&ps(a))return o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"datasets"})})});if(!e||n.length<2)return o.jsx(ia,{children:o.jsx(Ox,{children:o.jsx("div",{className:"text-neutral4 py-8 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(ia,{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-6",children:[o.jsxs(Nh,{children:[o.jsxs(Nh.Column,{children:[o.jsxs(Nh.Title,{children:[o.jsx(Ctn,{})," Compare Dataset Versions"]}),o.jsx(Nh.Description,{children:o.jsxs(Ad,{children:[o.jsx(X0e,{})," Comparing ",n.length," versions of"," ",s?.name||e?.slice(0,8)]})})]}),o.jsx(Nh.Column,{children:o.jsxs(oe,{as:yo,to:`/datasets/${e}`,children:[o.jsx(wu,{}),"Back to Dataset"]})})]}),o.jsx(bM,{children:o.jsxs(el,{children:[o.jsx(bxs,{datasetId:e,versionA:String(n[0]),versionB:String(n[1]),onVersionChange:p}),o.jsx(zxs,{datasetId:e,versionA:n[0],versionB:n[1],allItems:d,itemsAMap:f,itemsBMap:h})]})})]})})})}const Qxs=["agent","workflow","scorer","processor"],Yxs=new Set(Qxs);function Kxs(e){return typeof e=="string"&&Yxs.has(e)}function Xxs(){const e=Kr(),[t]=ya(),n=t.get("targetType"),r=Kxs(n)?n:void 0,s=t.get("targetIds"),a=r&&s?s.split(",").map(i=>i.trim()).filter(Boolean):void 0;return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsxs("div",{className:"w-full max-w-2xl overflow-y-auto px-6 py-8",children:[o.jsx(Nh,{className:"mb-6 p-0",children:o.jsxs(Nh.Column,{children:[o.jsxs(Nh.Title,{children:[o.jsx($g,{})," Create new dataset"]}),o.jsx(Nh.Description,{children:"Datasets group test cases used to evaluate your agents and workflows."})]})}),o.jsx(Ic,{className:"p-6",children:o.jsx(gbs,{targetType:r,targetIds:a,onSuccess:i=>{e(`/datasets/${i}`)},onCancel:()=>{e(-1)}})})]})})]})}function C0e({children:e,className:t}){return o.jsx("div",{className:K("flex flex-wrap gap-8",t),children:e})}function Jxs(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 e0s({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=Jxs(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 wWt({open:e,onOpenChange:t,experimentId:n,experimentName:r,onSuccess:s}){const{deleteExperiment:a}=Fa(),i=async()=>{try{await a.mutateAsync(n),Ve.success("Experiment deleted successfully"),t(!1),s?.()}catch(l){Ve.error(`Failed to delete experiment: ${l instanceof Error?l.message:"Unknown error"}`)}};return o.jsx(Dt,{open:e,onOpenChange:t,children:o.jsxs(Dt.Content,{children:[o.jsxs(Dt.Header,{children:[o.jsx(Dt.Title,{children:"Delete Experiment"}),o.jsxs(Dt.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(Dt.Footer,{children:[o.jsx(oe,{variant:"primary",size:"lg",onClick:i,disabled:a.isPending,children:a.isPending?"Deleting...":"Delete"}),o.jsx(Dt.Cancel,{children:"Cancel"})]})]})})}function SWt(e){const t=b0(e.id)??e.id;return e.name||`Experiment #${t}`}const t0s=60;function n0s({experiment:e}){return o.jsx("span",{className:"text-neutral4 block min-w-0 truncate text-left",children:SWt(e)})}function r0s({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<=t0s?n:o.jsxs(gn,{children:[o.jsx(fn,{asChild:!0,children:n}),o.jsx(hn,{children:t})]})}const vY=()=>{const{requestContext:e}=vs(),t=Ze();return mt({queryKey:["processors"],queryFn:()=>t.listProcessors(e)})},kWt=(e,t)=>{const n=Ze(),{requestContext:r}=vs();return mt({queryKey:["processor",e],queryFn:()=>n.getProcessor(e).details(r),enabled:!!e})},s0s=()=>{const e=Ze(),{requestContext:t}=vs();return bn({mutationFn:async({processorId:n,phase:r,messages:s,agentId:a})=>e.getProcessor(n).execute({phase:r,messages:s,agentId:a,requestContext:t})})};function OWt(){const{data:e}=zm(),{data:t}=Yy(),{data:n}=up(),{data:r}=vY();return{agents:e,workflows:t,scorers:n,processors:r}}const CWt={agent:co,workflow:Su,scorer:M_,processor:aV},_Wt={agent:"Agent",workflow:"Workflow",scorer:"Scorer",processor:"Processor"},a0s="External (caller-run)";function EWt(e,{agents:t,workflows:n,scorers:r,processors:s}){const{targetType:a,targetId:i}=e;if(!i)return a0s;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 i0s({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(ve.Cell,{children:o.jsx(n0s,{experiment:e})}),o.jsx(ve.Cell,{children:o.jsx(r0s,{experiment:e})}),t!==void 0&&o.jsx(ve.TextCell,{children:t}),o.jsx(ve.Cell,{children:o.jsx(o0s,{experiment:e})}),o.jsx(ve.Cell,{children:o.jsx(yt,{variant:OVt[r]??"neutral",indicator:"dot",children:qT[r]??r})}),o.jsx(ve.TextCell,{className:"text-center",children:i}),o.jsx(ve.TextCell,{className:"text-center",children:s}),o.jsx(ve.TextCell,{className:"text-center",children:o.jsx("span",{className:a>0?"text-accent2":"",children:a})}),o.jsx(ve.Cell,{className:"text-center",children:o.jsx(l0s,{review:n})}),o.jsx(ve.TextCell,{children:dfs(e.createdAt)})]})}function o0s({experiment:e}){const t=OWt(),n=EWt(e,t),r=e.targetId?e.targetType:null,s=r?CWt[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":_Wt[r],children:o.jsx(s,{})}),o.jsx("span",{className:r?"truncate":"text-neutral2 truncate",children:n})]})}function l0s({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(yt,{size:"xs",variant:"yellow",children:[e.needsReview," pending"]}):o.jsxs(yt,{size:"xs",variant:"green",children:[e.complete,"/",t," reviewed"]})}const TWt=`${ofs} ${lfs} ${cfs} ${ufs}`,vnt=`${TWt} auto`,c0s=[{label:Cv.experiment},{label:Cv.description},{label:Cv.dataset},{label:Cv.target},{label:Cv.status},{label:Cv.items,className:"text-center"},{label:Cv.succeeded,className:"text-center"},{label:Cv.failed,className:"text-center"},{label:Cv.review,className:"text-center"},{label:Cv.date}];function u0s({experiments:e,datasets:t,reviewByExperiment:n,isLoading:r,search:s="",statusFilter:a="all",datasetFilter:i="all",selection:l}){const c=l!==void 0,{paths:u,Link:d}=ln(),f=g.useMemo(()=>{const k=new Map;return t?.forEach(O=>k.set(O.id,O.name)),k},[t]),h=g.useMemo(()=>[...e].sort((k,O)=>{const _=k.createdAt?new Date(k.createdAt).getTime():0;return(O.createdAt?new Date(O.createdAt).getTime():0)-_}),[e]),p=g.useMemo(()=>{const k=s.toLowerCase();return h.filter(O=>{const _=O.datasetId?f.get(O.datasetId)??"":"",E=!k||O.id.toLowerCase().includes(k)||(O.name??"").toLowerCase().includes(k)||_.toLowerCase().includes(k)||(O.targetId??"").toLowerCase().includes(k),T=a==="all"||O.status===a,N=i==="all"||O.datasetId===i;return E&&T&&N})},[h,s,f,a,i]),{containerRef:m,getRowProps:v}=ol({count:p.length}),[y,b]=g.useState(null);if(r)return o.jsx(Do,{columns:vnt});const x=c?`auto ${TWt}`:vnt,w=c0s.map(k=>o.jsx(ve.TopCell,{className:k.className,children:k.label},k.label));return o.jsxs(ve,{columns:x,scrollRef:m,children:[o.jsx(ve.Top,{hasLeadingCell:c,children:c?o.jsxs(o.Fragment,{children:[o.jsx(ve.TopCell,{children:" "}),o.jsx(ve.TopCells,{colStart:2,children:w})]}):o.jsxs(o.Fragment,{children:[w,o.jsx(ve.TopCell,{"aria-hidden":!0,children:null})]})}),p.map((k,O)=>{const _=k.datasetId?f.get(k.datasetId)??b0(k.datasetId)??k.datasetId:"—",E=o.jsx(i0s,{experiment:k,datasetName:_,review:n?.get(k.id)});if(!l)return o.jsxs(ve.RowWrapper,{children:[o.jsx(ve.RowLink,{colEnd:-2,to:u.experimentLink(k.id),LinkComponent:d,...v(O),children:E}),o.jsx(ve.ActionsCell,{className:"pl-2",children:o.jsx(oe,{type:"button",variant:"ghost",size:"icon-xs",tooltip:"Delete experiment","aria-label":`Delete experiment ${k.name??k.id}`,onClick:I=>{I.stopPropagation(),b(k)},children:o.jsx(ll,{className:"size-4"})})})]},k.id);const T=l.selectedExperimentIds.includes(k.id),N=()=>l.onToggleSelection(k.id);return o.jsxs(ve.RowWrapper,{children:[o.jsx(ve.SelectCell,{checked:T,onToggle:N,"aria-label":`Select experiment ${k.id}`}),o.jsx(ve.RowButton,{colStart:2,featured:T,onClick:N,...v(O),children:E})]},k.id)}),y&&o.jsx(wWt,{open:!0,onOpenChange:k=>{k||b(null)},experimentId:y.id,experimentName:y.name??void 0})]})}const d0s=[{value:"all",label:"All statuses"},{value:"completed",label:"Completed"},{value:"running",label:"Running"},{value:"failed",label:"Failed"},{value:"pending",label:"Pending"}];function f0s(e){return[{value:"all",label:"All datasets"},...(e??[]).map(t=>({value:t.id,label:t.name}))]}const p8={completed:G7.neutral3,running:"#facc15",pending:"#fb923c",failed:"#f87171"},h0s=[{label:"Completed",color:p8.completed},{label:"Running",color:p8.running},{label:"Pending",color:p8.pending},{label:"Failed",color:p8.failed}];function p0s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Experiments by Dataset",description:"Experiment status breakdown per dataset."}),i&&o.jsx(qt.Summary,{value:String(e?.length??0),label:"Total experiments"})]}),n?o.jsx(qt.Loading,{}):r?o.jsx(qt.Error,{message:"Failed to load experiments data"}):o.jsx(qt.Content,{children:i?o.jsx(nI,{data:s,segments:h0s,maxVal:a,fmt:l=>String(l)}):o.jsx(qt.NoData,{message:"No experiments have been run yet"})})]})}const m0s=({onRunExperiment:e})=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),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.jsxs(oe,{variant:"primary",onClick:e,children:[o.jsx(Pc,{}),"Run Experiment"]}),o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/evals/experiments",target:"_blank",rel:"noopener noreferrer",children:["Experiments Documentation ",o.jsx(Ds,{})]})]})})});function g0s({search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:s,onDatasetFilterChange:a,datasetOptions:i,onReset:l,hasActiveFilters:c,onRunClick:u,runTooltip:d="Run an experiment",onCompareClick:f,selection:h}){const p=h?.selectedCount===2&&!h.compareDisabledReason;return o.jsxs("div",{className:"flex min-h-9 flex-wrap items-center gap-2",children:[o.jsx("div",{className:"max-w-120 min-w-48 flex-1",children:o.jsx(Uc,{label:"Search experiments",placeholder:"Filter by experiment, dataset, or target",value:e,onSearch:t})}),o.jsxs(ts,{children:[o.jsx(Kd,{label:"Status",labelIsHidden:!0,name:"filter-status",options:[...d0s],value:n,onValueChange:r,className:"whitespace-nowrap"}),o.jsx(Kd,{label:"Dataset",labelIsHidden:!0,name:"filter-dataset",options:i,value:s,onValueChange:a,className:"whitespace-nowrap"}),l&&c&&o.jsxs(oe,{onClick:l,size:"sm",variant:"default",children:[o.jsx(or,{className:"size-3"})," Reset"]})]}),h?o.jsxs(ts,{className:"ml-auto shrink-0 whitespace-nowrap",children:[o.jsxs(Dh,{className:"gap-2",children:[o.jsxs(yt,{size:"sm",variant:h.selectedCount<2?"red":"green",children:[h.selectedCount," / 2"]}),"selected",h.compareDisabledReason&&o.jsxs("span",{className:"text-accent2",children:["· ",h.compareDisabledReason]})]}),o.jsxs(oe,{variant:"primary",disabled:!p,onClick:h.onExecuteCompare,children:[o.jsx(hpe,{}),"Compare Experiments"]}),o.jsx(oe,{onClick:h.onCancelSelection,children:"Cancel"})]}):o.jsxs(ts,{className:"ml-auto shrink-0",children:[f&&o.jsxs(oe,{onClick:f,tooltip:"Select two experiments of the same dataset to compare",children:[o.jsx(hpe,{}),"Compare"]}),u&&o.jsxs(oe,{onClick:u,tooltip:d,variant:"primary",children:[o.jsx(Pc,{}),"Run Experiment"]})]})]})}const v0s={present:!1,output:null,metadata:null,comment:null,error:null,startedAt:null,completedAt:null,scores:[]},ynt=e=>e?e instanceof Date?e.toISOString():e:null,bnt=e=>{const t=new Map;for(const n of e??[])t.set(n.itemId,n);return t},xnt=(e,t,n)=>{if(!e)return v0s;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:ynt(t?.startedAt),completedAt:ynt(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))}},y0s=({comparison:e,baselineId:t,contenderId:n,baselineResults:r,contenderResults:s,baselineScores:a,contenderScores:i})=>{if(!e)return[];const l=bnt(r),c=bnt(s);return e.items.map(u=>{const d=xnt(u.results[t],l.get(u.itemId),a?.[u.itemId]),f=xnt(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 Bk({title:e,actions:t,tone:n="default",defaultOpen:r=!0,children:s}){return o.jsxs(lc,{defaultOpen:r,className:"grid gap-2",children:[o.jsxs("div",{className:"flex min-h-6 items-center justify-between gap-2",children:[o.jsxs(Bl,{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(qr,{}),e]}),t]}),o.jsx(Ul,{role:"region","aria-label":e,children:s})]})}function wnt({label:e,value:t}){return t==null?null:o.jsx(Bk,{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 jWt({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-sm",t),children:[o.jsx("span",{className:"inline-block w-3",children:e>0?"+":e<0?"-":""}),Math.abs(e).toFixed(2),e>0?o.jsx(fut,{className:"size-3.5"}):e<0?o.jsx(GYt,{className:"size-3.5"}):null]})}function NWt({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 flex min-w-0 items-center gap-1.5 text-sm font-medium hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0",children:[o.jsx(M_,{}),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 font-mono text-sm",children:t!=null?t.toFixed(2):"-"}),n!=null&&o.jsx(jWt,{delta:n})]})]}),r&&o.jsx("p",{className:"text-neutral3 text-sm",children:r})]})}function Snt(e){return e==null?"-":typeof e=="string"?e:JSON.stringify(e,null,2)}function b0s(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 x0s="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 knt({side:e,row:t,showDeltas:n,isLoading:r}){const s=t[e],a=b0s(s);if(r)return o.jsx("div",{className:"flex h-32 items-center justify-center",children:o.jsx(Vt,{})});if(!s.present)return o.jsx("p",{className:"text-neutral3 py-8 text-center text-sm",children:"Not present in this experiment"});const i=Snt(s.output);return o.jsxs("div",{className:"grid content-start gap-5",children:[a&&o.jsxs(gn,{children:[o.jsx(fn,{render:o.jsxs("p",{className:"text-neutral3 flex items-center justify-end gap-1.5 text-sm [&>svg]:size-3.5",children:[o.jsx(lS,{}),a]})}),o.jsx(hn,{children:"Run duration"})]}),s.error?o.jsx(Bk,{title:"Error",tone:"negative",actions:o.jsx(Da,{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(Bk,{title:"Output",actions:o.jsx(Da,{content:i}),children:o.jsx("pre",{className:x0s,children:i})}),s.scores.length>0&&o.jsx(Bk,{title:"Scores",children:o.jsx("div",{className:"grid gap-2",children:s.scores.map(l=>o.jsx(NWt,{scorerId:l.scorerId,value:l.value,delta:n?t.deltas[l.scorerId]:null,reason:l.reason},l.scorerId))})}),s.comment&&o.jsx(Bk,{title:"Comment",defaultOpen:!1,children:o.jsx("p",{className:"text-neutral3 text-sm",children:s.comment})}),s.metadata&&Object.keys(s.metadata).length>0&&o.jsx(Bk,{title:"Metadata",defaultOpen:!1,children:o.jsx("dl",{className:"grid gap-1",children:Object.entries(s.metadata).map(([l,c])=>o.jsxs("div",{className:"flex items-start justify-between gap-4 text-sm",children:[o.jsx("dt",{className:"text-neutral3",children:l}),o.jsx("dd",{className:"text-neutral5 font-mono break-all",children:Snt(c)})]},l))})})]})}const w0s={baseline:"Baseline",contender:"Contender"},S0s={baseline:"purple",contender:"blue"},k0s="flex min-w-0 items-center gap-1.5 hover:underline [&>svg]:size-3.5 [&>svg]:shrink-0";function Ont({side:e,experiment:t,summary:n,showDeltas:r,versionMismatch:s}){const{Link:a,paths:i}=ln(),l=w0s[e],c=t?b0(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(yt,{variant:S0s[e],size:"xs",children:l}),t&&o.jsx(oe,{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(Ad,{children:[o.jsx(l3,{})," ",c]}),t.targetType==="agent"&&t.targetId?o.jsxs(a,{href:i.agentLink(t.targetId),className:k0s,children:[o.jsx(co,{}),o.jsx("span",{className:"min-w-0 truncate",children:t.targetId})]}):o.jsxs(Ad,{children:[o.jsx(But,{})," ",t.targetId]}),o.jsx("span",{className:K(s&&"text-accent6"),children:o.jsxs(Ad,{children:[o.jsx(UV,{})," v",t.datasetVersion??"—",s&&" · different dataset version"]})}),u&&o.jsxs(Ad,{children:[o.jsx(Y9,{})," ",mr(u,"MMM d, yyyy HH:mm")]})]}),d.length>0&&o.jsx(Bk,{title:"Overall score",children:o.jsx("div",{className:"grid gap-2",children:d.map(({scorerId:f,average:h,delta:p})=>o.jsx(NWt,{scorerId:f,value:h,delta:r?p:null},f))})})]})}const QE="min-w-0 px-4 py-3";function O0s({datasetId:e,experimentIdA:t,experimentIdB:n}){const{Link:r,paths:s}=ln(),{data:a,isLoading:i,error:l}=$ys(e,t,n),{data:c}=XD(e,t),{data:u}=XD(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}=JD({datasetId:e,experimentId:f,experimentStatus:p?.status}),{data:b,isLoading:x}=JD({datasetId:e,experimentId:h,experimentStatus:m?.status}),{data:w}=Ny(f,p?.status),{data:k}=Ny(h,m?.status),O=g.useMemo(()=>y0s({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(T=>Object.keys(T.deltas)))].sort(),[O]),E=g.useMemo(()=>{const T=(A,R)=>{const L=O.map(M=>M[A].scores.find(B=>B.scorerId===R)?.value).filter(M=>M!=null);return L.length>0?L.reduce((M,B)=>M+B,0)/L.length:null},N=_.map(A=>({scorerId:A,average:T("baseline",A),delta:null})),I=_.map(A=>{const R=T("baseline",A),L=T("contender",A);return{scorerId:A,average:L,delta:R!=null&&L!=null?L-R:null}});return{baseline:N,contender:I}},[O,_]);return i?o.jsx("div",{className:"flex h-64 items-center justify-center",children:o.jsx(Vt,{})}):l?o.jsx(An,{variant:"warning",title:"Error loading comparison",children:o.jsx(An.Message,{children:l instanceof Error?l.message:"Unknown error"})}):!a||a.items.length===0?o.jsx("div",{className:"text-neutral4 py-8 text-center text-sm",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:`${QE} text-neutral3 text-ui-sm uppercase`,children:"Items"}),o.jsx("div",{role:"columnheader","aria-label":"Baseline",className:QE,children:o.jsx(Ont,{side:"baseline",experiment:p,summary:E.baseline,versionMismatch:d})}),o.jsx("div",{role:"columnheader","aria-label":"Contender",className:QE,children:o.jsx(Ont,{side:"contender",experiment:m,summary:E.contender,versionMismatch:d,showDeltas:!0})})]}),O.map(T=>{const N=Object.entries(T.deltas).filter(([,I])=>I!=null&&I!==0);return o.jsxs("div",{role:"row","aria-label":T.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:`${QE} grid content-start gap-1`,children:[o.jsx(r,{href:s.datasetItemLink(e,T.itemId),"aria-label":`Open item ${T.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",T.baseline.present&&T.contender.present?"text-neutral4":"text-neutral1"),children:o.jsx("span",{className:"min-w-0",children:T.itemId})}),N.length>0&&o.jsx("span",{className:"flex flex-wrap items-center gap-2",children:N.map(([I,A])=>o.jsx(jWt,{delta:A},I))}),o.jsxs("div",{className:"grid pt-3",children:[o.jsx(wnt,{label:"Input",value:T.input}),o.jsx(wnt,{label:"Ground truth",value:T.groundTruth})]})]}),o.jsx("div",{role:"cell","aria-label":"Baseline",className:QE,children:o.jsx(knt,{side:"baseline",row:T,isLoading:y})}),o.jsx("div",{role:"cell","aria-label":"Contender",className:QE,children:o.jsx(knt,{side:"contender",row:T,isLoading:x,showDeltas:!0})})]},T.itemId)})]})})}const C0s=100;function yY(e){const t=Ze(),n={perPage:C0s};return mt({queryKey:e?["dataset-experiments",e,n]:["experiments",n],queryFn:()=>e?t.listDatasetExperiments(e,n):t.listExperiments(n)})}const IWt=(e,t)=>{const n=Ze(),{data:r,isLoading:s}=yY(void 0),a=r?.experiments,i=t?a?.filter(c=>c.id===t):a,l=mt({queryKey:["review-items",e,t??"all",i?.map(c=>c.id)],queryFn:async()=>!i||i.length===0?[]:(await Promise.all(i.map(async u=>{if(!u.datasetId)return[];try{const{results:d}=await n.listDatasetExperimentResults(u.datasetId,u.id);return d.filter(f=>f.status===e).map(f=>({id:f.id,input:f.input,output:f.output,error:f.error,itemId:f.itemId,experimentId:f.experimentId,datasetId:u.datasetId??void 0,traceId:f.traceId??void 0,scores:f.scores?Object.fromEntries(f.scores.map(h=>[h.scorerId,h.score??0])):{},tags:f.tags??[],createdAt:f.createdAt,status:f.status,groundTruth:f.groundTruth,toolMockReport:f.toolMockReport}))}catch{return[]}}))).flat(),enabled:!!a,refetchOnWindowFocus:!1});return{...l,isLoading:l.isLoading||s}},_0s=({experimentId:e}={})=>IWt("needs-review",e),E0s=({experimentId:e}={})=>IWt("complete",e),T0s=[{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"}],coe="__untagged__",uoe="all",j0s=[{value:"review",label:"Review queue"},{value:"completed",label:"Completed"}];function N0s({datasetId:e,experimentId:t,featuredItemId:n,detailPanelVariant:r="inline",toolbarStart:s,toolbarEnd:a}){const i=Ze(),{paths:l}=ln(),{data:c}=Yg(e??""),{data:u,isLoading:d}=_0s({experimentId:t}),{data:f,isLoading:h}=E0s({experimentId:t}),{updateExperimentResult:p}=Fa(),[m,v]=g.useState(n??null);g.useEffect(()=>{n!==void 0&&v(n)},[n]);const[y,b]=g.useState(null),[x,w]=g.useState(new Set),[k,O]=g.useState(!1),[_,E]=g.useState(!1),[T,N]=g.useState(!1),[I,A]=g.useState(""),[R,L]=g.useState(""),[M,B]=g.useState(""),[V,q]=g.useState([]),[F,H]=g.useState(!1),D=g.useMemo(()=>u??[],[u]),G=g.useMemo(()=>{const ae=new Set;if(c?.tags)for(const ce of c.tags)ae.add(ce);for(const ce of D)for(const me of ce.tags)ae.add(me);return[...ae].sort()},[c,D]),z=g.useCallback(ae=>{!c||!e||(c.tags??[]).includes(ae)},[c,e]),$=g.useMemo(()=>y?y===coe?D.filter(ae=>ae.tags.length===0):D.filter(ae=>ae.tags.includes(y)):D,[D,y]),U=g.useMemo(()=>{const ae=new Map;let ce=0;for(const Se of D){Se.tags.length===0&&ce++;for(const Fe of Se.tags)ae.set(Fe,(ae.get(Fe)??0)+1)}const me=[...ae.entries()].sort((Se,Fe)=>Fe[1]-Se[1]).map(([Se])=>({value:Se,label:Se}));return[{value:uoe,label:"All tags"},...ce>0?[{value:coe,label:"Untagged"}]:[],...me]},[D]),W=!!y||k,Y=g.useCallback(()=>{b(null),O(!1),v(null)},[]),te=g.useCallback((ae,ce)=>{const me=D.find(Se=>Se.id===ae);me?.experimentId&&me?.datasetId&&p.mutate({datasetId:me.datasetId,experimentId:me.experimentId,resultId:me.id,tags:ce})},[D,p]),ee=g.useCallback(ae=>{const ce=D.find(me=>me.id===ae);w(me=>{const Se=new Set(me);return Se.delete(ae),Se}),m===ae&&v(null),ce?.experimentId&&ce?.datasetId&&p.mutate({datasetId:ce.datasetId,experimentId:ce.experimentId,resultId:ce.id,status:null})},[D,p,m]),J=g.useCallback(ae=>{const ce=D.find(me=>me.id===ae);w(me=>{const Se=new Set(me);return Se.delete(ae),Se}),m===ae&&v(null),ce?.experimentId&&ce?.datasetId&&p.mutate({datasetId:ce.datasetId,experimentId:ce.experimentId,resultId:ce.id,status:"complete"})},[D,p,m]),re=g.useMemo(()=>{const ae=k?f??[]:$;return!k||!y?ae:y===coe?ae.filter(ce=>ce.tags.length===0):ae.filter(ce=>ce.tags.includes(y))},[k,f,$,y]),le=k?h:!1,X=g.useMemo(()=>new Set(re.map(ae=>ae.id)),[re]),ne=g.useMemo(()=>[...x].filter(ae=>X.has(ae)).length,[x,X]),se=re.length>0&&ne===re.length,de=g.useCallback(ae=>{w(ce=>{const me=new Set(ce);return me.has(ae)?me.delete(ae):me.add(ae),me})},[]),ue=g.useCallback(()=>{w(se?new Set:new Set(re.map(ae=>ae.id)))},[se,re]),ye=g.useCallback(ae=>{for(const ce of x){const me=D.find(Se=>Se.id===ce);me&&!me.tags.includes(ae)&&te(ce,[...me.tags,ae])}},[D,x,te]),he=g.useCallback(ae=>{for(const ce of x){const me=D.find(Se=>Se.id===ce);me&&me.tags.includes(ae)&&te(ce,me.tags.filter(Se=>Se!==ae))}},[D,x,te]),xe=g.useCallback(()=>{for(const ae of x)J(ae);w(new Set)},[x,J]),Ne=g.useCallback(()=>{for(const ae of x)ee(ae);w(new Set)},[x,ee]),Me=g.useCallback(()=>{A(""),N(!0)},[]),Re=g.useCallback(async()=>{if(!(!R||!M)){E(!0),N(!1);try{const ae=D.filter(me=>x.has(me.id));if(ae.length===0){E(!1);return}const ce=await i.clusterFailures({modelId:`${R}/${M}`,items:ae.map(me=>({id:me.id,input:me.input,output:me.output??void 0,error:typeof me.error=="string"?me.error:me.error?String(me.error):void 0,scores:me.scores,existingTags:me.tags.length>0?me.tags:void 0})),availableTags:G.length>0?G:void 0,prompt:I||void 0});ce.proposedTags&&ce.proposedTags.length>0&&(q(ce.proposedTags.map(me=>({...me,accepted:!0}))),H(!0))}catch(ae){console.error("Analysis failed:",ae)}finally{E(!1)}}},[R,M,D,x,i,G,I]),Ae=g.useCallback(()=>{for(const ae of V){if(!ae.accepted)continue;const ce=D.find(me=>me.id===ae.itemId);if(ce){const me=[...new Set([...ce.tags,...ae.tags])];te(ce.id,me)}}H(!1)},[V,D,te]),Ie=g.useCallback(ae=>{v(ce=>ce===ae?null:ae)},[]),Pe=g.useMemo(()=>m?re.find(ae=>ae.id===m)??null:null,[m,re]),{data:Ce}=Ny(Pe?.experimentId??""),Ee=m?re.findIndex(ae=>ae.id===m):-1,ze=Ee>0?()=>v(re[Ee-1].id):void 0,Oe=Ee>=0&&Ee<re.length-1?()=>v(re[Ee+1].id):void 0,$e=!k&&x.size>0,tt=o.jsxs("div",{className:"flex flex-wrap items-center gap-2",children:[o.jsxs(ts,{children:[s,o.jsx(Kd,{label:"Status",labelIsHidden:!0,name:"filter-status",options:j0s,value:k?"completed":"review",onValueChange:ae=>{O(ae==="completed"),v(null)},className:"whitespace-nowrap"}),U.length>1&&o.jsx(Kd,{label:"Tags",labelIsHidden:!0,name:"filter-tags",options:U,value:y??uoe,onValueChange:ae=>b(ae===uoe?null:ae),className:"whitespace-nowrap"}),W&&o.jsxs(oe,{onClick:Y,size:"sm",variant:"default",children:[o.jsx(or,{className:"size-3"})," Reset"]})]}),($e||a)&&o.jsxs("div",{className:"ml-auto flex shrink-0 items-center gap-2",children:[a,$e&&o.jsxs(o.Fragment,{children:[o.jsx(BHt,{size:"md",selectedCount:x.size,vocabulary:G,onApplyTag:ye,onRemoveTag:he,onNewTag:ae=>ye(ae)}),o.jsxs(oe,{variant:"primary",onClick:xe,children:[o.jsx(uI,{}),"Mark as reviewed"]}),o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(oe,{variant:"outline",disabled:_,"aria-label":"More actions",children:_?o.jsx(Vt,{className:"h-4 w-4"}):o.jsx(wut,{})})}),o.jsxs(ot.Content,{align:"end",children:[o.jsxs(ot.Item,{onSelect:Me,children:[o.jsx(Je,{size:"sm",children:o.jsx(uS,{})}),"Analyze"]}),o.jsx(ot.Separator,{}),o.jsxs(ot.Item,{onSelect:Ne,children:[o.jsx(Je,{size:"sm",children:o.jsx(ll,{})}),"Remove from queue"]})]})]})]})]})]});if(d)return o.jsxs(o.Fragment,{children:[o.jsx(Lt.TopArea,{children:tt}),o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(Vt,{className:"h-6 w-6"})})]});const Ge=Pe?o.jsx(ERe,{className:"h-full",result:Pe,scores:Ce?.[Pe.itemId],experimentLink:Pe.experimentId?l.experimentItemLink(Pe.experimentId,Pe.itemId):void 0,tagVocabulary:G,onTagsChange:k?void 0:ae=>{te(Pe.id,ae);for(const ce of ae)G.includes(ce)||z(ce)},onComplete:k?void 0:()=>J(Pe.id),onPrevious:ze,onNext:Oe,onClose:()=>v(null)}):null;return o.jsxs(o.Fragment,{children:[o.jsx(Lt.TopArea,{children:tt}),o.jsx(vr,{open:T,onOpenChange:N,children:o.jsxs(yr,{children:[o.jsxs(br,{children:[o.jsx(fr,{children:"Analyze Items"}),o.jsx($s,{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(Mt,{className:"mb-1 block text-xs",children:"Provider"}),o.jsx(Gy,{value:R,onValueChange:L})]}),o.jsxs("div",{children:[o.jsx(Mt,{className:"mb-1 block text-xs",children:"Model"}),o.jsx(Qy,{llmId:R,value:M,onValueChange:B})]})]}),o.jsxs(ge,{variant:"ui-xs",className:"text-neutral3",children:[x.size," item",x.size!==1?"s":""," will be analyzed"]}),o.jsxs("div",{children:[o.jsx(Mt,{className:"text-xs",children:"Instructions (optional)"}),o.jsx(Mo,{value:I,onChange:ae=>A(ae.target.value),placeholder:"E.g., Focus on safety issues and factual errors...",rows:3,className:"mt-1 text-xs"})]})]}),o.jsxs(Fl,{children:[o.jsx(oe,{variant:"outline",onClick:()=>N(!1),children:"Cancel"}),o.jsxs(oe,{onClick:Re,disabled:!R||!M||_,children:[_?o.jsx(Vt,{className:"mr-1 h-4 w-4"}):null,"Analyze"]})]})]})}),o.jsx(vr,{open:F,onOpenChange:H,children:o.jsxs(yr,{className:"max-h-[80vh] max-w-2xl overflow-y-auto",children:[o.jsxs(br,{children:[o.jsx(fr,{children:"Review Proposed Tags"}),o.jsxs($s,{children:[V.filter(ae=>ae.accepted).length," of ",V.length," proposals selected"]})]}),o.jsx("div",{className:"space-y-3 py-2",children:V.map((ae,ce)=>{const me=D.find(Se=>Se.id===ae.itemId);return o.jsx("div",{className:K("p-3 border rounded-lg",!ae.accepted&&"opacity-50"),children:o.jsxs("div",{className:"flex items-start gap-2",children:[o.jsx(zo,{checked:ae.accepted,onCheckedChange:Se=>q(Fe=>Fe.map((De,be)=>be===ce?{...De,accepted:!!Se}:De))}),o.jsxs("div",{className:"min-w-0 flex-1",children:[o.jsx(ge,{variant:"ui-xs",className:"text-neutral4 block truncate",children:me?typeof me.input=="string"?me.input.slice(0,100):JSON.stringify(me.input).slice(0,100):ae.itemId}),o.jsx("div",{className:"mt-1.5 flex flex-wrap gap-1",children:ae.tags.map((Se,Fe)=>o.jsx(UHt,{tag:Se,onRename:De=>q(be=>be.map((je,Le)=>Le===ce?{...je,tags:je.tags.map((Xe,kt)=>kt===Fe?De:Xe)}:je)),onRemove:()=>q(De=>De.map((be,je)=>je===ce?{...be,tags:be.tags.filter((Le,Xe)=>Xe!==Fe)}:be))},`${Se}-${Fe}`))}),ae.reason&&o.jsx(ge,{variant:"ui-xs",className:"text-neutral3 mt-1 block italic",children:ae.reason})]})]})},ae.itemId)})}),o.jsxs(Fl,{children:[o.jsx(oe,{variant:"outline",onClick:()=>H(!1),children:"Cancel"}),o.jsxs(oe,{onClick:Ae,disabled:V.filter(ae=>ae.accepted).length===0,children:["Accept ",V.filter(ae=>ae.accepted).length," proposals"]})]})]})}),o.jsxs(Lt.MainArea,{className:K("grid h-full min-h-0 w-full grid-cols-1 gap-4",r==="overlay"?"overflow-visible":"overflow-hidden",Pe&&r==="inline"&&"grid-cols-[1fr_1fr]"),children:[o.jsx("div",{className:"min-h-0 w-full overflow-hidden",children:le?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Vt,{className:"h-6 w-6"})}):re.length===0?o.jsx("div",{className:"flex h-full items-center-safe justify-center-safe overflow-auto py-12",children:o.jsx(pr,{iconSlot:o.jsx(ks,{className:"text-neutral3 h-8 w-8"}),titleSlot:k?"No completed reviews yet":"No items to review",descriptionSlot:k?"Items marked as complete will appear here for auditing.":"When experiment results are flagged for review, they will appear here."})}):o.jsx(dY,{results:re,isLoading:!1,featuredResultId:m,onResultClick:Ie,columns:T0s,selectedIds:k?void 0:x,onToggleSelect:k?void 0:de,onToggleSelectAll:k?void 0:ue})}),Ge&&(r==="overlay"?o.jsx(gY,{label:`Review item ${Pe?.id??""}`,children:o.jsx("div",{className:"[&>section]:bg-surface3 h-full min-h-0 p-3 [&>section]:rounded-lg [&>section]:shadow-lg",children:Ge})}):Ge)]})]})}const Cnt={needsReview:"#facc15",complete:"#22c55e"},I0s=[{label:"Needs Review",color:Cnt.needsReview},{label:"Reviewed",color:Cnt.complete}];function A0s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Review Pipeline",description:"Items in review across experiments."}),c&&o.jsx(qt.Summary,{value:String(l),label:"Items in pipeline"})]}),r?o.jsx(qt.Loading,{}):s?o.jsx(qt.Error,{message:"Failed to load review data"}):o.jsx(qt.Content,{children:c?o.jsx(nI,{data:a,segments:I0s,maxVal:i,fmt:u=>String(u)}):o.jsx(qt.NoData,{message:"No items have been sent to review yet"})})]})}function AWt(){const e=Ze();return mt({queryKey:["experiment-review-summary"],queryFn:()=>e.getExperimentReviewSummary()})}function R0s(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 P0s(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 $0s(){const[e,t]=g.useState("all"),[n,r]=g.useState({}),{data:s,isLoading:a,error:i}=up(),{data:l,isLoading:c,error:u}=Rm(),{data:d,isLoading:f,error:h}=QH(),{data:p,isLoading:m,isError:v,error:y}=wWr(n),{data:b,isLoading:x,isError:w,error:k}=AWt(),O=l?.datasets,_=d?.experiments,E=g.useMemo(()=>P0s(b),[b]),T=i||u||h||y||k;return T&&hs(T)?o.jsx(Zn,{children:o.jsx(Es,{})}):T&&ps(T)?o.jsx(Zn,{children:o.jsx(Os,{resource:"evaluation"})}):T?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load evaluation data",message:T.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{children:o.jsx(Lt.Column,{children:o.jsx(KL,{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-6",children:[o.jsx(C0e,{children:o.jsx(e0s,{scorers:s,datasets:O,experiments:_,avgScore:p?.avgScore??null,prevAvgScore:p?.prevAvgScore??null,totalNeedsReview:E.needsReview,isLoadingScorers:a,isLoadingDatasets:c,isLoadingExperiments:f,isLoadingScores:m,isLoadingReview:x})}),o.jsx(RHr,{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-6 lg:grid-cols-2",children:[o.jsx(rbs,{experiments:_,isLoading:f,isError:!!h}),o.jsx(p0s,{experiments:_,datasets:O,isLoading:f,isError:!!h})]}),o.jsx(A0s,{reviewSummary:b,experiments:_,datasets:O,isLoading:x,isError:!!w})]})]})}function M0s(){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=Kr(),[f,h]=ya(),p=f.get("dataset")??"all",m=g.useCallback(G=>{h(z=>{const $=new URLSearchParams(z);return G==="all"?$.delete("dataset"):$.set("dataset",G),$},{replace:!0})},[h]),{data:v,isLoading:y,error:b}=Rm(),{data:x,isLoading:w,error:k}=yY(p==="all"?void 0:p),{data:O}=AWt(),_=g.useMemo(()=>v?.datasets??[],[v?.datasets]),E=g.useMemo(()=>x?.experiments??[],[x?.experiments]),T=g.useMemo(()=>f0s(_),[_]),N=g.useMemo(()=>R0s(O),[O]),I=y||w,A=k||b,R=G=>{u(z=>z.includes(G)?z.filter($=>$!==G):z.length>=2?[z[0],G]:[...z,G])},L=()=>{u([]),l(!1)},{selectedIds:M,selectedDatasetIds:B}=g.useMemo(()=>{const G=new Map(E.map($=>[$.id,$.datasetId])),z=c.filter($=>G.has($));return{selectedIds:z,selectedDatasetIds:new Set(z.map($=>G.get($)))}},[E,c]),V=M.length===2&&B.size!==1?"not the same dataset":void 0,q=()=>{if(M.length!==2||V)return;const[G,z]=M,[$]=B;if(!$)return;const U=new URLSearchParams({dataset:$,baseline:G,contender:z});d(`/experiments/compare?${U.toString()}`)};if(A&&hs(A))return o.jsx(Zn,{children:o.jsx(Es,{})});if(k&&ps(k))return o.jsx(Zn,{children:o.jsx(Os,{resource:"experiments"})});if(b&&ps(b))return o.jsx(Zn,{children:o.jsx(Os,{resource:"datasets"})});if(A)return o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load experiments",message:A.message})});const F=o.jsx(mY,{open:s,onOpenChange:a,onSuccess:G=>{d(`/experiments/${G}`)}});if(E.length===0&&!I&&p==="all")return o.jsxs(Zn,{children:[o.jsx(m0s,{onRunExperiment:()=>a(!0)}),F]});const H=n!=="all"||p!=="all"||e!=="",D=()=>{t(""),r("all"),m("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(g0s,{search:e,onSearchChange:t,statusFilter:n,onStatusFilterChange:r,datasetFilter:p,onDatasetFilterChange:m,datasetOptions:T,onReset:D,hasActiveFilters:H,onRunClick:()=>a(!0),onCompareClick:()=>l(!0),selection:i?{selectedCount:M.length,onExecuteCompare:q,onCancelSelection:L,compareDisabledReason:V}:void 0})}),o.jsx(u0s,{experiments:E,datasets:_,reviewByExperiment:N,isLoading:I,search:e,statusFilter:n,datasetFilter:p,selection:i?{selectedExperimentIds:M,onToggleSelection:R}:void 0}),F]})}function m8({experimentId:e}){const{Link:t,paths:n}=ln();return o.jsx(oe,{as:t,href:n.experimentLink(e),size:"sm","aria-label":`Open experiment ${e}`,children:e.slice(0,8)})}function D0s(){const[e,t]=ya(),n=e.get("dataset")??"",r=e.get("baseline")??"",s=e.get("contender")??"",a=XD(n,r),i=XD(n,s),l=a.isLoading||i.isLoading,c=a.error??i.error;return c&&hs(c)?o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Es,{})})}):c&&ps(c)?o.jsx(ia,{children:o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"experiments"})})}):!n||!r||!s?o.jsx(ia,{children:o.jsx(Ox,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsx("p",{children:"Select two experiments to compare."}),o.jsxs("p",{className:"mt-2 text-sm",children:["Use the URL format: /experiments/compare?dataset=","{datasetId}","&baseline=","{experimentIdA}","&contender=","{experimentIdB}"]})]})})}):l?null:c&&!h0(c)?o.jsx(ia,{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(ia,{children:o.jsx(Ox,{children:o.jsxs("div",{className:"text-neutral4 py-8 text-center",children:[o.jsxs("p",{children:["Experiments must belong to the same dataset (",n,") to be compared."]}),o.jsxs("p",{className:"mt-2 flex items-center justify-center gap-2 text-sm",children:["One of",o.jsx(m8,{experimentId:r}),"and",o.jsx(m8,{experimentId:s}),"was not found in it."]})]})})}):o.jsx(ia,{children:o.jsx(Ox,{children:o.jsxs("div",{className:"grid w-full content-start",children:[o.jsxs("div",{className:"flex items-center justify-between gap-4 px-6 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(m8,{experimentId:r}),"and",o.jsx(m8,{experimentId:s})]})]}),o.jsxs(gn,{children:[o.jsx(fn,{asChild:!0,children:o.jsxs(oe,{onClick:()=>t({dataset:n,baseline:s,contender:r}),children:[o.jsx(dut,{}),"Swap sides"]})}),o.jsx(hn,{children:"Switch baseline and contender"})]})]}),o.jsx(O0s,{datasetId:n,experimentIdA:r,experimentIdB:s})]})})})}function L0s({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(ts,{className:"whitespace-nowrap",children:[o.jsxs(oe,{variant:"outline",disabled:i,onClick:e.flagSelectedForReview,children:[o.jsx($C,{}),"Flag ",t.size," to review"]}),o.jsx(jVt,{selectedResults:n,vocabulary:r,onAddTag:e.addTagToSelected,disabled:i}),o.jsx(oe,{variant:"ghost",onClick:e.clearSelection,children:"Clear"})]})}const RWt=e=>o.jsx("svg",{width:"16",height:"16",viewBox:"0 0 8.64637 9.45103",fill:"none",xmlns:"http://www.w3.org/2000/svg",...e,children:o.jsx("path",{d:"M7.80735 5.87241C7.63209 5.97219 7.43696 6.06166 7.22844 6.13866C6.46456 6.42068 5.43714 6.58649 4.32296 6.58649C3.20873 6.58649 2.18135 6.4207 1.41747 6.13866C1.20889 6.06164 1.01385 5.97223 0.838558 5.87241V7.59003C0.838558 7.62341 0.855765 7.70759 1.00172 7.83512C1.14707 7.96201 1.38219 8.09563 1.70829 8.21605C2.3572 8.45563 3.28149 8.61268 4.32296 8.61269C5.36456 8.61269 6.28937 8.45568 6.9383 8.21605C7.26428 8.09566 7.49888 7.96198 7.64419 7.83512C7.79024 7.70754 7.80735 7.62342 7.80735 7.59003V5.87241ZM7.80735 3.00789C7.63214 3.10763 7.4369 3.19647 7.22844 3.27345C6.46455 3.55549 5.43719 3.72129 4.32296 3.72129C3.20868 3.72128 2.18136 3.55552 1.41747 3.27345C1.20896 3.19645 1.01381 3.10766 0.838558 3.00789V4.72551C0.838558 4.7589 0.855657 4.84301 1.00172 4.97059C1.14707 5.09749 1.38219 5.23111 1.70829 5.35153C2.3572 5.59109 3.28154 5.74747 4.32296 5.74748C5.36456 5.74748 6.28937 5.59116 6.9383 5.35153C7.26432 5.23112 7.49887 5.09747 7.64419 4.97059C7.7536 4.87505 7.79089 4.80404 7.80257 4.76033L7.80735 4.72551V3.00789ZM7.80735 1.86099C7.80735 1.82758 7.79045 1.74291 7.64419 1.61522C7.49887 1.48838 7.26421 1.35534 6.9383 1.23497C6.28937 0.995339 5.36456 0.838331 4.32296 0.838331C3.28149 0.83834 2.3572 0.995383 1.70829 1.23497C1.38219 1.35539 1.14707 1.48832 1.00172 1.61522C0.855475 1.7429 0.838558 1.82758 0.838558 1.86099C0.838673 1.89462 0.855968 1.97882 1.00172 2.10607C1.14707 2.23297 1.38219 2.3659 1.70829 2.48632C2.3572 2.7259 3.28149 2.88295 4.32296 2.88296C5.36456 2.88296 6.28937 2.72595 6.9383 2.48632C7.26421 2.36595 7.49887 2.23291 7.64419 2.10607C7.78996 1.97881 7.80724 1.89462 7.80735 1.86099ZM8.64637 7.59003C8.64637 7.95465 8.44458 8.25006 8.1958 8.46728C7.94608 8.68529 7.60876 8.86274 7.22844 9.00318C6.46455 9.28522 5.43718 9.45102 4.32296 9.45102C3.20869 9.45101 2.18135 9.28525 1.41747 9.00318C1.03715 8.86274 0.699831 8.68529 0.450113 8.46728C0.201377 8.25007 0.000227451 7.9546 0.000227451 7.59003V1.86099C0.000227451 1.49643 0.201388 1.20095 0.450113 0.983742C0.699831 0.765728 1.03715 0.588275 1.41747 0.447838C2.18136 0.165769 3.20868 8.74396e-06 4.32296 0C5.43719 0 6.46455 0.165797 7.22844 0.447838C7.60876 0.588275 7.94608 0.765728 8.1958 0.983742C8.44457 1.20096 8.64637 1.49638 8.64637 1.86099V7.59003Z",fill:"currentColor"})});function PWt(e){const{data:t}=Ny(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 doe({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(fn,{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(hn,{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 foe="text-neutral5 inline-flex min-w-0 items-center gap-1.5 hover:underline";function F0s({experiment:e,className:t}){const{Link:n,paths:r}=ln(),s=OWt(),{scorers:a}=s,{data:i,isLoading:l}=Yg(e.datasetId??""),c=PWt(e),u=e.targetType,d=e.targetId,f=EWt(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&&CWt[u]||co,m=u&&_Wt[u]||"Evaluation target";return o.jsxs("ol",{className:K("grid",t),children:[o.jsx(doe,{icon:o.jsx(RWt,{}),typeLabel:"Dataset",description:`Each item will be passed to the ${m.toLowerCase()}`,subject:e.datasetId?o.jsxs(n,{href:r.datasetLink(e.datasetId),className:foe,children:[o.jsx("span",{className:"truncate",children:l?o.jsx(wt,{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(doe,{icon:o.jsx(p,{}),typeLabel:m,description:"Its output is then scored",subject:h?o.jsx(n,{href:h,className:foe,children:o.jsx("span",{className:"truncate",children:f})}):o.jsx("span",{className:"text-neutral3 truncate",children:f})}),o.jsx(doe,{icon:o.jsx(M_,{}),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:foe,children:o.jsx("span",{className:"truncate",children:y})})},v)})})})]})}function YE({label:e,children:t}){return o.jsxs(o.Fragment,{children:[o.jsx(Fn.Key,{children:e}),o.jsx(Fn.Value,{className:"flex flex-wrap items-baseline justify-end gap-x-1.5 text-right",children:t})]})}function _nt(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 z0s({experiment:e,metrics:t}){const{data:n}=Ny(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?"—":_nt(c)})();return o.jsxs(Fn,{children:[o.jsx(YE,{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(YE,{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(YE,{label:"Started",children:i?o.jsx("span",{title:DDn(i,{addSuffix:!0}),children:mr(i,"MMM d, h:mm a")}):o.jsx("span",{children:"—"})}),o.jsx(YE,{label:"Duration",children:o.jsx("span",{children:l})}),t?.isEnabled&&o.jsxs(o.Fragment,{children:[o.jsx(YE,{label:"Tokens",children:t.data?.totalTokens==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsxs(o.Fragment,{children:[o.jsx("span",{children:to(t.data.totalTokens)}),t.data.estimatedCost!=null&&o.jsxs("span",{className:"text-neutral3",children:["· ",Fd(t.data.estimatedCost,t.data.costUnit)]}),r&&o.jsx("span",{className:"text-neutral3",children:"· so far"})]})}),o.jsx(YE,{label:"Latency (avg)",children:t.data?.avgAgentDurationMs==null?o.jsx("span",{className:"text-neutral3",children:"—"}):o.jsx("span",{children:_nt(Math.round(t.data.avgAgentDurationMs))})})]})]})}function B0s({scoresByItemId:e,experimentStatus:t}){const{Link:n,paths:r}=ln(),{data:s}=up(),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(Ry,{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(fn,{render:o.jsx(M_,{role:"img","aria-label":"Scorer"})}),o.jsx(hn,{children:"Scorer"})]}),o.jsx("span",{className:"truncate",children:c})]}),o.jsxs("strong",{className:"text-ui-lg 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 hoe({title:e,children:t}){return o.jsxs("section",{className:"grid gap-3",children:[o.jsx("h2",{className:"text-ui-sm text-neutral2 tracking-widest uppercase",children:e}),t]})}function U0s({experiment:e,metrics:t,className:n}){const{Link:r,paths:s}=ln(),{data:a}=Ny(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(Ic,{as:"aside","aria-label":"Experiment details",className:K("grid content-start gap-8 p-5",n),children:[o.jsxs(hoe,{title:"Pipeline",children:[o.jsx(F0s,{experiment:e}),e.agentVersion&&o.jsxs(Fn,{children:[o.jsx(Fn.Key,{children:"Version"}),i?o.jsx(Fn.ValueLink,{href:i,as:r,children:e.agentVersion}):o.jsx(Fn.Value,{children:e.agentVersion})]})]}),o.jsx(hoe,{title:"Run",children:o.jsx(z0s,{experiment:e,metrics:t})}),o.jsx(hoe,{title:"Scorers",children:o.jsx(B0s,{scoresByItemId:a,experimentStatus:e.status})})]})}function q0s({experiment:e,open:t,onOpenChange:n}){const[r,s]=g.useState(e.name??""),[a,i]=g.useState(e.description??""),{updateExperiment:l}=Fa(),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()}),Ve.success("Experiment renamed"),n(!1)}catch(f){Ve.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(fr,{children:"Rename Experiment"})}),o.jsx(Pr,{children:o.jsxs("form",{onSubmit:u,className:"space-y-4",children:[o.jsxs("div",{className:"space-y-2",children:[o.jsx(Mt,{htmlFor:"rename-experiment-name",children:"Name *"}),o.jsx(jn,{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(Mt,{htmlFor:"rename-experiment-description",children:"Description"}),o.jsx(jn,{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(oe,{type:"button",onClick:()=>n(!1),disabled:l.isPending,children:"Cancel"}),o.jsx(oe,{type:"submit",variant:"primary",disabled:!c,children:l.isPending?"Saving...":"Save"})]})]})})]})})}const V0s=["agent","workflow","scorer"];function H0s({experiment:e}){const[t,n]=g.useState(!1),r=Kr(),{paths:s}=ln(),a=PWt(e),i=V0s.find(l=>l===e.targetType);return!e.datasetId||!i||!e.targetId?null:o.jsxs(o.Fragment,{children:[o.jsxs(oe,{variant:"primary",onClick:()=>n(!0),tooltip:"Run this experiment again with the same configuration",children:[o.jsx(Pc,{}),"Rerun"]}),t&&o.jsx(mY,{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 W0s({experiment:e,onDeleteClick:t,children:n}){const{Link:r}=ln(),[s,a]=g.useState(!1),i=!!e.datasetId,l=i||!!t;return o.jsxs(Lt.TopArea,{children:[o.jsxs(Lt.Row,{className:"items-center justify-start gap-2",children:[o.jsxs(ts,{className:"whitespace-nowrap",children:[o.jsx(H0s,{experiment:e}),o.jsxs(oe,{as:r,to:mDt(e.id),children:[o.jsx($C,{}),"Review queue"]}),l&&o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(oe,{size:"lg","aria-label":"Experiment actions menu",children:o.jsx(XS,{})})}),o.jsxs(ot.Content,{align:"start",className:"w-48",children:[i&&o.jsxs(ot.Item,{onSelect:()=>a(!0),children:[o.jsx(Qh,{})," Rename Experiment"]}),t&&o.jsxs(ot.Item,{onSelect:t,className:"text-red-500 focus:text-red-400",children:[o.jsx(ll,{})," Delete Experiment"]})]})]})]}),n]}),s&&o.jsx(q0s,{experiment:e,open:!0,onOpenChange:a})]})}const Z0s=({experimentId:e,experimentStatus:t})=>{const n=Ze(),{supportsMetrics:r}=HQ(),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 G0s({datasetId:e,experimentId:t}){const[n,r]=g.useState(!1),{updateExperimentResult:s}=Fa();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?Ve(`Tag "${i}" added to ${u} result${u>1?"s":""}`):Ve.error("Failed to add tag")},[e,t,n,s]),isPending:n}}function $Wt(e,t){const{data:n}=Yg(e);return g.useMemo(()=>[...new Set([...n?.tags??[],...t.flatMap(r=>r.tags??[])])].sort(),[n?.tags,t])}function Q0s({datasetId:e,experimentId:t,results:n}){const[r,s]=g.useState(new Set),[a,i]=g.useState(!1),{updateExperimentResult:l}=Fa(),{addTag:c,isPending:u}=G0s({datasetId:e,experimentId:t}),d=$Wt(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}),Ve(`${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 Y0s=[];function g8({children:e}){return o.jsxs(Lt,{height:"full",children:[o.jsx("div",{}),o.jsx(Lt.MainArea,{isCentered:!0,children:e})]})}function K0s(){const{experimentId:e}=ur(),t=Kr(),[n,r]=g.useState(!1),{data:s,isLoading:a}=QH(),l=s?.experiments?.find(w=>w.id===e)?.datasetId??"",{data:c,isLoading:u,error:d}=XD(l,e??""),{data:f,isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v}=JD({datasetId:l,experimentId:e??"",experimentStatus:c?.status}),y=Z0s({experimentId:e,experimentStatus:c?.status}),b=Q0s({datasetId:l,experimentId:e??"",results:f??Y0s});if(!e||a||u)return null;if(d&&hs(d))return o.jsx(g8,{children:o.jsx(Es,{})});if(d&&ps(d))return o.jsx(g8,{children:o.jsx(Os,{resource:"datasets"})});const x=o.jsx(g8,{children:o.jsx(pr,{iconSlot:o.jsx(U0e,{}),titleSlot:"Experiment not found",descriptionSlot:`No experiment with id "${e}".`,actionSlot:o.jsxs(oe,{as:yo,to:"/experiments",children:[o.jsx(wu,{}),"Back to Experiments"]})})});return d&&h0(d)?x:d?o.jsx(g8,{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(gxs,{experimentId:e,datasetId:l,experimentStatus:c.status,results:f??[],isLoadingResults:h,hasNextPage:v,children:o.jsxs("div",{className:"h-full",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(W0s,{experiment:c,onDeleteClick:()=>r(!0),children:o.jsx(L0s,{selection:b})}),o.jsxs(Lt.MainArea,{className:"grid grid-cols-[1fr_auto] gap-6 overflow-visible",children:[o.jsx(vxs,{experimentId:e,experimentStatus:c.status,results:f??[],isLoading:h,setEndOfListElement:p,isFetchingNextPage:m,hasNextPage:v,selectedIds:b.selectedIds,onToggleSelect:b.toggleSelect}),o.jsx(U0s,{experiment:c,metrics:y,className:"w-80 overflow-y-auto"})]})]}),o.jsx(Fg,{}),o.jsx(wWt,{open:n,onOpenChange:r,experimentId:e,experimentName:c.name??void 0,onSuccess:()=>t("/experiments")})]})})}function X0s(){const{itemId:e}=ur();return e?o.jsx(J0s,{itemId:e},e):null}function J0s({itemId:e}){const{experimentId:t,datasetId:n,experimentStatus:r,results:s,isLoadingResults:a,hasNextPage:i,close:l,goToPreviousItem:c,goToNextItem:u}=bWt(),d=g.useMemo(()=>s.find(w=>w.itemId===e)??null,[s,e]),{data:f}=Ny(t,r),{updateExperimentResult:h}=Fa(),p=g.useCallback(async w=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,status:"needs-review"}),Ve("Result flagged for review")}catch{Ve.error("Failed to flag result for review")}},[n,t,h]),m=$Wt(n,s),v=g.useCallback(async(w,k)=>{try{await h.mutateAsync({datasetId:n,experimentId:t,resultId:w,tags:k})}catch{Ve.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"}),Ve("Result marked as reviewed")}catch{Ve.error("Failed to complete result")}},[n,t,h]),b=d?f?.[d.itemId]:void 0,x=IVt(b);return o.jsx(gY,{label:`Experiment item ${e}`,wide:x.wide,children:d?o.jsx(ERe,{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(Vt,{})})}):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(pr,{iconSlot:o.jsx(U0e,{}),titleSlot:"Item not found",descriptionSlot:`No loaded result for item "${e}".`,actionSlot:o.jsx(oe,{onClick:l,children:"Close"})})})})})}const MWt=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"})}),PV="all",Ent=60,ews=e=>e.length>Ent?`${e.slice(0,Ent)}…`:e;function tws({value:e,onValueChange:t,className:n,variant:r,allOption:s}){const{data:a,isLoading:i,isError:l}=yY(void 0),c=(a?.experiments??[]).map(d=>({label:SWt(d),value:d.id,start:o.jsx(MWt,{className:"text-neutral3 size-4 shrink-0","data-testid":"experiments-icon"}),description:d.description?ews(d.description):b0(d.id)??d.id})),u=s?[{label:"All experiments",value:PV},...c]:c;return o.jsx(Fo,{options:u,value:e??(s?PV:""),onValueChange:t,placeholder:i?"Loading experiments...":l?"Failed to load experiments":"Select experiment",searchPlaceholder:"Search experiments...",emptyText:"No experiments found.",className:n,disabled:i||l,variant:r})}function nws(){const[e,t]=ya(),n=e.get("experiment"),r=e.get("review"),{Link:s,paths:a}=ln(),{data:i,error:l}=yY(void 0),c=i?.experiments.find(d=>d.id===n),u=d=>{t(d===PV?{}:{experiment:d},{replace:!0})};return l&&hs(l)?o.jsx(Zn,{children:o.jsx(Es,{})}):l&&ps(l)?o.jsx(Zn,{children:o.jsx(Os,{resource:"experiments"})}):l?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load experiments",message:l.message})}):o.jsx(Lt,{height:"full",children:o.jsx(N0s,{datasetId:c?.datasetId??void 0,experimentId:n??void 0,featuredItemId:r,detailPanelVariant:"overlay",toolbarStart:o.jsx(tws,{allOption:!0,value:n??void 0,onValueChange:u,className:"w-72"}),toolbarEnd:n?o.jsxs(oe,{as:s,href:a.experimentLink(n),children:["See experiment",o.jsx(fut,{})]}):void 0},n??PV)})}const DWt=[{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"}],rws=DWt.map(e=>e.size).join(" ");function sws({items:e,isLoading:t,error:n}){const r=Kr(),[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(Do,{columns:rws}):n?o.jsx(Fs,{title:"Failed to load dataset items",message:n.message}):e.length===0?o.jsx(pr,{iconSlot:o.jsx(ks,{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(Uc,{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(dY,{results:l,isLoading:!1,featuredResultId:null,onResultClick:c=>{const u=l.find(d=>d.id===c);u&&r(mDt(u.experimentId,u.id))},columns:DWt,emptyMessage:"No dataset items match your search"})})]})}function aws(){return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),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(oe,{as:yo,to:"/experiments",variant:"outline",children:"Go to experiments"}),o.jsx(oe,{as:yo,to:"/traces",variant:"outline",children:"Go to traces"})]})})})}function _0e(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 Tnt="minmax(0, 2fr) minmax(0, 1fr) auto minmax(0, 1fr) auto auto";function iws({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=>_0e(x).toLowerCase().includes(h)||(TV(x)??"").toLowerCase().includes(h)||(x.traceId??"").toLowerCase().includes(h)||(x.feedbackSource??"").toLowerCase().includes(h)):e,{containerRef:m,getRowProps:v}=ol({count:p.length}),{inView:y,setRef:b}=s0({root:m});return g.useEffect(()=>{y&&r&&!s&&a()},[y,r,s,a]),t?o.jsx(Do,{columns:Tnt}):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(Uc,{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(ve,{columns:Tnt,fit:"container",scrollRef:m,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Feedback"}),o.jsx(ve.TopCell,{children:"Author"}),o.jsx(ve.TopCell,{children:"Source"}),o.jsx(ve.TopCell,{children:"Trace"}),o.jsx(ve.TopCell,{children:"Date"}),o.jsx(ve.TopCell,{children:" "})]}),p.length===0?o.jsx(ve.NoMatch,{message:h?"No feedback matches your search":"No feedback needs review"}):p.map((x,w)=>{const k=x.feedbackId,O=TV(x);return o.jsxs(ve.RowWrapper,{children:[o.jsxs(ve.RowButton,{colEnd:-2,disabled:!x.traceId,featured:k!==void 0&&k===u,onClick:()=>c(x),...v(w),children:[o.jsx(ve.TextCell,{className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:_0e(x)})}),o.jsx(ve.Cell,{className:"flex gap-2",children:O&&o.jsxs(o.Fragment,{children:[o.jsx(jy,{name:O,src:x.author?.avatarUrl,size:"sm"}),o.jsx("span",{className:"truncate",children:O})]})}),o.jsx(ve.Cell,{children:o.jsx(yt,{size:"sm",children:x.feedbackSource})}),o.jsx(ve.TextCell,{font:"mono",className:"min-w-0",children:o.jsx("span",{className:"block truncate",children:x.traceId??"—"})}),o.jsx(ve.TextCell,{children:mr(x.timestamp,"MMM d, h:mm a")})]}),o.jsx(ve.ActionsCell,{className:"pl-2",children:k?o.jsx(oe,{variant:"ghost",size:"sm",onClick:()=>i(k),disabled:l===k,children:"Mark reviewed"}):null})]},k??`${String(x.timestamp)}-${x.traceId}`)}),o.jsx(ve.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:b})]})})]})}function ows({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}=rWt({traceId:t,anchorSpanId:null,listMode:"traces"}),h=TV(e)??e.feedbackUserId;return o.jsx(gY,{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(wn,{className:"max-h-[33vh]",children:[o.jsxs(wn.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(wn.Heading,{children:"Feedback"}),o.jsx(yt,{variant:"neutral",emphasis:"muted",children:e.feedbackType}),e.feedbackSource&&o.jsx(yt,{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(jy,{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:mr(new Date(e.timestamp),"MMM dd, yyyy HH:mm:ss")})]})]}),o.jsx(ts,{className:"ml-auto shrink-0",children:o.jsxs(oe,{variant:"primary",size:"sm",onClick:i,disabled:l,children:[o.jsx(Je,{children:o.jsx(Dr,{})}),"Mark as reviewed"]})})]}),o.jsx(wn.Content,{children:o.jsx(ge,{as:"p",variant:"ui-md",className:"text-neutral5 whitespace-pre-wrap",children:_0e(e)})})]}),o.jsx("section",{className:"min-h-0 overflow-hidden",children:o.jsx(_Re,{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(t3,{traceId:p}),spanFeedbackTabSlot:({traceId:p,spanId:m})=>p&&m?o.jsx(hRe,{traceId:p,spanId:m},`${p}:${m}`):null})})]})})}const LWt=100;async function lws(e){const t=[];let n=0,r=!0;for(;r;){const s=await e.listExperiments({page:n,perPage:LWt});t.push(...s.experiments),r=s.pagination.hasMore,n+=1}return t}async function cws(e,t,n){const r=[];let s=0,a=!0;for(;a;){const i=await e.listDatasetExperimentResults(t,n,{page:s,perPage:LWt});r.push(...i.results),a=i.pagination.hasMore,s+=1}return r}function uws(){const e=Ze();return mt({queryKey:["inbox-dataset-review-items"],queryFn:async()=>{const t=await lws(e);return(await Promise.all(t.map(async r=>{const s=r.datasetId;return s?(await cws(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 dws({enabled:e}){const t=Ze();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 fws(e){return e==="dataset"||e==="feedback"}function hws(){const[e,t]=ya(),n=e.get("tab"),r=fws(n)?n:"feedback",s=_hs({reviewStatus:"needs-review"}),a=fRe(),i=uws(),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=E=>{t(T=>{const N=new URLSearchParams(T);for(const I of["feedbackId","traceId","spanId"]){const A=E[I];A?N.set(I,A):N.delete(I)}return N},{replace:!0})},m=()=>p({}),v=E=>p({feedbackId:E.feedbackId??void 0,traceId:E.traceId??void 0,spanId:E.spanId??void 0}),y=s.items.findIndex(E=>E.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=E=>{a.mutate({feedbackId:E,reviewStatus:"reviewed"},{onSuccess:()=>E===d&&m()})},_=E=>{t(T=>{const N=new URLSearchParams(T);return N.set("tab",E),N},{replace:!0})};return o.jsxs("div",{className:"relative h-full overflow-hidden",children:[o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(pu,{children:[o.jsx(pu.Title,{children:"Inbox"}),o.jsx(pu.Description,{children:"Items waiting for review"})]})}),o.jsx(Lt.MainArea,{className:"min-h-0 overflow-hidden",children:u?o.jsx(aws,{}):o.jsxs(wl,{defaultTab:"feedback",value:r,onValueChange:_,className:"grid h-full min-h-0 grid-rows-[auto_1fr]",children:[o.jsxs(xl,{variant:"pill-ghost",children:[o.jsxs(wr,{value:"feedback",className:"px-3 py-2.5",children:[o.jsx(Je,{size:"sm",children:o.jsx(c3,{})}),o.jsx(ge,{variant:"ui-sm",className:"text-inherit",children:"Feedback"}),c>0&&o.jsx(yt,{variant:"yellow",size:"sm",children:c})]}),o.jsxs(wr,{value:"dataset",className:"px-3 py-2.5",children:[o.jsx(Je,{size:"sm",children:o.jsx($C,{})}),o.jsx(ge,{variant:"ui-sm",className:"text-inherit",children:"Dataset items"}),l.length>0&&o.jsx(yt,{variant:"yellow",size:"sm",children:l.length})]})]}),o.jsx(Qr,{value:"feedback",className:"h-full min-h-0 pt-4",children:o.jsx(iws,{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(Qr,{value:"dataset",className:"h-full min-h-0 pt-4",children:o.jsx(sws,{items:l,isLoading:i.isLoading,error:i.error??void 0})})]})})]}),k&&f&&b&&o.jsx(ows,{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 pws({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-xs",children:e.connectionId}),o.jsxs("div",{className:"text-xs 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 FWt({connections:e,isAdmin:t,disconnectPending:n,onDisconnect:r}){return o.jsx("ul",{className:"space-y-1",children:e.map(s=>o.jsx(pws,{connection:s,isAdmin:t,disconnectPending:n,onDisconnect:()=>r(s.connectionId)},s.connectionId))})}function mws({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-sm font-semibold text-gray-700","data-testid":`integration-author-group-${s}`,children:s==="shared"?"Shared":`Owned by ${s}`}),o.jsx(FWt,{connections:a,isAdmin:t,disconnectPending:n,onDisconnect:r})]},s))})}function gws({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-lg 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(mws,{groups:r,isAdmin:s,disconnectPending:l,onDisconnect:u}):o.jsx(FWt,{connections:n,isAdmin:s,disconnectPending:l,onDisconnect:u}),c?o.jsx("p",{className:"text-red-600",children:String(c)}):null]})}function vws({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 jnt=e=>e.authorId?.trim()||"shared",yws=(e,t)=>{if(!t||new Set(e.map(jnt)).size<=1)return null;const r=new Map;for(const a of e){const i=jnt(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},bws=["*","tool-providers:*","tool-providers:admin"];function xws(){const{data:e}=Fm();return e?.permissions?.some(t=>bws.includes(t))??!1}function wws(){const[e,t]=g.useState(""),[n,r]=g.useState(""),[s,a]=g.useState(""),i=oA(),l=vG(e||null),c=YLt(e||null,n||null),u=QLt(),d=WLt(),f=xws(),h=i.data?.providers??[],p=l.data?.data??[],m=g.useMemo(()=>c.data?.items??[],[c.data?.items]),v=g.useMemo(()=>yws(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-6 max-w-3xl space-y-6 text-sm",children:[o.jsx("h1",{className:"text-2xl 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(vws,{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(gws,{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 Sws({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-xl font-semibold",children:e})]}),t,n,r]})})}function zWt({redirectUri:e,onSuccess:t,initialMode:n="signin",errorMessage:r}){const{data:s,isLoading:a}=uc(),{mutate:i,isPending:l,error:c}=W2r(),{mutate:u,isPending:d,error:f}=G2r(),{mutate:h,isPending:p}=GDt(),[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,E=_.type==="sso"||_.type==="both",T=_.type==="credentials"||_.type==="both",N=_.sso,I=_.signUpEnabled!==!1,A=m==="signin"||!I,R=A?l:d,L=A?c:f,M=()=>{t?t():e?window.location.href=e:window.location.href=_G("/")},B=D=>{D.preventDefault(),A?i({email:x,password:k},{onSuccess:M}):u({email:x,password:k,name:y||void 0},{onSuccess:M})},V=()=>{h({redirectUri:e},{onSuccess:D=>{window.location.href=D.url}})},q=()=>{v(A?"signup":"signin")},F=_.description?o.jsxs("div",{className:"border-border1 bg-surface1 flex items-start gap-2.5 rounded-md border p-3",children:[o.jsx(Bd,{className:"text-neutral4 mt-0.5 h-4 w-4 shrink-0"}),o.jsx("p",{className:"text-neutral3 text-sm",children:_.description})]}):null,H=r?o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:r}):null;return o.jsxs(Sws,{title:A?"Sign in to Mastra Studio":"Create your account",description:F,errorBanner:H,children:[T&&o.jsxs("form",{onSubmit:B,className:"space-y-4",children:[!A&&o.jsxs("div",{className:"space-y-2",children:[o.jsx("label",{htmlFor:"name",className:"text-neutral4 block text-sm",children:"Name"}),o.jsx(jn,{id:"name",type:"text",value:y,onChange:D=>b(D.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 block text-sm",children:"Email"}),o.jsx(jn,{id:"email",type:"email",value:x,onChange:D=>w(D.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 block text-sm",children:"Password"}),o.jsx(jn,{id:"password",type:"password",value:k,onChange:D=>O(D.target.value),placeholder:A?"Enter your password":"Create a password",required:!0,variant:"default",size:"lg"})]}),L&&o.jsx("div",{className:"rounded-md bg-red-500/10 p-3 text-sm text-red-400",children:L.message}),o.jsx(oe,{type:"submit",disabled:R,className:"w-full",size:"lg",children:R?A?"Signing in...":"Creating account...":A?"Sign in":"Create account"}),I&&o.jsxs("div",{className:"text-center text-sm",children:[o.jsx("span",{className:"text-neutral3",children:A?"Don't have an account? ":"Already have an account? "}),o.jsx("button",{type:"button",onClick:q,className:"text-neutral6 hover:underline",children:A?"Sign up":"Sign in"})]})]}),E&&T&&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:"relative flex justify-center text-sm",children:o.jsx("span",{className:"bg-surface1 text-neutral3 px-2",children:"or continue with"})})]}),E&&N&&o.jsxs(oe,{onClick:V,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 kws(){const[e]=ya(),t=Kr(),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(zWt,{redirectUri:n,onSuccess:i,initialMode:s,errorMessage:a})}const yh=Ra.KeyValueList;function Ows(e){return e instanceof Date?e:new Date(e)}function Cws({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=Ows(e.timestamp),p=e.traceId,m=e.spanId;return o.jsxs(Ra,{collapsed:d,children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Log ",o.jsx("b",{children:mr(h,"MMM dd, HH:mm:ss.SSS")})]}),o.jsxs(ts,{className:"ml-auto shrink-0",children:[l&&o.jsx(oe,{size:"md",tooltip:d?"Expand panel":"Collapse panel",onClick:()=>f(!d),children:d?o.jsx(cI,{}):o.jsx(LV,{})}),o.jsxs(ts,{spacing:"close",children:[o.jsx(oe,{size:"md",tooltip:"Previous log",onClick:s,disabled:!s,children:o.jsx(KS,{})}),o.jsx(oe,{size:"md",tooltip:"Next log",onClick:a,disabled:!a,children:o.jsx(MV,{})})]}),o.jsx(Ra.CloseButton,{onClick:t})]})]}),!d&&o.jsxs(Ra.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(ts,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(oe,{size:"md",className:"min-w-0 flex-1 overflow-hidden",onClick:()=>n?.(p),children:[o.jsx(Mf,{}),o.jsx("span",{children:"Trace"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",p]})]}),o.jsx(Da,{content:p,size:"md",tooltip:"Copy Trace ID to clipboard"})]}),m&&o.jsxs(ts,{spacing:"close",className:"w-full min-w-0",children:[o.jsxs(oe,{size:"md",className:"min-w-0 flex-1 overflow-hidden",disabled:!p||!r,onClick:()=>p&&r?.(p,m),children:[o.jsx(Mf,{}),o.jsx("span",{children:"Span"}),o.jsxs("span",{className:"text-ui-sm text-neutral2 ml-auto min-w-0 truncate",children:["# ",m]})]}),o.jsx(Da,{content:m,size:"md",tooltip:"Copy Span ID to clipboard"})]})]}),o.jsxs(yh,{className:"mb-6",children:[e.entityType&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Entity Type"}),o.jsx(yh.Value,{children:e.entityType})]}),e.entityName&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Entity Name"}),o.jsx(yh.Value,{children:e.entityName})]}),e.serviceName&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Service"}),o.jsx(yh.Value,{children:e.serviceName})]}),e.environment&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Environment"}),o.jsx(yh.Value,{children:e.environment})]}),e.source&&o.jsxs(o.Fragment,{children:[o.jsx(yh.Key,{children:"Source"}),o.jsx(yh.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(yh.Key,{children:v}),o.jsx(yh.Value,{children:String(y)})]},v))})]}),e.data&&Object.keys(e.data).length>0&&o.jsx(Ra.CodeSection,{title:"Data",codeStr:JSON.stringify(e.data,null,2),className:"mt-6"})]})]})}function _ws({error:e,resource:t,errorTitle:n}){if(hs(e))return o.jsx(Es,{});if(ps(e))return o.jsx(Os,{resource:t});if(YL(e))return o.jsx(pr,{iconSlot:o.jsx(ks,{}),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(QL(e,"logs"))return o.jsx(pr,{iconSlot:o.jsx(ks,{}),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 Ews({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 Tws={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 jws({level:e}){const t=Tws[e];return o.jsx(lo,{children:o.jsx("span",{className:"text-ui-sm font-semibold uppercase",style:{color:t.color},children:t.label})})}function Nws({entityType:e,className:t}){const n=K("size-3.5 shrink-0 text-neutral2",t);switch(e.toLowerCase()){case"agent":return o.jsx(co,{className:n,"aria-hidden":!0});case"workflow":case"workflow_run":return o.jsx(Su,{className:n,"aria-hidden":!0});case"tool":return o.jsx(Uf,{className:n,"aria-hidden":!0});default:return null}}function Iws({entityType:e,entityName:t}){const n=e??"";return o.jsxs(lo,{className:"flex min-w-0 items-center gap-2",children:[o.jsx(Nws,{entityType:n}),t?o.jsx("span",{className:"text-ui-smd min-w-0 truncate",children:t}):"-"]})}function Aws({message:e}){return o.jsx(lo,{className:"text-ui-smd text-neutral4 min-w-0 truncate font-mono",children:e})}function Rws({data:e}){if(!e||Object.keys(e).length===0)return o.jsx(lo,{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(bTe,{font:"mono",children:t})}const Jl=Object.assign(WL,{Top:GL,TopCell:y1,TopCellWithTooltip:sG,TopCellSmart:_Mt,RowWrapper:STe,RowButton:ZL,RowLink:CMt,Spacer:kTe,NoMatch:rG,DateCell:SMt,TimeCell:kMt,LevelCell:jws,EntityCell:Iws,MessageCell:Aws,DataCell:Rws,NextPageLoading:nG}),Nnt="6rem 9rem 5rem 10rem minmax(8rem,1fr) minmax(8rem,1fr)",Pws=36,$ws=8;function Mws({logs:e,isLoading:t,isFetchingNextPage:n,hasNextPage:r,setEndOfListElement:s,logIdMap:a,featuredLogId:i,onLogClick:l}){const c=g.useRef(null),u=nWt({count:e.length,getScrollElement:()=>c.current,estimateSize:()=>Pws,overscan:$ws}),{getRowProps:d}=ol({count:e.length,containerRef:c,onNavigate:y=>u.scrollToIndex(y)}),f=g.useRef(t);if(g.useEffect(()=>{f.current&&!t&&c.current?.dispatchEvent(new Event("scroll")),f.current=t},[t]),t)return o.jsx(Do,{columns:Nnt});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:Nnt,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 Dws({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=>Lws(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] items-start gap-3"),children:[o.jsx(PRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ARe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function Lws(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 Fws={"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"},poe="MMM d, yyyy HH:mm",moe="Pick a wider range or lower the logging level — verbose entries (debug, info) may be filtered out.";function zws({datePreset:e,dateFrom:t,dateTo:n}){return e&&e!=="all"&&e!=="custom"?{title:`No logs for ${Fws[e]}`,description:moe}:t&&n?{title:`No logs between ${mr(t,poe)} and ${mr(n,poe)}`,description:moe}:t?{title:`No logs since ${mr(t,poe)}`,description:moe}:{title:"No logs yet",description:"Logs will appear here once agents, workflows, or tools are executed."}}const Bws=({datePreset:e,dateFrom:t,dateTo:n}={})=>{const{title:r,description:s}=zws({datePreset:e,dateFrom:t,dateTo:n});return o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),titleSlot:r,descriptionSlot:s,actionSlot:o.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/en/docs/observability/logging",target:"_blank",rel:"noopener noreferrer",children:["Logging Documentation ",o.jsx(Ds,{})]})})})},Uws=20,qws=1e4;function Vws(e,t,n){if(e?.pagination?.hasMore)return n+1}function Hws(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 Wws(e){return QL(e.state.error,"logs")||YL(e.state.error)?!1:qws}const Zws=({filters:e}={})=>{const t=Ze(),{inView:n,setRef:r}=s0(),s=Fy({queryKey:["logs",e],queryFn:({pageParam:h})=>t.listLogsVNext({pagination:{page:h,perPage:Uws},filters:e,orderBy:{field:"timestamp",direction:"DESC"}}),initialPageParam:0,getNextPageParam:Vws,select:Hws,retry:!1,refetchInterval:Wws}),{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}},v8={AGENT:"agent",WORKFLOW:"workflow_run",SCORER:"scorer",INGEST:"rag_ingestion"},BWt=[{label:"Agent",entityType:v8.AGENT},{label:"Workflow",entityType:v8.WORKFLOW},{label:"Scorer",entityType:v8.SCORER},{label:"Ingest",entityType:v8.INGEST}],Gws=[{label:"Debug",value:"debug"},{label:"Info",value:"info"},{label:"Warn",value:"warn"},{label:"Error",value:"error"},{label:"Fatal",value:"fatal"}],Kx="rootEntityType",nx="datePreset",rx="dateFrom",sx="dateTo",Qws=new Set(["all","last-24h","last-3d","last-7d","last-14d","last-30d","custom"]),Nl={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"},r5=Object.keys(Nl),HRe=new Set(["tags"]),WRe="mastra:logs:saved-filters";function Yws(e,t=WRe){const n=tSs(e),r=e.get(nx);r&&n.set(nx,r);const s=e.get(rx);s&&n.set(rx,s);const a=e.get(sx);a&&n.set(sx,a);try{localStorage.setItem(t,n.toString())}catch{}}function Kws(e=WRe){try{localStorage.removeItem(e)}catch{}}function Int(e=WRe){try{const t=localStorage.getItem(e);if(!t)return null;const n=new URLSearchParams(t);return n.toString()?n:null}catch{return null}}function Xws(e){if(e.has(nx)||e.has(rx)||e.has(sx)||e.has(Kx))return!0;for(const t of r5)if(e.has(Nl[t]))return!0;return!1}function Jws({availableTags:e,availableRootEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:BWt.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:Gws.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 eSs(e){const t=[],n=new Map([[Kx,"rootEntityType"]]);for(const s of r5)n.set(Nl[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),HRe.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 tSs(e){const t=new URLSearchParams,n=e.get(Kx);n&&t.set(Kx,n);for(const r of r5){const s=Nl[r];if(HRe.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 nSs(e,t){e.delete(Kx);for(const n of r5)e.delete(Nl[n]);for(const n of t){if(n.fieldId==="rootEntityType"&&typeof n.value=="string"){e.set(Kx,n.value);continue}const r=Nl[n.fieldId];if(r){if(HRe.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 rSs({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 sSs(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 aSs="Filters setting for Logs saved",iSs="Filters setting for Logs cleared up";function oSs(e,t,n){const{storageKey:r,messages:s,skipHydration:a}={},[i,l]=g.useState(()=>Int(r)!==null),c=g.useCallback(()=>{Yws(e,r),l(!0);const f=s?.saved??aSs;f!==!1&&Ve.success(f)},[e,r,s?.saved]),u=g.useCallback(()=>{Kws(r),l(!1);const f=s?.cleared??iSs;f!==!1&&Ve.success(f)},[r,s?.cleared]),d=g.useRef(!1);return g.useEffect(()=>{if(a||d.current||(d.current=!0,Xws(e)))return;const f=Int(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 lSs(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 cSs(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,lSs(`${r}${n.message??""}${n.data?JSON.stringify(n.data):""}`))}return t}function uSs(e,t,n,r){const s=g.useMemo(()=>cSs(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 E0e="logId",T0e="traceId",j0e="spanId",FP=1440*60*1e3,dSs={"last-24h":FP,"last-3d":3*FP,"last-7d":7*FP,"last-14d":14*FP,"last-30d":30*FP};function y8(e){e.delete(E0e),e.delete(T0e),e.delete(j0e)}function fSs(e,t,n){const{onRemoveAll:r}={},s=g.useMemo(()=>{const O=e.get(nx);return O&&Qws.has(O)?O:"last-24h"},[e]),a=e.get(rx),i=e.get(sx),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=dSs[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(E0e),f=e.get(T0e),h=e.get(j0e),p=g.useMemo(()=>BWt.find(O=>O.entityType===e.get(Kx)),[e]),m=g.useMemo(()=>eSs(e),[e]),v=g.useCallback(O=>{t(_=>{const E=new URLSearchParams(_);for(const[T,N]of Object.entries(O)){const I=T==="logId"?E0e:T==="traceId"?T0e:j0e;N?E.set(I,N):E.delete(I)}return E},{replace:!0})},[t]),y=g.useCallback(O=>{t(_=>{const E=new URLSearchParams(_);return nSs(E,O),y8(E),E},{replace:!0})},[t]),b=y,x=g.useCallback((O,_)=>{if(u.current!=="custom")return;const E=_==="from"?rx:sx;t(T=>{const N=new URLSearchParams(T);return O?N.set(E,O.toISOString()):N.delete(E),y8(N),N},{replace:!0})},[t]),w=g.useCallback(O=>{u.current=O,t(_=>{const E=new URLSearchParams(_);return O==="last-24h"?(E.delete(nx),E.delete(rx),E.delete(sx)):O==="custom"?E.set(nx,"custom"):(E.set(nx,O),E.delete(rx),E.delete(sx)),y8(E),E},{replace:!0})},[t]),k=g.useCallback(()=>{t(O=>{const _=new URLSearchParams(O);_.delete(Kx);for(const E of r5)_.delete(Nl[E]);return _.delete(nx),_.delete(rx),_.delete(sx),y8(_),_},{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 Ab=Ra.KeyValueList;function hSs({spanId:e,span:t,isLoading:n,onClose:r}){const s=uRe(t?.startedAt,t?.endedAt),a=gtt(t?.startedAt),i=gtt(t?.endedAt);return o.jsxs(Ra,{children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Span ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Ra.CloseButton,{onClick:r})]}),n?o.jsx(Ra.LoadingData,{children:"Loading span..."}):t?o.jsxs(Ra.Content,{children:[o.jsxs(Ab,{children:[t.spanType&&o.jsxs(o.Fragment,{children:[o.jsx(Ab.Key,{children:"Type"}),o.jsx(Ab.Value,{children:t.spanType})]}),a&&o.jsxs(o.Fragment,{children:[o.jsx(Ab.Key,{children:"Started"}),o.jsx(Ab.Value,{children:a})]}),i&&o.jsxs(o.Fragment,{children:[o.jsx(Ab.Key,{children:"Ended"}),o.jsx(Ab.Value,{children:i})]}),s&&o.jsxs(o.Fragment,{children:[o.jsx(Ab.Key,{children:"Duration"}),o.jsx(Ab.Value,{children:s})]})]}),o.jsx("br",{}),o.jsx(Ra.CodeSection,{title:"Input",icon:o.jsx(_O,{}),codeStr:JSON.stringify(t.input??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Output",icon:o.jsx(dy,{}),codeStr:JSON.stringify(t.output??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Metadata",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.metadata??null,null,2)}),o.jsx(Ra.CodeSection,{title:"Attributes",icon:o.jsx(nc,{}),codeStr:JSON.stringify(t.attributes??null,null,2)})]}):o.jsx(Ra.NoData,{children:"Span not found."})]})}function pSs({traceId:e,spans:t,isLoading:n,onClose:r,onSpanSelect:s,selectedSpanId:a}){const i=g.useMemo(()=>Y4(t??[]),[t]),[l,c]=g.useState([]);g.useEffect(()=>{i.length>0&&c(GQ(i))},[i]);const u=d=>{s?.(a===d?void 0:d)};return o.jsxs(Ra,{children:[o.jsxs(Ra.Header,{children:[o.jsxs(Ra.Heading,{children:["Trace ",o.jsxs("b",{children:["# ",e]})]}),o.jsx(Ra.CloseButton,{onClick:r})]}),n?o.jsx(Ra.LoadingData,{children:"Loading trace..."}):i.length===0?o.jsx(Ra.NoData,{children:"No spans found for this trace."}):o.jsx(Ra.Content,{children:o.jsx(pRe,{hierarchicalSpans:i,onSpanClick:u,selectedSpanId:a??void 0,expandedSpanIds:l,setExpandedSpanIds:c})})]})}function mSs(){const[e,t]=ya(),n=fSs(e,t),r=oSs(e,t),[s,a]=g.useState(),[i,l]=g.useState(!1),{data:c=[],isPending:u}=BRe(),{data:d=[],isPending:f}=LRe({entityType:n.selectedEntityOption?.entityType,rootOnly:!0}),{data:h=[],isPending:p}=FRe(),{data:m=[],isPending:v}=zRe(),y=g.useMemo(()=>Jws({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(()=>rSs({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:E}=Zws({filters:b}),{logIdMap:T,featuredLog:N,handleLogClick:I,handlePreviousLog:A,handleNextLog:R}=uSs(x,n.featuredLogId,n.handleFeaturedChange,n.featuredTraceId),{data:L,isLoading:M}=xA(n.featuredTraceId??null),{data:B,isLoading:V}=ZQ(n.featuredTraceId??"",n.featuredSpanId??""),q=g.useCallback(()=>n.applyFilterTokens(sSs(y,n.filterTokens)),[y,n]),F=g.useCallback(()=>n.handleFeaturedChange({logId:null}),[n]),H=g.useCallback(Y=>n.handleFeaturedChange({traceId:Y,spanId:null}),[n]),D=g.useCallback((Y,te)=>n.handleFeaturedChange({traceId:Y,spanId:te}),[n]),G=g.useCallback(()=>{n.handleFeaturedChange({traceId:null,spanId:null}),l(!1)},[n]),z=g.useCallback(()=>n.handleFeaturedChange({spanId:null}),[n]),$=g.useCallback(Y=>n.handleFeaturedChange({spanId:Y??null}),[n]),U=o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(KL,{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($Re,{fields:y,tokens:n.filterTokens,onTokensChange:n.handleFilterTokensChange,disabled:w,onStartTextFilter:a})]})}),o.jsx(Dws,{isLoading:w,filterFields:y,filterTokens:n.filterTokens,onFilterTokensChange:n.handleFilterTokensChange,onClear:q,onRemoveAll:n.handleRemoveAll,onSave:r.handleSave,onRemoveSaved:r.hasSavedFilters?r.handleRemoveSaved:void 0,autoFocusFilterFieldId:s})]});if(k)return o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(_ws,{error:k,resource:"logs",errorTitle:"Failed to load logs"})})]});const W=!!n.selectedEntityOption||n.filterTokens.length>0;return x.length===0&&!w&&!W?o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Lt.MainArea,{isCentered:!0,children:o.jsx(Bws,{datePreset:n.datePreset,dateFrom:n.selectedDateFrom,dateTo:n.selectedDateTo})})]}):o.jsxs(Lt,{width:"wide",height:"full",children:[U,o.jsx(Ews,{logCollapsed:i,listSlot:o.jsx(Mws,{logs:x,isLoading:w,isFetchingNextPage:O,hasNextPage:_,setEndOfListElement:E,logIdMap:T,featuredLogId:n.featuredLogId,onLogClick:I}),logPanelSlot:N?o.jsx(Cws,{log:N,onClose:F,onTraceClick:H,onSpanClick:D,onPrevious:A,onNext:R,collapsed:i,onCollapsedChange:l}):null,tracePanelSlot:n.featuredTraceId?o.jsx(pSs,{traceId:n.featuredTraceId,spans:L?.spans,isLoading:M,onClose:G,onSpanSelect:$,selectedSpanId:n.featuredSpanId}):null,spanPanelSlot:n.featuredTraceId&&n.featuredSpanId?o.jsx(hSs,{spanId:n.featuredSpanId,span:B?.span,isLoading:V,onClose:z}):null})]})}function gSs({server:e,rowProps:t}){const{paths:n,Link:r}=ln(),a=Ze().options.baseUrl,i=a?`${a}/api/mcp/${e.id}/sse`:"",{data:l}=vqt(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=Rd(e.name,50);return o.jsxs(ve.RowLink,{to:n.mcpServerLink(e.id),LinkComponent:r,...t,children:[o.jsx(ve.NameCell,{children:h}),o.jsx(ve.DescriptionCell,{children:i}),o.jsx(ve.TextCell,{className:"text-center",children:d||""}),o.jsx(ve.TextCell,{className:"text-center",children:u||""}),o.jsx(ve.TextCell,{className:"text-center",children:f||""})]})}function vSs({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}=ol({count:r.length});return t?o.jsx(Do,{columns:"auto 1fr auto auto auto"}):o.jsxs(ve,{columns:"auto 1fr auto auto auto",scrollRef:s,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"URL"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(co,{}),tooltip:"Agent Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Tools",short:o.jsx(Uf,{}),tooltip:"Tools",className:"text-center"}),o.jsx(ve.TopCellSmart,{long:"Workflows",short:o.jsx(Su,{}),tooltip:"Workflow Tools",className:"text-center"})]}),r.length===0&&n?o.jsx(ve.NoMatch,{message:"No MCP Servers match your search"}):null,r.map((i,l)=>o.jsx(gSs,{server:i,rowProps:a(l)},i.id))]})}const ySs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),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.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/tools-mcp/mcp-overview",target:"_blank",rel:"noopener noreferrer",children:["MCP Documentation ",o.jsx(Ds,{})]})})}),bSs=()=>{const{data:e=[],isLoading:t,error:n}=DQ(),[r,s]=g.useState("");return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Es,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"MCP servers"})}):n?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load MCP servers",message:n.message})}):e.length===0&&!t?o.jsx(Zn,{children:o.jsx(ySs,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx("div",{className:"max-w-120",children:o.jsx(Uc,{onSearch:s,label:"Filter MCP servers",placeholder:"Filter by name"})})}),o.jsx(vSs,{mcpServers:e,isLoading:t,search:r})]})},xSs=(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 wSs({tools:e,agents:t,isLoading:n,search:r=""}){const{paths:s,Link:a}=ln(),i=g.useMemo(()=>xSs(e,t),[e,t]),l=g.useMemo(()=>i.filter(d=>d.id.toLowerCase().includes(r.toLowerCase())),[i,r]),{containerRef:c,getRowProps:u}=ol({count:l.length});return n?o.jsx(Do,{columns:"auto 1fr auto"}):o.jsxs(ve,{columns:"auto 1fr auto",scrollRef:c,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Name"}),o.jsx(ve.TopCell,{children:"Description"}),o.jsx(ve.TopCellSmart,{long:"Agents",short:o.jsx(co,{}),tooltip:"Attached Agents",className:"text-center"})]}),l.length===0&&r?o.jsx(ve.NoMatch,{message:"No Tools match your search"}):null,l.map((d,f)=>{const h=Rd(d.id,50),p=Rd(d.description??"",200),m=d.agents.length;return o.jsxs(ve.RowLink,{to:s.toolLink(d.id),LinkComponent:a,...u(f),children:[o.jsx(ve.NameCell,{children:h}),o.jsx(ve.DescriptionCell,{children:p}),o.jsx(ve.TextCell,{className:"text-center",children:m||""})]},d.id)})]})}const SSs=()=>o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),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.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/agents/using-tools-and-mcp",target:"_blank",rel:"noopener noreferrer",children:["Tools Documentation ",o.jsx(Ds,{})]})})}),kSs=()=>{const e=Ze();return bn({mutationFn:async({toolId:t,input:n,requestContext:r})=>{const s=new qC;Object.entries(r??{}).forEach(([a,i])=>{s.set(a,i)});try{return await e.getTool(t).execute({data:n,requestContext:s})}catch(a){throw Ve.error("Error executing dev tool"),console.error("Error executing dev tool:",a),a}}})},OSs=({toolId:e})=>{const{canExecute:t}=Vo(),n=t("tools"),{data:r={}}=zm(),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}=i2r(e,{enabled:!s}),c=s||a,{mutateAsync:u,isPending:d,data:f}=kSs(),{requestContext:h}=vs();g.useEffect(()=>{if(l){const v=l instanceof Error?l.message:"Failed to load tool";Ve.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?bm(Ax(c?.inputSchema)):xs({});return i?o.jsxs("div",{className:"p-6",children:[o.jsx(wt,{className:"mb-4 h-8 w-48"}),o.jsx(wt,{className:"h-32 w-full"})]}):l?null:c?n?o.jsx(ZAe,{executionResult:f,isExecutingTool:d,zodInputSchema:m,handleExecuteTool:p,toolDescription:c.description,toolId:c.id,requestContextSchema:c.requestContextSchema}):o.jsx("div",{className:"px-6 py-12 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-6 py-12 text-center",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})})};function CSs({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}){const{data:u={},isLoading:d,isError:f,error:h}=aA(),{data:p={},isLoading:m,isError:v,error:y}=zm(),{navigate:b,paths:x}=ln();g.useEffect(()=>{if(f){const _=h instanceof Error?h.message:"Failed to load tools";Ve.error(`Error loading tools: ${_}`)}},[f,h]),g.useEffect(()=>{if(v){const _=y instanceof Error?y.message:"Failed to load agents";Ve.error(`Error loading agents: ${_}`)}},[v,y]);const w=new Map;Object.values(p).forEach(_=>{_.tools&&Object.values(_.tools).forEach(E=>{w.has(E.id)||w.set(E.id,E)})}),Object.values(u).forEach(_=>{w.has(_.id)||w.set(_.id,_)});const k=Array.from(w.values()).map(_=>({label:_.id,value:_.id})),O=_=>{t?t(_):_&&_!==e&&b(x.toolLink(_))};return o.jsx(Fo,{options:k,value:e,onValueChange:O,placeholder:d||m?"Loading tools...":n,searchPlaceholder:r,emptyText:s,className:a,disabled:i||d||m||f||v,variant:l,size:c})}const _Ss=({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(Ox,{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(Ox,{isDivided:!0,children:[o.jsxs("div",{className:"mx-auto w-full max-w-2xl px-8 py-12",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-6",children:[o.jsx(yt,{icon:o.jsx(YVt,{}),size:"sm",children:"Version"}),o.jsx(yt,{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(yt,{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(Da,{tooltip:"Copy HTTP Stream URL",content:r})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(yt,{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(Da,{tooltip:"Copy SSE URL",content:n})})]})]}),o.jsxs("div",{className:"border-border1 bg-surface3 rounded-lg border p-4",children:[o.jsx(yt,{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(Da,{tooltip:"Copy Command Line Config",content:a})})]})]})]})]}),o.jsx("div",{className:"border-border1 h-full overflow-y-scroll border-l",children:o.jsx(ESs,{server:t})})]})},ESs=({server:e})=>{const{data:t={},isLoading:n}=vqt(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(Je,{size:"lg",className:"bg-surface4 rounded-md p-1",children:o.jsx(R_,{})}),o.jsx(ge,{variant:"header-md",as:"h2",className:"font-medium",children:"Available Tools"})]}),o.jsx("div",{className:"flex flex-col gap-2 pt-6",children:r.map(s=>{const a=t[s];return o.jsx(jSs,{tool:a,serverId:e.id},s)})})]})};function TSs(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 jSs=({tool:e,serverId:t})=>{const n=g.useRef(null),{Link:r,paths:s}=ln(),a=_qt[e.toolType||"tool"],i=TSs(e._meta);return o.jsxs(Gf,{onClick:()=>n.current?.click(),children:[o.jsx(GLt,{children:o.jsx(a,{className:"group-hover/entity:text-accent6"})}),o.jsxs(Yf,{children:[o.jsx(Qf,{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(yt,{size:"xs",children:"App"})]})}),o.jsx(cp,{children:e.description})]})]})},NSs=()=>{const{serverId:e}=ur(),{data:t=[],isLoading:n}=DQ(),r=t.find(s=>s.id===e);return o.jsx("div",{className:"h-full w-full overflow-hidden",children:o.jsx(_Ss,{isLoading:n,server:r})})};function ISs(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 ASs=({toolId:e,serverId:t})=>{const{canExecute:n}=Vo(),r=n("tools"),s=Ze(),{data:a,isLoading:i,error:l}=WAe(t,e),{mutateAsync:c,isPending:u,data:d}=ils(t,e),f=a?ISs(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";Ve.error(`Error loading tool: ${y}`)}},[l]);const m=async y=>{if(a)return await c(y)};if(i)return o.jsxs("div",{className:"p-6",children:[o.jsx(wt,{className:"mb-4 h-8 w-48"}),o.jsx(wt,{className:"h-32 w-full"})]});if(l)return null;if(!a)return o.jsx("div",{className:"px-6 py-12 text-center",children:o.jsx(ge,{variant:"header-md",className:"text-neutral3",children:"Tool not found"})});if(!r)return o.jsx("div",{className:"px-6 py-12 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=bm(a.inputSchema)}catch(y){console.error("Error processing input schema:",y),Ve.error("Failed to process tool input schema."),v=xs({})}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(gqt,{html:h,toolName:a.name??a.id,onToolCall:p})}),o.jsx(ZAe,{executionResult:d,isExecutingTool:u,zodInputSchema:v,handleExecuteTool:m,toolDescription:a.description||"",toolId:a.id})]})},RSs=()=>{const{serverId:e,toolId:t}=ur(),{data:n,isLoading:r}=WAe(e,t);return r||!n?null:o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(ASs,{toolId:t,serverId:e})})},UWt=[{label:"Agent",entityType:"agent"},{label:"Workflow",entityType:"workflow_run"},{label:"Scorer",entityType:"scorer"},{label:"Ingest",entityType:"rag_ingestion"}],rI="rootEntityType",sI={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"},bY=Object.keys(sI),ZRe="mastra:metrics:saved-filters";function PSs(e){const t=FSs(e);try{localStorage.setItem(ZRe,t.toString())}catch{}}function $Ss(){try{localStorage.removeItem(ZRe)}catch{}}function qWt(){try{const e=localStorage.getItem(ZRe);if(!e)return null;const t=new URLSearchParams(e);return t.toString()?t:null}catch{return null}}function MSs(e){if(e.has(rI))return!0;for(const t of bY)if(e.has(sI[t]))return!0;return!1}function DSs({availableTags:e,availableEntityNames:t,availableServiceNames:n,availableEnvironments:r,loading:s}){const a=[{id:"rootEntityType",label:"Primitive Type",kind:"pick-multi",searchable:!1,options:UWt.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 LSs(e){const t=[],n=new Map([[rI,"rootEntityType"]]);for(const s of bY)n.set(sI[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 FSs(e){const t=new URLSearchParams,n=e.getAll(rI);for(const r of n)t.append(rI,r);for(const r of bY){const s=sI[r],a=e.getAll(s);for(const i of a)t.append(s,i)}return t}function zSs(e,t){e.delete(rI);for(const n of bY)e.delete(sI[n]);for(const n of t){const r=n.fieldId==="rootEntityType"?rI:sI[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 BSs="Any";function Ant(e){const t=e.trim();return t===""||t===BSs}const USs=new Set(UWt.map(e=>e.entityType));function Rnt(e){const t=e.trim();return USs.has(t)?t:void 0}function qSs(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=>!Ant(a));if(s.length===0)continue;if(r==="tags")t.tags=s;else if(r==="rootEntityType"){const a=s[0],i=a!==void 0?Rnt(a):void 0;i&&(t.rootEntityType=i)}else t[r]=s[0]}else if(typeof n.value=="string"){if(Ant(n.value))continue;const s=n.value.trim();if(r==="rootEntityType"){const a=Rnt(s);a&&(t.rootEntityType=a)}else t[r]=s}}return t}const VWt=[{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"}],VSs=new Set(VWt.map(e=>e.value));function HSs(e){return typeof e=="string"&&(VSs.has(e)||e==="custom")}const HWt=g.createContext({datePreset:"24h",setDatePreset:()=>{},customRange:void 0,setCustomRange:()=>{},dateRangeLabel:"Last 24 hours",filterTokens:[],setFilterTokens:()=>{},dimensionalFilter:{},dimensionalFilterKey:"{}",tracesBasePath:void 0,logsBasePath:void 0});function xY(){return g.useContext(HWt)}function WSs(e,t){return e!=="custom"?VWt.find(n=>n.value===e)?.label??e:t?.from?t.to?`${mr(t.from,"MMM d, yyyy")} – ${mr(t.to,"MMM d, yyyy")}`:mr(t.from,"MMM d, yyyy"):"Custom range"}function ZSs({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(()=>qSs(d),[d]),h=g.useMemo(()=>JSON.stringify(f),[f]),p=WSs(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(HWt.Provider,{value:m,children:e})}const GSs=["last-24h","last-3d","last-7d","last-14d","last-30d","custom"];function QSs(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 YSs(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 KSs(){const{datePreset:e,setDatePreset:t,customRange:n,setCustomRange:r}=xY(),s=g.useRef(e);s.current=e;const a=g.useRef(n);return a.current=n,o.jsx(KL,{preset:QSs(e),onPresetChange:i=>{const l=YSs(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:GSs})}const N0e=1440*60*1e3,XSs={"24h":N0e,"3d":4320*60*1e3,"7d":10080*60*1e3,"14d":336*60*60*1e3,"30d":720*60*60*1e3};function JSs(e,t,n){if(e!=="custom"){const r=XSs[e]??N0e;return{start:new Date(n-r),end:new Date(n)}}return{start:t?.from??new Date(n-N0e),end:t?.to??new Date(n)}}function Vm(){const{datePreset:e,customRange:t,dimensionalFilter:n,dimensionalFilterKey:r}=xY(),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(()=>JSs(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 WWt(){const e=Ze(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","agent-runs-kpi",n],queryFn:()=>e.getMetricAggregate({name:["mastra_agent_duration_ms"],aggregation:"count",filters:t,comparePeriod:"previous_period"})})}function s5({href:e,LinkComponent:t="a"}){return o.jsx(oe,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View in Traces","aria-label":"View in Traces",children:o.jsx(Ec,{})})}function e1s({href:e,LinkComponent:t="a"}){return o.jsx(oe,{as:t,href:e,variant:"ghost",size:"icon-md",tooltip:"View errors in Logs","aria-label":"View errors in Logs",children:o.jsx(oen,{})})}function t1s(e){return e==="agents"||e==="workflows"||e==="tools"}function Pnt(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 n1s(e){const t=e;return typeof t?.tsMs=="number"&&Number.isFinite(t.tsMs)}const r1s=[{dataKey:"p50",label:"p50",color:Gh.blue,aggregate:e=>({value:Pnt(e,"p50"),suffix:"avg ms"})},{dataKey:"p95",label:"p95",color:Gh.yellow,aggregate:e=>({value:Pnt(e,"p95"),suffix:"avg ms"})}];function goe({data:e,onPointClick:t}){return e.length===0?o.jsx(qt.NoData,{message:"No latency data yet"}):o.jsx(LD,{data:e,series:r1s,onPointClick:t?n=>n1s(n)?t(n):void 0:void 0})}function s1s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Latency",description:"Hourly p50 and p95 latency."}),m&&o.jsx(qt.Summary,{value:y,label:"Avg p50"}),p?o.jsx(qt.Actions,{children:p}):null]}),t?o.jsx(qt.Loading,{}):n?o.jsx(qt.Error,{message:"Failed to load latency data"}):o.jsx(qt.Content,{children:m?o.jsxs(wl,{value:h,onValueChange:b=>{t1s(b)&&c[b]&&f(b)},defaultTab:u,className:"overflow-visible",children:[o.jsxs(xl,{children:[o.jsx(wr,{value:"agents",disabled:!a,disabledTooltip:"No agent latency data for this period",children:"Agents"}),o.jsx(wr,{value:"workflows",disabled:!i,disabledTooltip:"No workflow latency data for this period",children:"Workflows"}),o.jsx(wr,{value:"tools",disabled:!l,disabledTooltip:"No tool latency data for this period",children:"Tools"})]}),o.jsx(Qr,{value:"agents",children:o.jsx(goe,{data:e.agentData,onPointClick:r?b=>r("agents",b):void 0})}),o.jsx(Qr,{value:"workflows",children:o.jsx(goe,{data:e.workflowData,onPointClick:r?b=>r("workflows",b):void 0})}),o.jsx(Qr,{value:"tools",children:o.jsx(goe,{data:e.toolData,onPointClick:r?b=>r("tools",b):void 0})})]}):o.jsx(qt.NoData,{message:"No latency data yet"})})]})}function a1s(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 i1s(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 ZWt(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=a1s(s);l&&e.set(t,l)}function Io(e,t,n){typeof n=="string"&&n.length>0&&e.set(t,n)}function GWt(e,t,n){if(!(!Array.isArray(n)||n.length===0))for(const r of n)r&&e.append(t,r)}function $nt({preset:e,customRange:t,dashboardFilter:n,scope:r,tracesBasePath:s="/traces"}){const a=new URLSearchParams;a.set(Bw,"branches"),ZWt(a,Uw,VT,HT,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Qx,i),r.status&&a.set(Yx,r.status),Io(a,jl.entityName,r.entityName??n.entityName),Io(a,jl.threadId,r.threadId??n.threadId),Io(a,jl.resourceId,r.resourceId??n.resourceId),Io(a,jl.entityId,n.entityId),Io(a,jl.runId,n.runId),Io(a,jl.sessionId,n.sessionId),Io(a,jl.requestId,n.requestId),Io(a,jl.userId,n.userId),Io(a,jl.organizationId,n.organizationId),Io(a,jl.experimentId,n.experimentId),Io(a,jl.serviceName,n.serviceName),Io(a,jl.environment,n.environment),GWt(a,jl.tags,n.tags);const l=a.toString();return l?`${s}?${l}`:s}function o1s({preset:e,customRange:t,dashboardFilter:n,scope:r,logsBasePath:s="/logs"}){const a=new URLSearchParams;ZWt(a,nx,rx,sx,e,t,r.window);const i=r.rootEntityType??n.rootEntityType;i&&a.set(Kx,i),Io(a,Nl.entityName,r.entityName??n.entityName),Io(a,Nl.threadId,r.threadId??n.threadId),Io(a,Nl.resourceId,r.resourceId??n.resourceId),Io(a,Nl.runId,n.runId),Io(a,Nl.sessionId,n.sessionId),Io(a,Nl.requestId,n.requestId),Io(a,Nl.userId,n.userId),Io(a,Nl.organizationId,n.organizationId),Io(a,Nl.experimentId,n.experimentId),Io(a,Nl.serviceName,n.serviceName),Io(a,Nl.environment,n.environment),GWt(a,Nl.tags,n.tags),r.status==="error"&&a.append(Nl.level,"error");const l=a.toString();return l?`${s}?${l}`:s}function TA(){const{datePreset:e,customRange:t,dimensionalFilter:n,tracesBasePath:r,logsBasePath:s}=xY(),a=g.useCallback((c={})=>$nt({preset:e,customRange:t,dashboardFilter:n,scope:c,tracesBasePath:r}),[e,t,n,r]),i=g.useCallback((c={})=>o1s({preset:e,customRange:t,dashboardFilter:n,scope:c,logsBasePath:s}),[e,t,n,s]),l=g.useCallback((c,u,d)=>{const f=i1s(u,d);return $nt({preset:e,customRange:t,dashboardFilter:n,scope:{...c,window:f},tracesBasePath:r})},[e,t,n,r]);return{getTracesHref:a,getLogsHref:i,getBucketTracesHref:l}}const QWt="1h";async function voe(e,t,n){const r=await e.getMetricPercentiles({name:t,percentiles:[.5,.95],interval:QWt,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 l1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","latency",n],queryFn:async()=>{const[r,s,a]=await Promise.all([voe(e,"mastra_agent_duration_ms",t),voe(e,"mastra_workflow_duration_ms",t),voe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a,interval:QWt}}})}const Mnt={agents:Yu.AGENT,workflows:Yu.WORKFLOW_RUN,tools:Yu.TOOL};function c1s(){const{data:e,isLoading:t,isError:n}=l1s(),{getTracesHref:r,getBucketTracesHref:s}=TA(),{Link:a}=ln(),i=Kr();return o.jsx(s1s,{data:e,isLoading:t,isError:n,onPointClick:(l,c)=>{Number.isFinite(c.tsMs)&&i(s({rootEntityType:Mnt[l]},c.tsMs,"1h"))},actions:l=>o.jsx(s5,{href:r({rootEntityType:Mnt[l]}),LinkComponent:a})})}function u1s(e){return e==="threads"||e==="resources"}function yoe(e){return e.length<=12?e:`${e.slice(0,6)}…${e.slice(-4)}`}function d1s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Memory",description:"Resource and Thread consumption"}),i==="threads"&&d&&o.jsx(qt.Summary,{value:h.toLocaleString(),label:"Total runs"}),i==="resources"&&f&&o.jsx(qt.Summary,{value:p.toLocaleString(),label:"Total threads"}),v?o.jsx(qt.Actions,{children:v}):null]}),m.isLoading?o.jsx(qt.Loading,{}):m.isError?o.jsx(qt.Error,{message:"Failed to load memory data"}):o.jsx(qt.Content,{children:o.jsxs(wl,{defaultTab:"threads",value:i,onValueChange:y=>{u1s(y)&&l(y)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(xl,{children:[o.jsx(wr,{value:"threads",children:"Threads"}),o.jsx(wr,{value:"resources",children:"Resources"})]}),o.jsx(Qr,{value:"threads",children:d?o.jsxs(ve,{columns:"auto auto auto auto auto",...f0e,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Thread ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Runs"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),c.map(y=>{const b=n?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{className:"text-ui-sm",children:yoe(y.threadId)}),o.jsx(ve.NumberCell,{children:y.resourceId?yoe(y.resourceId):"—"}),o.jsx(ve.NumberCell,{highlight:!0,children:y.runs.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?to(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Fd(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ve.RowStatic,{children:x},y.key)})]}):o.jsx(qt.NoData,{message:"No thread activity yet"})}),o.jsx(Qr,{value:"resources",children:f?o.jsxs(ve,{columns:"auto auto auto auto",...f0e,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Resource ID"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Threads"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Tokens"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),u.map(y=>{const b=r?.(y),x=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{className:"text-ui-sm",children:yoe(y.resourceId)}),o.jsx(ve.NumberCell,{highlight:!0,children:y.threadCount.toLocaleString()}),o.jsx(ve.NumberCell,{children:y.tokens>0?to(y.tokens):"—"}),o.jsx(ve.NumberCell,{children:y.cost!=null?Fd(y.cost,y.costUnit):"—"})]});return b?o.jsx(ve.RowLink,{to:b,LinkComponent:a,children:x},y.key):o.jsx(ve.RowStatic,{children:x},y.key)})]}):o.jsx(qt.NoData,{message:"No resource activity yet"})})]})})]})}const boe=20;function f1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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:boe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:boe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:boe})]),l=new Map,c=d=>wA(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 xoe=20;function h1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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:xoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_input_tokens"],aggregation:"sum",limit:xoe}),e.getMetricBreakdown({...r,name:["mastra_model_total_output_tokens"],aggregation:"sum",limit:xoe})]),l=new Map,c=d=>wA(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 p1s(){const e=f1s(),t=h1s(),{getTracesHref:n}=TA(),{Link:r}=ln();return o.jsx(d1s,{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 a5({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 m1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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 g1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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 v1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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 y1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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 b1s(){const{data:e,isLoading:t,isError:n}=WWt();return o.jsx(a5,{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 x1s(){const{data:e,isLoading:t,isError:n}=v1s();return o.jsx(a5,{label:"Total Model Cost",value:e?.cost!=null?Fd(e.cost,e.costUnit):null,prevValue:e?.previousCost!=null?Fd(e.previousCost,e.costUnit):void 0,changePct:e?.costChangePercent??null,isLoading:t,isError:n})}function w1s(){const{data:e,isLoading:t,isError:n}=y1s();return o.jsx(a5,{label:"Total Tokens",value:e?.value!=null?to(e.value):null,prevValue:e?.previousValue!=null?to(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function S1s(){const{data:e,isLoading:t,isError:n}=g1s();return o.jsx(a5,{label:"Total Threads",value:e?.value!=null?to(e.value):null,prevValue:e?.previousValue!=null?to(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function k1s(){const{data:e,isLoading:t,isError:n}=m1s();return o.jsx(a5,{label:"Total Resources",value:e?.value!=null?to(e.value):null,prevValue:e?.previousValue!=null?to(e.previousValue):void 0,changePct:e?.changePercent??null,isLoading:t,isError:n})}function O1s({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=>C1s(f,a));return o.jsxs("div",{className:K("grid grid-cols-[1fr_auto] gap-3 items-start"),children:[o.jsx(PRe,{fields:a,tokens:i,onTokensChange:l,disabled:s,autoFocusFieldId:c}),u&&o.jsx(ARe,{disabled:s,onClear:d?e:void 0,onRemoveAll:t,onSave:n,onRemoveSaved:r})]})}function C1s(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 _1s({rows:e,isLoading:t,isError:n,getRowHref:r,actions:s,LinkComponent:a}){const i=!!e&&e.length>0;return o.jsxs(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.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?Fd(l):"—":c.size===1?u=l>0?Fd(l,[...c][0]):"—":u="Mixed",o.jsx(qt.Summary,{value:u,label:"Total cost"})})(),s?o.jsx(qt.Actions,{children:s}):null]}),t?o.jsx(qt.Loading,{}):n?o.jsx(qt.Error,{message:"Failed to load model usage data"}):o.jsx(qt.Content,{children:i?o.jsxs(ve,{columns:"auto auto auto auto auto auto",...f0e,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{sticky:"start",children:"Model"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Input"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Output"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Read"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cache Write"}),o.jsx(ve.TopCell,{className:"justify-end text-right",children:"Cost"})]}),e.map(l=>{const c=r?.(l),u=o.jsxs(o.Fragment,{children:[o.jsx(ve.RowHeaderCell,{className:"text-ui-sm",children:l.model}),o.jsx(ve.NumberCell,{children:l.input}),o.jsx(ve.NumberCell,{children:l.output}),o.jsx(ve.NumberCell,{children:l.cacheRead}),o.jsx(ve.NumberCell,{children:l.cacheWrite}),o.jsx(ve.NumberCell,{highlight:!0,children:l.cost!=null?Fd(l.cost,l.costUnit):"—"})]});return c?o.jsx(ve.RowLink,{to:c,LinkComponent:a,children:u},l.model):o.jsx(ve.RowStatic,{children:u},l.model)})]}):o.jsx(qt.NoData,{message:"No model usage data yet"})})]})}function E1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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=>wA(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:to(f.input),output:to(f.output),cacheRead:to(f.cacheRead),cacheWrite:to(f.cacheWrite),cost:f.cost,costUnit:f.costUnit})).sort((d,f)=>d.model.localeCompare(f.model))}})}function T1s(){const{data:e,isLoading:t,isError:n}=E1s(),{getTracesHref:r}=TA(),{Link:s}=ln();return o.jsx(_1s,{rows:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:()=>r({rootEntityType:Yu.AGENT}),actions:o.jsx(s5,{href:r({rootEntityType:Yu.AGENT}),LinkComponent:s})})}function j1s(e){return e==="tokens"||e==="cost"}function N1s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Token Usage by Agent",description:"Token consumption grouped by agent."}),u&&(i==="cost"&&y?o.jsx(qt.Summary,{value:Fd(v,m),label:"Total cost"}):o.jsx(qt.Summary,{value:to(d),label:"Total tokens"})),u&&s?o.jsx(qt.Actions,{children:s}):null]}),t?o.jsx(qt.Loading,{}):n?o.jsx(qt.Error,{message:"Failed to load token usage data"}):o.jsx(qt.Content,{children:u?o.jsxs(wl,{defaultTab:"tokens",value:i,onValueChange:b=>{j1s(b)&&l(b)},className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(xl,{children:[o.jsx(wr,{value:"tokens",children:"Tokens"}),o.jsx(wr,{value:"cost",children:"Cost"})]}),o.jsx(Qr,{value:"tokens",children:o.jsx(nI,{LinkComponent:a,data:c.map(b=>({name:b.name,values:[b.input,b.output],href:r?.(b)})),segments:[{label:"Input",color:Gh.blueDark},{label:"Output",color:Gh.blue}],maxVal:Math.max(...c.map(b=>b.input+b.output)),fmt:to})}),o.jsx(Qr,{value:"cost",children:y?o.jsx(nI,{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:Gh.purple}],maxVal:Math.max(...f.map(b=>b.cost??0)),fmt:b=>Fd(b,m)}):o.jsx(qt.NoData,{message:"No cost data yet"})})]}):o.jsx(qt.NoData,{message:"No token usage data yet"})})]})}function I1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();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=>wA(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 A1s(){const{data:e,isLoading:t,isError:n}=I1s(),{getTracesHref:r}=TA(),{Link:s}=ln();return o.jsx(N1s,{data:e,isLoading:t,isError:n,LinkComponent:s,getRowHref:a=>r({rootEntityType:Yu.AGENT,entityName:a.name}),actions:o.jsx(s5,{href:r({rootEntityType:Yu.AGENT}),LinkComponent:s})})}function I0e(e,t=to){return n=>({value:t(n.reduce((r,s)=>r+(typeof s[e]=="number"?s[e]:0),0))})}const R1s=[{dataKey:"input",label:"Input tokens",color:Gh.blue,aggregate:I0e("input")},{dataKey:"output",label:"Output tokens",color:Gh.yellow,aggregate:I0e("output")}];function P1s(e){return e==="tokens"||e==="cost"}function $1s({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:Gh.purple,aggregate:I0e("cost",k=>Fd(k,v))}];return o.jsxs(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Token usage over time",description:x}),u&&(a==="cost"&&b?o.jsx(qt.Summary,{value:Fd(y,v),label:"Total cost"}):o.jsx(qt.Summary,{value:to(d),label:"Total tokens"})),u&&s?o.jsx(qt.Actions,{children:s}):null]}),n?o.jsx(qt.Loading,{}):r?o.jsx(qt.Error,{message:"Failed to load token usage timeline"}):o.jsx(qt.Content,{children:u?o.jsxs(wl,{defaultTab:"tokens",value:a,onValueChange:k=>{P1s(k)&&i(k)},className:"overflow-visible",children:[o.jsxs(xl,{children:[o.jsx(wr,{value:"tokens",children:"Tokens"}),o.jsx(wr,{value:"cost",children:"Cost"})]}),o.jsx(Qr,{value:"tokens",children:o.jsx(LD,{data:c,series:R1s})}),o.jsx(Qr,{value:"cost",children:b?o.jsx(LD,{data:h,series:w}):o.jsx(qt.NoData,{message:"No cost data yet"})})]}):o.jsx(qt.NoData,{message:"No token usage data yet"})})]})}function M1s(e){return e==="24h"?"1h":"1d"}function D1s(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 Dnt(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 L1s(e){return e.cost==null||e.hasUnknownCostUnit||e.costUnits.size!==1?null:[...e.costUnits][0]??null}function F1s(){const e=Ze(),{datePreset:t,filters:n,filterKey:r}=Vm(),s=M1s(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 Dnt(l,a.series[0],"input"),Dnt(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:D1s(d,s),tsMs:u.tsMs,input:u.input,output:u.output,total:u.input+u.output,cost:u.cost,costUnit:L1s(u)}}),interval:s}}})}function z1s(){const{data:e,isLoading:t,isError:n}=F1s(),{getTracesHref:r}=TA(),{Link:s}=ln();return o.jsx($1s,{data:e?.data,interval:e?.interval,isLoading:t,isError:n,actions:o.jsx(s5,{href:r(),LinkComponent:s})})}function woe({data:e,rowHrefs:t,errorHrefs:n,LinkComponent:r}){return o.jsx(nI,{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:Gh.blueDark},{label:"Errors",color:Gh.pink}],maxVal:Math.max(...e.map(s=>s.completed+s.errors)),fmt:to})}function B1s({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(qt,{children:[o.jsxs(qt.TopBar,{children:[o.jsx(qt.TitleAndDescription,{title:"Trace Volume",description:"Runs and call counts."}),d&&o.jsx(qt.Summary,{value:to(f),label:"Total runs"}),u?o.jsx(qt.Actions,{children:u}):null]}),t?o.jsx(qt.Loading,{}):n?o.jsx(qt.Error,{message:"Failed to load trace volume data"}):o.jsx(qt.Content,{children:d?o.jsxs(wl,{value:l,onValueChange:c,defaultTab:"agents",className:"grid h-full grid-rows-[auto_1fr] overflow-y-auto",children:[o.jsxs(xl,{children:[o.jsx(wr,{value:"agents",children:"Agents"}),o.jsx(wr,{value:"workflows",children:"Workflows"}),o.jsx(wr,{value:"tools",children:"Tools"})]}),o.jsx(Qr,{value:"agents",children:e.agentData.length>0?o.jsx(woe,{data:e.agentData,rowHrefs:h("agents"),errorHrefs:p("agents"),LinkComponent:i}):o.jsx(qt.NoData,{message:"No agent data yet"})}),o.jsx(Qr,{value:"workflows",children:e.workflowData.length>0?o.jsx(woe,{data:e.workflowData,rowHrefs:h("workflows"),errorHrefs:p("workflows"),LinkComponent:i}):o.jsx(qt.NoData,{message:"No workflow data yet"})}),o.jsx(Qr,{value:"tools",children:e.toolData.length>0?o.jsx(woe,{data:e.toolData,rowHrefs:h("tools"),errorHrefs:p("tools"),LinkComponent:i}):o.jsx(qt.NoData,{message:"No tool data yet"})})]}):o.jsx(qt.NoData,{message:"No trace volume data yet"})})]})}async function Soe(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=wA(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 U1s(){const e=Ze(),{filters:t,filterKey:n}=Vm();return mt({queryKey:["metrics","trace-volume",n],queryFn:async()=>{const[r,s,a]=await Promise.all([Soe(e,"mastra_agent_duration_ms",t),Soe(e,"mastra_workflow_duration_ms",t),Soe(e,"mastra_tool_duration_ms",t)]);return{agentData:r,workflowData:s,toolData:a}}})}const b8={agents:Yu.AGENT,workflows:Yu.WORKFLOW_RUN,tools:Yu.TOOL};function q1s(){const{data:e,isLoading:t,isError:n}=U1s(),{getTracesHref:r,getLogsHref:s}=TA(),{Link:a}=ln();return o.jsx(B1s,{data:e,isLoading:t,isError:n,LinkComponent:a,getRowHref:(i,l)=>r({rootEntityType:b8[i],entityName:l.name}),getErrorSegmentHref:(i,l)=>l.errors>0?s({rootEntityType:b8[i],entityName:l.name,status:"error"}):void 0,actions:i=>o.jsxs(o.Fragment,{children:[o.jsx(s5,{href:r({rootEntityType:b8[i]}),LinkComponent:a}),o.jsx(e1s,{href:s({rootEntityType:b8[i],status:"error"}),LinkComponent:a})]})})}const koe="period",x8="dateFrom",w8="dateTo";function V1s(){const[e,t]=ya(),n=e.get(koe),r=HSs(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(x8)),h=d(e.get(w8));if(!(!f&&!h))return{from:f,to:h}},[r,e.toString()]),a=g.useMemo(()=>LSs(e),[e.toString()]),i=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d==="24h"?h.delete(koe):h.set(koe,d),d!=="custom"&&(h.delete(x8),h.delete(w8)),h},{replace:!0})},[t]),l=g.useCallback(d=>{t(f=>{const h=new URLSearchParams(f);return d?.from?h.set(x8,d.from.toISOString()):h.delete(x8),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 zSs(h,d),h},{replace:!0})},[t]),u=g.useRef(!1);return g.useEffect(()=>{if(u.current||(u.current=!0,MSs(e)))return;const d=qWt();d&&t(f=>{const h=new URLSearchParams(f);for(const[p,m]of d)h.append(p,m);return h},{replace:!0})},[]),o.jsx(ZSs,{preset:r,filterTokens:a,onPresetChange:i,onFilterTokensChange:c,customRange:s,onCustomRangeChange:l,children:o.jsx(H1s,{})})}function H1s(){const[e]=ya(),{error:t,isLoading:n}=WWt(),{filterTokens:r,setFilterTokens:s}=xY(),[a,i]=g.useState(),{supportsMetrics:l,isInMemory:c,isLoading:u}=HQ(),{data:d,isLoading:f}=BRe(),{data:h,isLoading:p}=LRe(),{data:m,isLoading:v}=zRe(),{data:y,isLoading:b}=FRe(),x=g.useMemo(()=>DSs({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(()=>qWt()!==null),O=g.useCallback(()=>{PSs(e),k(!0),Ve.success("Filters setting for Metrics saved")},[e]),_=g.useCallback(()=>{$Ss(),k(!1),Ve.success("Filters setting for Metrics cleared up")},[]),E=g.useCallback(()=>{s([])},[s]),T=g.useCallback(()=>{const N=r.map(I=>{const A=x.find(R=>R.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&&hs(t)?o.jsx(Zn,{children:o.jsx(Es,{})}):t&&ps(t)?o.jsx(Zn,{children:o.jsx(Os,{resource:"metrics"})}):t?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load metrics",message:t.message})}):o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsxs(Lt.TopArea,{children:[o.jsx(Lt.Row,{children:o.jsxs(Lt.Column,{className:"flex flex-wrap items-start justify-start gap-2",children:[o.jsx(KSs,{}),o.jsx($Re,{fields:x,tokens:r,onTokensChange:s,disabled:n,onStartTextFilter:i})]})}),o.jsx(O1s,{isLoading:n,filterFields:x,filterTokens:r,onFilterTokensChange:s,onClear:T,onRemoveAll:E,onSave:O,onRemoveSaved:w?_:void 0,autoFocusFilterFieldId:a})]}),u?null:l?o.jsxs("div",{className:"grid content-start gap-8 pb-10",children:[c&&o.jsx(An,{variant:"info",title:"Metrics are not persisted",children:o.jsx(An.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(C0e,{children:[o.jsx(b1s,{}),o.jsx(x1s,{}),o.jsx(w1s,{}),o.jsx(S1s,{}),o.jsx(k1s,{})]}),o.jsxs(C0e,{children:[o.jsx(T1s,{}),o.jsx(A1s,{}),o.jsx(z1s,{}),o.jsx(p1s,{}),o.jsx(q1s,{}),o.jsx(c1s,{})]})]}):o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(pr,{iconSlot:o.jsx(ks,{}),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.jsxs(oe,{variant:"ghost",as:"a",href:"https://mastra.ai/docs/observability/metrics/overview",target:"_blank",rel:"noopener noreferrer",children:["Metrics Documentation ",o.jsx(Ds,{})]})})})]})}const W1s=50;function Z1s(){const{paths:e}=ln(),{isCmsAvailable:t}=O1(),[n,r]=g.useState(""),[s,a]=g.useState(0),{data:i,isLoading:l,error:c,isPlaceholderData:u}=Iqt({page:s,perPage:W1s}),d=i?.promptBlocks??[],f=i?.hasMore??!1,h=g.useCallback(()=>{u||a(v=>v+1)},[u]),p=g.useCallback(()=>{u||a(v=>Math.max(0,v-1))},[u]),m=g.useCallback(v=>{r(v),a(0)},[]);return c&&hs(c)?o.jsx(Zn,{children:o.jsx(Es,{})}):c&&ps(c)?o.jsx(Zn,{children:o.jsx(Os,{resource:"prompt blocks"})}):c?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load prompt blocks",message:c.message})}):d.length===0&&!l&&s===0?o.jsx(Zn,{children:o.jsx(fus,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Uc,{onSearch:m,label:"Filter prompts",placeholder:"Filter by name or description"})}),t&&o.jsxs(oe,{as:yo,to:e.cmsPromptBlockCreateLink(),variant:"primary",className:"shrink-0",children:[o.jsx(Fr,{}),"Create Prompt"]})]})}),o.jsx(dus,{promptBlocks:d,isLoading:l,search:n,currentPage:s,hasMore:f,onNextPage:h,onPrevPage:p})]})}function G1s(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx(Xls,{children:o.jsx(e0e,{})})})})}const Q1s=[{title:"Mastra APIs",description:"Explore and test the available REST API endpoints with the interactive Swagger UI.",icon:_Xt,href:"/swagger-ui",external:!1},{title:"Documentation",description:"Read the official Mastra documentation for guides, references, and tutorials.",icon:put,href:"https://mastra.ai/en/docs",external:!0},{title:"Github",description:"Browse the source code, report issues, and contribute to the Mastra project.",icon:Ds,href:"https://github.com/mastra-ai/mastra",external:!0},{title:"Community",description:"Join the Mastra Discord community for help, discussion, and collaboration.",icon:c3,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:yut,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:mut,href:"https://mastra.ai/contact?ref=studio",external:!0}];function Y1s(){return o.jsx(Lt,{width:"narrow",children:o.jsx(Lt.MainArea,{children:o.jsx("div",{className:"grid max-w-3xl grid-cols-1 gap-4 sm:grid-cols-2",children:Q1s.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(Ds,{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 leading-relaxed",children:e.description})]},e.href))})})})}function K1s(){const{data:e={},isLoading:t,error:n}=up(),[r,s]=g.useState(""),[a,i]=g.useState("all");if(n&&hs(n))return o.jsx(Zn,{children:o.jsx(Es,{})});if(n&&ps(n))return o.jsx(Zn,{children:o.jsx(Os,{resource:"scorers"})});if(n)return o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load scorers",message:n.message})});if(Object.keys(e).length===0&&!t)return o.jsx(Zn,{children:o.jsx($Hr,{})});const l=a!=="all"||r!=="",c=()=>{s(""),i("all")};return o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsx(DHr,{search:r,onSearchChange:s,sourceFilter:a,onSourceFilterChange:i,onReset:c,hasActiveFilters:l})}),o.jsx(PHr,{scorers:e,isLoading:t,search:r,sourceFilter:a})]})}const YWt=["input","entity"],X1s={input:"Input",entity:"Entity"};function J1s(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 eks(){const[e,t]=g.useState(new Set),n=g.useMemo(()=>new Set(YWt.filter(a=>!e.has(a))),[e]),r=g.useMemo(()=>J1s(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 tks({visibleColumns:e,toggleColumn:t}){return o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsxs(oe,{children:[o.jsx(but,{}),"Columns"]})}),o.jsxs(ot.Content,{align:"end",children:[o.jsx(ot.Label,{children:"Toggle columns"}),YWt.map(n=>o.jsx(ot.CheckboxItem,{checked:e.has(n),onClick:()=>t(n),children:X1s[n]},n))]})]})}function nks(){const{scorerId:e}=ur(),[t,n]=ya(),r=t.get("scoreId")??void 0,[s,a]=g.useState(r),[i,l]=g.useState(!1),c=Kr(),[u,d]=g.useState({value:"all",label:"All Entities",type:"ALL"}),{scorer:f,error:h}=pHr(e),p=eks(),{data:m={},isLoading:v,error:y}=zm(),{isLoading:b,error:x}=Yy(),{data:w=[],isLoading:k,error:O,isFetchingNextPage:_,hasNextPage:E,setEndOfListElement:T}=hHr({scorerId:e,entityId:u?.value==="all"?void 0:u?.value,entityType:u?.type==="ALL"?void 0:u?.type}),N=g.useMemo(()=>f?.agentIds?.filter(W=>m[W]).map(W=>({value:W,label:m[W].name,type:"AGENT"}))||[],[f?.agentIds,m]),I=g.useMemo(()=>f?.workflowIds?.map(W=>({value:W,label:W,type:"WORKFLOW"}))||[],[f?.workflowIds]),A=g.useMemo(()=>[{value:"all",label:"All Entities",type:"ALL"},...N,...I],[N,I]),R=t.get("entity")??"all",L=A.find(W=>W.value===R);L&&L.value!==u?.value&&d(L),g.useEffect(()=>{if(h){const W=h instanceof Error?h.message:"Failed to load scorer";Ve.error(`Error loading scorer: ${W}`)}},[h]),g.useEffect(()=>{if(y){const W=y instanceof Error?y.message:"Failed to load agents";Ve.error(`Error loading agents: ${W}`)}},[y]),g.useEffect(()=>{if(x){const W=x instanceof Error?x.message:"Failed to load workflows";Ve.error(`Error loading workflows: ${W}`)}},[x]);const M=W=>{W?.value&&n(Y=>{const te=new URLSearchParams(Y);return te.set("entity",W.value),te})};g.useEffect(()=>{const W=t.get("scoreId")??void 0;if(W===s)return;if(!W){a(void 0);return}w.find(te=>te.id===W)&&a(W)},[t,w]);const B=g.useCallback(W=>{a(W||void 0),n(Y=>{const te=new URLSearchParams(Y);return W?te.set("scoreId",W):te.delete("scoreId"),te})},[n]);if(!f)return null;const V=hs(h)||hs(y)||hs(x),q=h&&ps(h),F=!V&&!q&&(h||y||x),H=!k&&w.length===0,D=u?.value!=="all",G=f?.scorer?.source==="stored",z=e?o.jsx(mY,{open:i,onOpenChange:l,initialScorerIds:[e],onSuccess:W=>{c(`/experiments/${W}`)}}):null,$=G?o.jsxs(ot,{children:[o.jsx(ot.Trigger,{asChild:!0,children:o.jsx(oe,{size:"lg","aria-label":"Scorer actions menu",children:o.jsx(XS,{})})}),o.jsx(ot.Content,{align:"end",className:"w-48",children:o.jsxs(ot.Item,{onSelect:()=>{c(`/cms/scorers/${e}/edit`)},children:[o.jsx(Qh,{})," Edit Scorer"]})})]}):null;if(V||q||F||H&&!D){const W=(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",Y=V||q||F;return o.jsxs(Lt,{width:"wide",height:"full",className:Y||!$?"grid-rows-[1fr]":void 0,children:[!Y&&$&&o.jsx(Lt.TopArea,{children:o.jsx(ts,{className:"ml-auto",children:$})}),o.jsx(Lt.MainArea,{isCentered:!0,children:V?o.jsx(Es,{}):q?o.jsx(Os,{resource:"scorers"}):F?o.jsx(Fs,{title:"Failed to load scorer",message:W}):o.jsx(iHr,{onRunExperiment:()=>l(!0)})}),z]})}return o.jsxs(Lt,{width:"wide",height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs("div",{className:"flex items-center justify-between gap-3",children:[o.jsx(oHr,{selectedEntity:u,entityOptions:A,onEntityChange:M,onReset:()=>{n(W=>{const Y=new URLSearchParams(W);return Y.set("entity","all"),Y})},isLoading:k||v||b}),o.jsxs(ts,{children:[o.jsx(tks,{visibleColumns:p.visibleColumns,toggleColumn:p.toggleColumn}),o.jsxs(oe,{variant:"primary",onClick:()=>l(!0),children:[o.jsx(Pc,{}),"Run Experiment"]}),$]})]})}),o.jsx(aHr,{scores:w,isLoading:k,selectedScoreId:s,isFetchingNextPage:_,hasNextPage:E,setEndOfListElement:T,onScoreClick:B,errorMsg:O?.message,columnsState:p}),z]})}const rks=io("flex min-w-0 flex-col",{variants:{variant:{default:"gap-3 sm:flex-row sm:items-center sm:justify-between",factory:"gap-2 px-4 py-3 lg:flex-row lg:items-center lg:justify-between lg:gap-4"}},defaultVariants:{variant:"default"}}),sks=io("flex min-w-0 flex-col",{variants:{variant:{default:"",factory:"gap-0.5"}},defaultVariants:{variant:"default"}}),Lnt=io("",{variants:{variant:{default:"text-sm font-medium",factory:"text-ui-md leading-ui-md text-neutral5"}},defaultVariants:{variant:"default"}}),aks=io("flex flex-col gap-0.5",{variants:{variant:{default:"text-sm text-neutral3",factory:"text-ui-sm text-neutral3"}},defaultVariants:{variant:"default"}});function iks({label:e,description:t,htmlFor:n,variant:r,className:s,children:a}){return o.jsxs("div",{className:K(rks({variant:r}),s),"data-slot":"settings-row",children:[o.jsxs("div",{className:sks({variant:r}),children:[n?o.jsx(Mt,{htmlFor:n,className:Lnt({variant:r}),children:e}):o.jsx("span",{className:Lnt({variant:r}),children:e}),t&&o.jsx("div",{className:aks({variant:r}),children:t})]}),a]})}const KWt=[{value:"dark",label:"Dark",Icon:Oen},{value:"light",label:"Light",Icon:Ytn},{value:"system",label:"System",Icon:Rut}],oks=e=>KWt.some(t=>t.value===e);function lks({option:e}){const{Icon:t}=e;return o.jsxs("span",{className:"inline-flex max-w-full min-w-0 items-center gap-2",children:[o.jsx(t,{"aria-hidden":"true",className:"h-4 w-4 shrink-0 opacity-70"}),o.jsx("span",{className:"min-w-0 truncate",children:e.label})]})}const cks=()=>{const{baseUrl:e,headers:t,apiPrefix:n}=UH(),{theme:r,setTheme:s}=c_();return o.jsx(Lt,{width:"narrow",children:o.jsxs(Lt.MainArea,{className:"mt-6 flex flex-col gap-5",children:[o.jsx(Oxe,{title:"Theme",description:"Customize the appearance of the studio.",children:o.jsx(iks,{label:"Theme mode",htmlFor:"theme",children:o.jsxs(ka,{value:r,onValueChange:a=>{oks(a)&&s(a)},children:[o.jsx(Ca,{id:"theme",className:"w-full sm:w-48",children:o.jsx(Oa,{className:"inline-flex max-w-full min-w-0 items-center"})}),o.jsx(_a,{children:KWt.map(a=>o.jsx(jr,{value:a.value,children:o.jsx(lks,{option:a})},a.value))})]})})}),o.jsx(Oxe,{title:"Mastra Connection",description:"Configure the Mastra instance URL, API prefix, and request headers used by the studio.",children:o.jsx(L4t,{initialConfig:{baseUrl:e,headers:t,apiPrefix:n}})})]})})};function uks(){const[e]=ya(),t=Kr(),n=e.get("redirect")||"/",r=()=>{n.startsWith("http")?window.location.href=n:t(n,{replace:!0})};return o.jsx(zWt,{redirectUri:n,onSuccess:r,initialMode:"signup"})}function dks(e){return e.replace(/\/$/,"").split("/").pop()}function wY({children:e,className:t}){return o.jsx("div",{className:K("border border-border1 rounded-lg mt-12 py-8 lg:min-h-[25rem] transition-height px-4 lg:px-12",t),children:e})}function fks({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-6 w-full gap-0.5","[&_svg]:w-[1em] [&_svg]:h-[1em] [&_svg]:text-neutral3"),children:[o.jsx("h2",{className:"text-ui-lg 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(co,{})," ",a.agents.length]}),a?.tools&&a.tools.length>0&&o.jsxs("li",{children:[o.jsx(Uf,{})," ",a.tools.length]}),a?.networks&&a.networks.length>0&&o.jsxs("li",{children:[o.jsx(Put,{})," ",a.networks.length]}),a?.workflows&&a.workflows.length>0&&o.jsxs("li",{children:[o.jsx(mI,{})," ",a.workflows.length]}),a?.mcp&&a.mcp.length>0&&o.jsxs("li",{children:[o.jsx(R_,{})," ",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(xG,{})," ",dks(a.githubUrl)]})})]},a.slug)})})}function hks({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-8","[&>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-8",u),children:[o.jsx(ED,{name:"search-templates",label:"Search templates",labelIsHidden:!0,value:i,onChange:f=>l?.(f.target.value),placeholder:"Search Template"}),o.jsx(Kd,{label:"Filter by tag",labelIsHidden:!0,name:"filter-tag",value:t,onValueChange:s,options:e}),o.jsx(Kd,{label:"Filter by provider",labelIsHidden:!0,name:"filter-provider",value:r,onValueChange:a,options:n}),c&&o.jsxs(oe,{onClick:c,children:["Reset ",o.jsx(or,{})]})]})}function pks(){const{data:e,isLoading:t}=Dsr(),{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(ia,{children:[o.jsx(V1e,{children:o.jsxs(Bxt,{children:[o.jsx(Je,{children:o.jsx(ux,{})}),"Templates"]})}),o.jsxs("div",{className:K("overflow-y-auto w-full h-full px-8 pb-12 z-10"),children:[o.jsx(hks,{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(fks,{templates:y,linkComponent:yo,className:"mx-auto max-w-[80rem]",isLoading:t})]})]})}const mks="1.66.0";function gks({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(jc,{className:"text-yellow-500"}),title:"Template Installed with Warnings"}:{icon:o.jsx(FXt,{}),title:"Template Installation Failed"},{icon:l,title:c}=i();return o.jsxs(wY,{className:"text-neutral3 mb-8 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-xs",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:"mt-4 max-h-60 space-y-2 overflow-auto rounded bg-gray-100 p-3 text-left text-xs 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:"mt-1 font-mono text-xs wrap-break-word whitespace-pre-wrap text-gray-700 dark:text-gray-300",children:u.message})]},d))})]}),n&&!s&&o.jsxs("details",{className:"text-xs",children:[o.jsx("summary",{className:"text-neutral3 hover:text-neutral4 cursor-pointer text-center select-none",children:"Show Details"}),o.jsx("div",{className:"mt-4 max-h-60 overflow-auto rounded bg-gray-100 p-3 text-left font-mono text-xs dark:bg-gray-800",children:o.jsx("div",{className:"wrap-break-word whitespace-pre-wrap",children:n})})]})]})}function vks({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(wY,{children:o.jsxs("div",{className:"mx-auto my-4 grid max-w-[40rem] gap-8 p-4 lg:p-8",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($ut,{})]}),o.jsx(Kd,{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(Vt,{})," Loading variables..."]}):Object.entries(r).map(([h,p])=>o.jsxs(g.Fragment,{children:[o.jsx(Jh,{name:`env-${h}`,labelIsHidden:!0,label:"Key",value:h,disabled:!0,className:"w-full"}),o.jsx(Jh,{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-lg",children:"Set AI Model for Template Installation"}),o.jsx("p",{className:"text-neutral3 text-ui-md mt-2 mb-8",children:"This model will be used by the workflow to process and install the template"}),o.jsx(D4t,{defaultProvider:u||"",defaultModel:d||"",updateModel:f||(()=>Promise.resolve({message:"Updated"})),closeEditor:()=>{},autoSave:!0,selectProviderPlaceholder:"Provider"})]})]}),t&&!l&&o.jsx(oe,{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(Vt,{className:"h-4 w-4"})," Installing..."]}):o.jsxs(o.Fragment,{children:["Install ",o.jsx(Mf,{})]})})]})})}function yks({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-8 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(ux,{}),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 leading-7",{"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(Cm,{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(Z0e,{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(xG,{}),n?.split("/")?.pop()]})]}),s&&o.jsx(Uje,{data:s,labelsAreHidden:!0,isLoading:r})]})]})}function Fnt(e){switch(e){case"running":return o.jsx(Vt,{size:"sm","aria-hidden":!0});case"success":return o.jsx(Dr,{"aria-hidden":!0});case"failed":return o.jsx(or,{"aria-hidden":!0});default:return null}}function bks(){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 xks({status:e,variant:t}){return t==="plain"?o.jsx("span",{className:K("flex size-4 items-center justify-center self-center [&>svg]:size-4",Yr.colors,{"[&>svg]:text-positive1":e==="success","[&>svg]:text-negative1":e==="failed"}),children:e==="pending"?o.jsx(bks,{}):Fnt(e)}):o.jsx("span",{className:K("flex size-7 items-center justify-center self-center rounded-full motion-reduce:transition-none",Yr.colors,Yr.transform,Yr.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:Fnt(e)})}function wks({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",Yr.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",Yr.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",Yr.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(xks,{status:e.status,variant:r})]})}function Sks({currentStep:e,steps:t=[],className:n}){return o.jsx("div",{className:K(n),children:t.map((r,s)=>o.jsx(wks,{step:r,isActive:e?.id===r.id,position:s+1},r.id))})}function kks({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",Yr.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",Yr.colors,Yr.transform,Yr.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(Vt,{}):s+1})},r.id))}),o.jsxs("div",{className:K("text-center text-xs text-neutral3",Yr.colors),children:[n," of ",t," steps completed"]})]})}function Oks({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(wY,{className:"text-neutral3 mb-8 content-center space-y-6",children:[o.jsxs("div",{className:"text-center",children:[o.jsx("h3",{className:"text-neutral5 text-lg 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-6",children:o.jsx(kks,{steps:m})}),l&&s==="error"&&o.jsxs("div",{className:K("rounded-lg text-neutral5 p-6 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(Den,{}),l||"Something went wrong"]}),u&&o.jsx(Sks,{steps:m,currentStep:i,className:"pb-4"}),!u&&s==="initializing"&&o.jsxs("div",{className:"text-neutral3 grid justify-items-center gap-4 text-center text-sm",children:[o.jsx(Vt,{}),o.jsx("p",{children:"This may take some time..."})]})]})}function Cks({name:e,installedEntities:t}){return o.jsxs(wY,{className:K("grid items-center justify-items-center gap-4 content-center","[&>svg]:w-8 [&>svg]:h-8"),children:[o.jsx($ut,{}),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(Uje,{data:t})]})}function _ks(){const{templateSlug:e}=ur(),[t,n]=ya(),[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),[E,T]=g.useState([]),{data:N,isLoading:I}=Lsr({repoOrSlug:e,owner:"mastra-ai"}),R=mks?.includes("beta")??!1?"beta":"main",{data:L,isLoading:M}=Fsr({repo:N?.githubUrl?new URL(N.githubUrl).pathname.split("/")[2]:`template-${e}`,owner:"mastra-ai",branch:R}),{data:B,isLoading:V}=zsr(),{mutateAsync:q,isPending:F}=Bsr(),{mutateAsync:H}=Usr(),{streamInstall:D,streamResult:G,isStreaming:z}=Vsr(B),{observeInstall:$,streamResult:U,isStreaming:W}=Hsr(B);g.useEffect(()=>{const ne=t.get("runId");ne&&!v&&!p&&!z&&!W&&(console.info("🔄 Checking completed run after hot reload:",{runId:ne}),x(ne),H({runId:ne}).then(se=>{const de=se.snapshot;if(de?.status==="success"&&de?.result?.success)y(!0);else if(de?.result?.success===!1)if(de?.result?.validationResults&&!de?.result?.validationResults?.valid&&de?.result?.validationResults?.remainingErrors>0){const{remainingErrors:ye,errors:he}=de.result.validationResults,xe=`Template installation completed but ${ye} validation issue${ye>1?"s":""} remain unresolved.`;m(xe),T(he||[])}else{const ye=de?.result?.message||de?.result?.error||"Template installation failed";m(typeof ye=="string"?ye:String(ye))}}).catch(se=>{console.error("❌ Failed to fetch run details:",se),m("Failed to retrieve installation status after reload")}))},[t,v,p,z,W,H]),g.useEffect(()=>{const ne=t.get("runId"),se=t.get("resume"),de=t.get("provider");if(ne&&se==="true"&&de&&!z&&!W&&!w&&!O&&B){x(ne),k(!0);try{H({runId:ne}).then(ue=>{if(ue.snapshot?.status==="running")return $.mutateAsync({runId:ne})}).then(()=>{n(ue=>{const ye=new URLSearchParams(ue);return ye.delete("resume"),ye})}).catch(ue=>{console.error("❌ Failed to resume template installation:",ue),ue.message?.includes("404")||ue.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(ue){console.error("❌ Auto-resume failed with error:",ue),m("Failed to resume template installation. Please refresh and try again.")}}},[t,e,z,W,w,O,B,H,$,n]);const Y=[{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(Uf,{})},{key:"agents",label:"Agents",value:N?.agents?.length?N.agents.map(ne=>ne).join(", "):"n/a",icon:o.jsx(co,{})},{key:"workflows",label:"Workflows",value:N?.workflows?.length?N.workflows.map(ne=>ne).join(", "):"n/a",icon:o.jsx(mI,{})},{key:"providers",label:"Providers",value:N?.supportedProviders?.length?N.supportedProviders.join(", "):"n/a",icon:o.jsx(Gv,{})},{key:"tags",label:"Tags",value:N?.tags?.length?N.tags.join(", "):"n/a",icon:o.jsx(pI,{})}],ee=[{...te[0]},{...te[1]},{...te[2]}].filter(ne=>ne.value!=="n/a");g.useEffect(()=>{L&&d(L)},[L]),g.useEffect(()=>{const ne=G||U;ne?.phase==="error"&&ne?.error&&m(typeof ne.error=="string"?ne.error:String(ne.error))},[G?.phase,G?.error,U?.phase,U?.error]);const J=ne=>{s(ne)},re=async ne=>(i(ne.provider),c(ne.modelId),{message:"Model updated successfully"}),le=async()=>{const ne=Object.entries(u).reduce((se,[de,ue])=>(ue===""&&se.push(de),se),[]);if(ne.length>0){h(ne);return}if(N){m(null),y(!1),x(""),_(!0);try{const de={repo:N.githubUrl||`https://github.com/mastra-ai/template-${N.slug}`,ref:R,slug:N.slug,variables:u},{runId:ue}=await q({});x(ue),n(ye=>{const he=new URLSearchParams(ye);return he.set("runId",ue),he.set("resume","true"),he.set("provider",r||"openai"),he}),await D.mutateAsync({inputData:de,selectedModel:{provider:a,modelId:l},runId:ue})}catch(se){_(!1),m(se?.message||"Template installation failed"),console.error("Template installation failed",se)}}},X=ne=>{const{name:se,value:de}=ne.target;de.trim()===""?h(ue=>[...ue,se]):h(ue=>ue.filter(ye=>ye!==se)),d(ue=>({...ue,[se]:de}))};return o.jsx(ia,{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-6",children:[o.jsx(yks,{isLoading:I,title:N?.title,description:N?.longDescription,imageURL:N?.imageURL,githubUrl:N?.githubUrl,infoData:te,templateSlug:e}),N&&o.jsxs(o.Fragment,{children:[(z||W)&&o.jsx(Oks,{name:N.title,streamResult:W?U:G,runId:b,workflowInfo:B}),v&&o.jsx(Cks,{name:N.title,installedEntities:ee,linkComponent:yo}),p&&o.jsx(gks,{errorMsg:p,validationErrors:E.length>0?E:G?.validationResults?.errors||U?.validationResults?.errors}),!z&&!W&&!v&&!p&&o.jsx(vks,{providerOptions:Y,selectedProvider:r,onProviderChange:J,variables:u,setVariables:d,errors:f,setErrors:h,handleInstallTemplate:le,handleVariableChange:X,isLoadingEnvVars:M||V,isInstalling:F,defaultModelProvider:a,defaultModelId:l,onModelUpdate:re})]})]})})})}const Eks=()=>{const{toolId:e,agentId:t}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-auto",children:o.jsx(mcs,{toolId:e,agentId:t})})},Tks=()=>{const{toolId:e}=ur();return o.jsx("div",{className:"h-full w-full overflow-y-hidden",children:o.jsx(OSs,{toolId:e})})};function jks(){const{data:e,isLoading:t,error:n}=Yy(),[r,s]=g.useState("");return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Es,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"workflows"})}):n?o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load workflows",message:n.message})}):Object.keys(e||{}).length===0&&!t?o.jsx(Zn,{children:o.jsx(nXr,{})}):o.jsxs(Lt,{height:"full",children:[o.jsx(Lt.TopArea,{children:o.jsxs(Lt.Row,{align:"center",stack:"responsive",children:[o.jsx("div",{className:"max-w-120 flex-1",children:o.jsx(Uc,{onSearch:s,label:"Filter workflows",placeholder:"Filter by name or description"})}),o.jsxs(oe,{as:yo,to:"/workflows/schedules",variant:"primary",className:"shrink-0",children:[o.jsx(RC,{}),"Schedules"]})]})}),o.jsx(tXr,{workflows:e||{},isLoading:t,search:r})]})}const Nks={active:"bg-accent1",paused:"bg-accent3"},Iks={active:"text-accent1",paused:"text-accent3"},XWt=({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 ${Nks[e]}`,"aria-hidden":!0}),o.jsx("span",{className:`text-ui-sm ${Iks[e]}`,children:e})]}),Aj=e=>!e||e<=0?"—":new Date(e).toLocaleString(),wM=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 JWt({status:e}){const{icon:t,color:n}=Aks(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 Aks(e){switch(e){case"success":return{icon:o.jsx(Dr,{size:14}),color:"text-accent1"};case"failed":return{icon:o.jsx(or,{size:14}),color:"text-accent2"};case"running":return{icon:o.jsx(Vt,{}),color:"text-neutral3"};case"suspended":return{icon:o.jsx(FV,{size:14}),color:"text-accent3"};case"canceled":return{icon:o.jsx(ks,{size:14}),color:"text-neutral3"};case"pending":case"waiting":return{icon:o.jsx(lS,{size:14}),color:"text-neutral3"};default:return{icon:null,color:"text-neutral3"}}}const znt="auto auto auto auto 1fr";function Rks(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 Pks(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 $ks=3e4,Mks=5*6e4;function Dks({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}=ol({count:u});let h=-1;return t?o.jsx(Do,{columns:znt}):e.length===0?o.jsx(ge,{variant:"ui-md",className:"text-neutral4 p-4",children:"No trigger history yet."}):o.jsxs(ve,{columns:znt,className:"min-w-0",scrollRef:d,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Run"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Started"}),o.jsx(ve.TopCell,{children:"Duration"}),o.jsx(ve.TopCell,{children:" "})]}),e.map(p=>{const m=p.actualFireAt-p.scheduledFireAt,v=Pks(m),y=`Scheduled ${Aj(p.scheduledFireAt)} — published ${Aj(p.actualFireAt)} (drift ${v})`,b=p.outcome==="failed",x=b?p.error:p.run?.error,w=Math.abs(m),k=!b&&w>$ks&&w<=Mks,O=`${p.scheduleId}-${p.runId}-${p.actualFireAt}`,_=c(p);_&&(h+=1);const E=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}),T=o.jsxs(o.Fragment,{children:[o.jsx(ve.Cell,{children:E}),o.jsx(ve.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(jc,{size:14}),"publish failed"]}):p.run?o.jsx(JWt,{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(fn,{asChild:!0,children:o.jsx("span",{className:"text-accent2 inline-flex",children:o.jsx(jc,{size:14})})}),o.jsx(hn,{children:x})]}):null]})}),o.jsx(ve.Cell,{children:o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx("span",{title:y,children:wM(p.actualFireAt)}),k?o.jsxs(gn,{children:[o.jsx(fn,{asChild:!0,children:o.jsx("span",{className:"text-accent3 inline-flex",children:o.jsx(jc,{size:14})})}),o.jsxs(hn,{children:["Published ",v," after the scheduled fire time"]})]}):null]})}),o.jsx(ve.Cell,{children:p.run?o.jsx("span",{children:Rks(p.run.durationMs)}):o.jsx("span",{className:"text-neutral4",children:"—"})}),o.jsx(ve.Cell,{children:" "})]});return _?o.jsx(ve.RowLink,{to:l.workflowRunLink(n,p.runId),LinkComponent:i,...f(h),children:T},O):o.jsx(ve.RowStatic,{children:T},O)}),o.jsx(ve.NextPageLoading,{isLoading:s,hasMore:r,setEndOfListElement:a})]})}const Lks=e=>{const t=Ze();return mt({queryKey:["schedule",e],enabled:!!e,queryFn:async()=>{if(!e)throw new Error("scheduleId is required");return t.getSchedule(e)}})},Bnt=25,Fks=e=>{const t=Ze(),{inView:n,setRef:r}=s0(),s=Fy({queryKey:["schedule-triggers",e],enabled:!!e,initialPageParam:void 0,queryFn:async({pageParam:u})=>e?t.listScheduleTriggers(e,{limit:Bnt,toActualFireAt:u}):{triggers:[]},getNextPageParam:u=>{if(!(!u?.triggers?.length||u.triggers.length<Bnt))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}},zks=e=>{const t=Ze(),n=Or();return bn({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"]}),Ve.success(s==="pause"?"Schedule paused":"Schedule resumed")},onError:r=>{Ve.error(r.message)}})};function S8({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 Bks(){const{scheduleId:e}=ur(),{paths:t}=ln(),{data:n,error:r}=Lks(e),{data:s,isLoading:a,error:i,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u}=Fks(e),d=zks(e);if(r&&hs(r))return o.jsx(Zn,{children:o.jsx(Es,{})});if(r&&ps(r))return o.jsx(Zn,{children:o.jsx(Os,{resource:"schedules"})});if(r)return o.jsx(Zn,{children:o.jsx(Fs,{title:"Failed to load schedule",message:r.message})});const f=n?.workflowId,h=n?.agentId;return o.jsxs(Lt,{children:[o.jsx(Lt.TopArea,{children:o.jsx(Lt.Row,{className:"justify-end",children:o.jsxs(Lt.Column,{className:"flex justify-end gap-2",children:[o.jsxs(oe,{as:yo,to:t.schedulesLink(),variant:"ghost",children:[o.jsx(wu,{}),"Back to schedules"]}),f?o.jsx(oe,{as:yo,to:t.workflowLink(f),variant:"ghost",children:"Open workflow"}):null,n?o.jsx(oe,{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(VV,{}),"Pause"]}):o.jsxs(o.Fragment,{children:[o.jsx(Pc,{}),"Resume"]})}):null]})})}),n?o.jsxs("div",{className:"grid h-full grid-cols-[minmax(0,20rem)_1fr] gap-6 overflow-hidden",children:[o.jsxs("div",{className:"border-border1 flex h-fit flex-col gap-4 rounded-md border p-4",children:[o.jsx(S8,{label:h?"Agent":"Workflow",children:f?o.jsx(yo,{to:t.workflowLink(f),className:"text-accent1 hover:underline",children:f}):h?o.jsx(yo,{to:t.agentLink(h),className:"text-accent1 hover:underline",children:h}):"—"}),o.jsxs(S8,{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(S8,{label:"Status",children:o.jsx(XWt,{status:n.status})}),o.jsx(S8,{label:"Next fire",children:o.jsx("span",{title:Aj(n.nextFireAt),children:wM(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(Dks,{triggers:s??[],isLoading:a,workflowId:f,hasNextPage:l,isFetchingNextPage:c,setEndOfListElement:u})]})]}):null]})}const Unt="minmax(0, 1.2fr) minmax(0, 1.4fr) minmax(0, 1fr) auto auto auto";function Uks({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}=ol({count:a.length});return t?o.jsx(Do,{columns:Unt}):o.jsxs(ve,{columns:Unt,className:"min-w-0",scrollRef:i,children:[o.jsxs(ve.Top,{children:[o.jsx(ve.TopCell,{children:"Target"}),o.jsx(ve.TopCell,{children:"Schedule ID"}),o.jsx(ve.TopCell,{children:"Cron"}),o.jsx(ve.TopCell,{children:"Status"}),o.jsx(ve.TopCell,{children:"Next fire"}),o.jsx(ve.TopCell,{children:"Last run"})]}),a.length===0&&n?o.jsx(ve.NoMatch,{message:"No schedules match your search"}):null,a.length===0&&!n?o.jsx(ve.NoMatch,{message:"No schedules configured"}):null,a.map((c,u)=>o.jsxs(ve.RowLink,{to:r.scheduleLink(c.id),LinkComponent:s,...l(u),children:[o.jsx(ve.NameCell,{children:c.workflowId??c.agentId}),o.jsx(ve.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(ve.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(ve.Cell,{children:o.jsx(XWt,{status:c.status})}),o.jsx(ve.Cell,{children:o.jsx("span",{className:"whitespace-nowrap",title:Aj(c.nextFireAt),children:wM(c.nextFireAt)})}),o.jsx(ve.Cell,{children:c.lastRun?o.jsxs("span",{className:"inline-flex items-center gap-2 whitespace-nowrap",children:[o.jsx(JWt,{status:c.lastRun.status}),o.jsx("span",{className:"text-neutral4 text-ui-sm",title:Aj(c.lastFireAt),children:c.lastFireAt?wM(c.lastFireAt):""})]}):c.lastFireAt?o.jsx("span",{className:"whitespace-nowrap",title:Aj(c.lastFireAt),children:wM(c.lastFireAt)}):o.jsx("span",{className:"text-neutral4",children:"Never"})})]},c.id))]})}function qks({workflowId:e}={}){const{data:t,isLoading:n,error:r}=U1e(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(Uc,{onSearch:a,label:"Filter schedules",placeholder:"Filter by id or workflow"})}),o.jsx("div",{className:"overflow-y-auto",children:o.jsx(Uks,{schedules:t??[],isLoading:n,search:s})})]})}function Vks(){const[e]=ya(),t=e.get("workflowId")??void 0,{error:n}=U1e(t?{workflowId:t}:{});return n&&hs(n)?o.jsx(Zn,{children:o.jsx(Es,{})}):n&&ps(n)?o.jsx(Zn,{children:o.jsx(Os,{resource:"schedules"})}):o.jsx(Lt,{children:o.jsx("div",{className:"h-full",children:o.jsx(qks,{workflowId:t})})})}function Hks({stepGraph:e,open:t,workflowName:n}){const{nodes:r,edges:s}=gCe({stepGraph:e}),[a,i]=g.useState(!1),[l,c,u]=pEt(r),[d]=mEt(s),{edgeTypes:f,nodeTypes:h,styledEdges:p}=eFt({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.jsxs(hEt,{nodes:l,edges:p,edgeTypes:f,fitView:!0,fitViewOptions:{maxZoom:1},minZoom:.01,maxZoom:1,nodeTypes:h,onNodesChange:u,children:[o.jsx(SNe,{position:"bottom-left"}),o.jsx(vEt,{variant:my.Lines,gap:12,size:.5})]}):o.jsx("div",{className:"flex h-full w-full items-center justify-center",children:o.jsx(Vt,{})})})}function Wks(){const{stepDetail:e,closeStepDetail:t}=UW();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(cS,{className:"h-4 w-4",style:{color:Du.map}}),e.type==="nested-graph"&&o.jsx(Su,{className:"h-4 w-4",style:{color:Du.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(or,{className:"text-neutral3 h-4 w-4"})})]}),o.jsxs("div",{className:"flex-1 overflow-auto",children:[e.type==="map-config"&&e.mapConfig&&o.jsx(gM,{data:e.mapConfig}),e.type==="nested-graph"&&e.nestedGraph&&o.jsx("div",{className:"h-full min-h-[400px]",children:o.jsx(mCe,{children:o.jsx(Hks,{stepGraph:e.nestedGraph.stepGraph,open:!0,workflowName:e.nestedGraph.fullStep})},`nested-graph-${e.nestedGraph.fullStep}`)})]})]}):null}function Zks(e){const t=new Blob([JSON.stringify(e??null)]).size;return t<1024?`${t} B`:`${(t/1024).toFixed(1)} KB`}function Gks(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 Qks({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(Je,{children:o.jsx(FV,{})}),"Step suspended"]}),o.jsx(yt,{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?bm(Ax(i.resumeSchema)):mf(cr(),_f());return o.jsx(Yks,{step:s,stepSchema:l,description:i.description,isStreaming:n,onResume:r},`${s.runId}-${s.stepId}-${a}`)})]})}function Yks({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(Je,{children:o.jsx(_en,{})}),"The step is asking"]}),o.jsxs(lc,{open:a,onOpenChange:i,children:[o.jsxs(Bl,{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(Je,{children:o.jsx(qr,{className:K("transition-transform text-neutral3",{"transform rotate-90":a})})}),o.jsx(ge,{as:"span",variant:"ui-md",className:"text-neutral6 truncate",children:Gks(e.suspendPayload,e.stepId)})]}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 shrink-0",children:Zks(e.suspendPayload)})]}),o.jsx(Ul,{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(Je,{children:o.jsx(Nen,{})}),"Your response"]}),o.jsx("div",{className:"-mx-5",children:o.jsx(OU,{schema:t,isSubmitLoading:r,submitButtonLabel:"Resume",submitButtonIcon:o.jsx(Pc,{}),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 Kks(){const{result:e,runSnapshot:t,workflow:n,runId:r,isStreamingWorkflow:s}=g.useContext(Wl),{runId:a}=ur(),i=OEt(e,r??""),l=rnr(),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(Qks,{suspendedSteps:i,workflow:n,isStreaming:s,onResume:l})},r)}const Xks=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"})]}),Jks=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"})]}),eOs=e=>e.includes("."),tOs=e=>e==="input"||e.endsWith(".input"),nOs=1;function rOs(e){return`${Number((e/1e3).toPrecision(3))}s`}function sOs(e,t){const n=Object.entries(e).filter(([i])=>!tOs(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,nOs);return{stepId:i,step:l,status:l.status,offsetPct:f,widthPct:h,durationMs:d,isRunning:c,isNestedEntry:eOs(i)}})}const aOs=({status:e})=>o.jsxs(Je,{children:[e==="success"&&o.jsx(Xks,{className:"text-accent1"}),e==="failed"&&o.jsx(Jks,{className:"text-accent2"}),e==="suspended"&&o.jsx(FV,{className:"text-accent3"}),e==="waiting"&&o.jsx(mpe,{className:"text-accent5"}),e==="skipped"&&o.jsx(mpe,{className:"text-icon3"}),e==="running"&&o.jsx(Vs,{className:"text-accent6 animate-spin"})]}),iOs={success:"bg-accent1",failed:"bg-accent2",suspended:"bg-accent3",waiting:"bg-accent5",skipped:"bg-border1",running:"bg-accent6"};function eZt(e){return e.split(/[-_.\s]+/).filter(Boolean).map(t=>t.charAt(0).toUpperCase()+t.slice(1)).join(" ")}const qnt=e=>e&&typeof e=="object"&&!Array.isArray(e)?e:{value:e},oOs=e=>{const t=e;return H6t({duration:t.duration,date:t.date,isForEach:t.isForEach,mapConfig:t.mapConfig,canSuspend:t.canSuspend,isParallel:t.isParallel,stepGraph:t.stepGraph})},lOs=({row:e,index:t,isSelected:n,isHovered:r,onSelectStep:s,onHoverStep:a,onOpenInput:i,onOpenOutput:l})=>{const c=oOs(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(aOs,{status:e.status})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(oe,{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(Vtn,{})})}),o.jsx("div",{className:"flex overflow-hidden",children:o.jsx(fV,{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:eZt(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 ${iOs[e.status]}`,style:{left:`${e.offsetPct}%`,width:`${e.widthPct}%`}})}),o.jsx("div",{className:"flex justify-center",children:o.jsx(oe,{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(Utn,{})})}),o.jsx(ge,{as:"span",variant:"ui-sm",className:"text-neutral3 w-20 justify-self-end text-right tabular-nums",children:rOs(e.durationMs)})]},`timeline-item-${e.stepId}-${t}`)};function cOs(){const{steps:e}=u4(),{selectedStepId:t,hoverStepId:n,setSelectedStepId:r,setHoverStepId:s}=JH(),[a,i]=g.useState(()=>Date.now()),[l,c]=g.useState(!1),[u,d]=g.useState(null),f=g.useRef(null);e0t(f,{enabled:!l});const h=sOs(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(Js,{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(lOs,{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:qnt(y.step.input)}),onOpenOutput:y=>d({type:"output",stepId:y.stepId,data:qnt(y.step.output)})},`timeline-item-${m.stepId}-${v}`))})]})}),o.jsx(vr,{open:!!u,onOpenChange:m=>!m&&d(null),children:u&&o.jsx(_Et,{data:u.data,title:`${eZt(u.stepId)} ${u.type==="input"?"input":"output"}`})})]})}const uOs=({workflowId:e,workflow:t,isLoading:n})=>{const{stepDetail:r}=UW();return o.jsxs("div",{className:"flex h-full min-h-0",children:[o.jsx("div",{className:"flex h-full min-h-0 flex-1 flex-col",children:o.jsxs("div",{className:"relative min-h-0 flex-1 p-2 pb-0",children:[o.jsx(oFt,{workflowId:e,workflow:t,isLoading:n}),o.jsx(Kks,{}),o.jsx(cOs,{})]})}),r&&o.jsx("div",{className:"border-border1 min-h-0 w-[420px] overflow-hidden border-l",children:o.jsx(Wks,{})})]})},Vnt=()=>{const{workflowId:e}=ur(),{data:t,isLoading:n,error:r}=xL(e);return r&&hs(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Es,{})}):r&&ps(r)?o.jsx("div",{className:"flex h-full items-center justify-center",children:o.jsx(Os,{resource:"workflows"})}):o.jsx(DCe,{children:o.jsx(uOs,{workflowId:e,workflow:t??void 0,isLoading:n})})};function dOs(e,t){if(e==null)return{};var n,r,s=jOt(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 A0e(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 fOs(e){if(Array.isArray(e))return A0e(e)}function hOs(e){if(typeof Symbol<"u"&&e[Symbol.iterator]!=null||e["@@iterator"]!=null)return Array.from(e)}function pOs(e,t){if(e){if(typeof e=="string")return A0e(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)?A0e(e,t):void 0}}function mOs(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
|
|
674
674
|
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function R0e(e){return fOs(e)||hOs(e)||pOs(e)||mOs()}function n3(e){"@babel/helpers - typeof";return n3=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},n3(e)}function gOs(e,t){if(n3(e)!="object"||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t);if(n3(r)!="object")return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return(t==="string"?String:Number)(e)}function vOs(e){var t=gOs(e,"string");return n3(t)=="symbol"?t:t+""}function tZt(e,t,n){return(t=vOs(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Hnt(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 ZT(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Hnt(Object(n),!0).forEach(function(r){tZt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Hnt(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}function yOs(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 Ooe={};function bOs(e){if(e.length===0||e.length===1)return e;var t=e.join(".");return Ooe[t]||(Ooe[t]=yOs(e)),Ooe[t]}function xOs(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=bOs(r);return s.reduce(function(a,i){return ZT(ZT({},a),n[i])},t)}function Wnt(e){return e.join(" ")}function wOs(e,t){var n=0;return function(r){return n+=1,r.map(function(s,a){return nZt({node:s,stylesheet:e,useInlineStyles:t,key:"code-segment-".concat(n,"-").concat(a)})})}}function nZt(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=wOs(n,a),h;if(!a)h=ZT(ZT({},l),{},{className:Wnt(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=ZT(ZT({},l),{},{className:Wnt(v)||void 0,style:xOs(l.className,Object.assign({},l.style,s),n)})}var y=f(t.children);return qe.createElement(u,oC({key:i},h),y)}}const SOs=(function(e,t){var n=e.listLanguages();return n.indexOf(t)!==-1});var kOs=["language","children","style","customStyle","codeTagProps","useInlineStyles","showLineNumbers","showInlineLineNumbers","startingLineNumber","lineNumberContainerStyle","lineNumberStyle","wrapLines","wrapLongLines","lineProps","renderer","PreTag","CodeTag","code","astGenerator"];function Znt(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 qw(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]!=null?arguments[t]:{};t%2?Znt(Object(n),!0).forEach(function(r){tZt(e,r,n[r])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Znt(Object(n)).forEach(function(r){Object.defineProperty(e,r,Object.getOwnPropertyDescriptor(n,r))})}return e}var OOs=/\n/g;function COs(e){return e.match(OOs)}function _Os(e){var t=e.lines,n=e.startingLineNumber,r=e.style;return t.map(function(s,a){var i=a+n;return qe.createElement("span",{key:"line-".concat(a),className:"react-syntax-highlighter-line-number",style:typeof r=="function"?r(i):r},"".concat(i,`
|
|
675
675
|
`))})}function EOs(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 qe.createElement("code",{style:Object.assign({},n,s)},_Os({lines:t.replace(/\n$/,"").split(`
|
|
676
676
|
`),style:i,startingLineNumber:l}))}function TOs(e){return"".concat(e.toString().length,".25em")}function rZt(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 sZt(e,t,n){var r={display:"inline-block",minWidth:TOs(n),paddingRight:"1em",textAlign:"right",userSelect:"none"},s=typeof e=="function"?e(t):e,a=qw(qw({},r),s);return a}function W9(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?qw({},typeof l=="function"?l(n):l):{};if(m.className=m.className?[].concat(R0e(m.className.trim().split(/\s+/)),R0e(u)):u,n&&a){var v=sZt(r,n,s);t.unshift(rZt(n,v))}return f&d&&(m.style=qw({display:"flex"},m.style)),{type:"element",tagName:"span",properties:m,children:t}}function aZt(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(W9({children:[s],className:R0e(new Set(t))}));else if(s.children){var a=t.concat(s.properties.className);aZt(s.children,a).forEach(function(i){return n.push(i)})}}return n}function jOs(e,t,n,r,s,a,i,l,c){var u,d=aZt(e.value),f=[],h=-1,p=0;function m(O,_){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return W9({children:O,lineNumber:_,lineNumberStyle:l,largestLineNumber:i,showInlineLineNumbers:s,lineProps:n,className:E,showLineNumbers:r,wrapLongLines:c,wrapLines:t})}function v(O,_){if(r&&_&&s){var E=sZt(l,_,i);O.unshift(rZt(_,E))}return O}function y(O,_){var E=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return t||E.length>0?m(O,_,E):v(O,_)}for(var b=function(){var _=d[p],E=_.children[0].value,T=COs(E);if(T){var N=E.split(`
|